PackageManagerService.java revision c6ea7fc45ef147fa9e9c4f424faa1628bf954534
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppInfo;
131import android.content.pm.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.EphemeralResponse;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManagerInternal;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.DisplayMetrics;
222import android.util.EventLog;
223import android.util.ExceptionUtils;
224import android.util.Log;
225import android.util.LogPrinter;
226import android.util.MathUtils;
227import android.util.PackageUtils;
228import android.util.Pair;
229import android.util.PrintStreamPrinter;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.util.SparseIntArray;
234import android.util.Xml;
235import android.util.jar.StrictJarFile;
236import android.view.Display;
237
238import com.android.internal.R;
239import com.android.internal.annotations.GuardedBy;
240import com.android.internal.app.IMediaContainerService;
241import com.android.internal.app.ResolverActivity;
242import com.android.internal.content.NativeLibraryHelper;
243import com.android.internal.content.PackageHelper;
244import com.android.internal.logging.MetricsLogger;
245import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
246import com.android.internal.os.IParcelFileDescriptorFactory;
247import com.android.internal.os.RoSystemProperties;
248import com.android.internal.os.SomeArgs;
249import com.android.internal.os.Zygote;
250import com.android.internal.telephony.CarrierAppUtils;
251import com.android.internal.util.ArrayUtils;
252import com.android.internal.util.FastPrintWriter;
253import com.android.internal.util.FastXmlSerializer;
254import com.android.internal.util.IndentingPrintWriter;
255import com.android.internal.util.Preconditions;
256import com.android.internal.util.XmlUtils;
257import com.android.server.AttributeCache;
258import com.android.server.BackgroundDexOptJobService;
259import com.android.server.EventLogTags;
260import com.android.server.FgThread;
261import com.android.server.IntentResolver;
262import com.android.server.LocalServices;
263import com.android.server.ServiceThread;
264import com.android.server.SystemConfig;
265import com.android.server.Watchdog;
266import com.android.server.net.NetworkPolicyManagerInternal;
267import com.android.server.pm.Installer.InstallerException;
268import com.android.server.pm.PermissionsState.PermissionState;
269import com.android.server.pm.Settings.DatabaseVersion;
270import com.android.server.pm.Settings.VersionInfo;
271import com.android.server.pm.dex.DexManager;
272import com.android.server.storage.DeviceStorageMonitorInternal;
273
274import dalvik.system.CloseGuard;
275import dalvik.system.DexFile;
276import dalvik.system.VMRuntime;
277
278import libcore.io.IoUtils;
279import libcore.util.EmptyArray;
280
281import org.xmlpull.v1.XmlPullParser;
282import org.xmlpull.v1.XmlPullParserException;
283import org.xmlpull.v1.XmlSerializer;
284
285import java.io.BufferedOutputStream;
286import java.io.BufferedReader;
287import java.io.ByteArrayInputStream;
288import java.io.ByteArrayOutputStream;
289import java.io.File;
290import java.io.FileDescriptor;
291import java.io.FileInputStream;
292import java.io.FileNotFoundException;
293import java.io.FileOutputStream;
294import java.io.FileReader;
295import java.io.FilenameFilter;
296import java.io.IOException;
297import java.io.PrintWriter;
298import java.nio.charset.StandardCharsets;
299import java.security.DigestInputStream;
300import java.security.MessageDigest;
301import java.security.NoSuchAlgorithmException;
302import java.security.PublicKey;
303import java.security.SecureRandom;
304import java.security.cert.Certificate;
305import java.security.cert.CertificateEncodingException;
306import java.security.cert.CertificateException;
307import java.text.SimpleDateFormat;
308import java.util.ArrayList;
309import java.util.Arrays;
310import java.util.Collection;
311import java.util.Collections;
312import java.util.Comparator;
313import java.util.Date;
314import java.util.HashSet;
315import java.util.HashMap;
316import java.util.Iterator;
317import java.util.List;
318import java.util.Map;
319import java.util.Objects;
320import java.util.Set;
321import java.util.concurrent.CountDownLatch;
322import java.util.concurrent.TimeUnit;
323import java.util.concurrent.atomic.AtomicBoolean;
324import java.util.concurrent.atomic.AtomicInteger;
325
326/**
327 * Keep track of all those APKs everywhere.
328 * <p>
329 * Internally there are two important locks:
330 * <ul>
331 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
332 * and other related state. It is a fine-grained lock that should only be held
333 * momentarily, as it's one of the most contended locks in the system.
334 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
335 * operations typically involve heavy lifting of application data on disk. Since
336 * {@code installd} is single-threaded, and it's operations can often be slow,
337 * this lock should never be acquired while already holding {@link #mPackages}.
338 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
339 * holding {@link #mInstallLock}.
340 * </ul>
341 * Many internal methods rely on the caller to hold the appropriate locks, and
342 * this contract is expressed through method name suffixes:
343 * <ul>
344 * <li>fooLI(): the caller must hold {@link #mInstallLock}
345 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
346 * being modified must be frozen
347 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
348 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
349 * </ul>
350 * <p>
351 * Because this class is very central to the platform's security; please run all
352 * CTS and unit tests whenever making modifications:
353 *
354 * <pre>
355 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
356 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
357 * </pre>
358 */
359public class PackageManagerService extends IPackageManager.Stub {
360    static final String TAG = "PackageManager";
361    static final boolean DEBUG_SETTINGS = false;
362    static final boolean DEBUG_PREFERRED = false;
363    static final boolean DEBUG_UPGRADE = false;
364    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
365    private static final boolean DEBUG_BACKUP = false;
366    private static final boolean DEBUG_INSTALL = false;
367    private static final boolean DEBUG_REMOVE = false;
368    private static final boolean DEBUG_BROADCASTS = false;
369    private static final boolean DEBUG_SHOW_INFO = false;
370    private static final boolean DEBUG_PACKAGE_INFO = false;
371    private static final boolean DEBUG_INTENT_MATCHING = false;
372    private static final boolean DEBUG_PACKAGE_SCANNING = false;
373    private static final boolean DEBUG_VERIFY = false;
374    private static final boolean DEBUG_FILTERS = false;
375
376    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
377    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
378    // user, but by default initialize to this.
379    public static final boolean DEBUG_DEXOPT = false;
380
381    private static final boolean DEBUG_ABI_SELECTION = false;
382    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
383    private static final boolean DEBUG_TRIAGED_MISSING = false;
384    private static final boolean DEBUG_APP_DATA = false;
385
386    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
387    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
388
389    private static final boolean DISABLE_EPHEMERAL_APPS = false;
390    private static final boolean HIDE_EPHEMERAL_APIS = false;
391
392    private static final boolean ENABLE_QUOTA =
393            SystemProperties.getBoolean("persist.fw.quota", false);
394
395    private static final int RADIO_UID = Process.PHONE_UID;
396    private static final int LOG_UID = Process.LOG_UID;
397    private static final int NFC_UID = Process.NFC_UID;
398    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
399    private static final int SHELL_UID = Process.SHELL_UID;
400
401    // Cap the size of permission trees that 3rd party apps can define
402    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
403
404    // Suffix used during package installation when copying/moving
405    // package apks to install directory.
406    private static final String INSTALL_PACKAGE_SUFFIX = "-";
407
408    static final int SCAN_NO_DEX = 1<<1;
409    static final int SCAN_FORCE_DEX = 1<<2;
410    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
411    static final int SCAN_NEW_INSTALL = 1<<4;
412    static final int SCAN_UPDATE_TIME = 1<<5;
413    static final int SCAN_BOOTING = 1<<6;
414    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
415    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
416    static final int SCAN_REPLACING = 1<<9;
417    static final int SCAN_REQUIRE_KNOWN = 1<<10;
418    static final int SCAN_MOVE = 1<<11;
419    static final int SCAN_INITIAL = 1<<12;
420    static final int SCAN_CHECK_ONLY = 1<<13;
421    static final int SCAN_DONT_KILL_APP = 1<<14;
422    static final int SCAN_IGNORE_FROZEN = 1<<15;
423    static final int REMOVE_CHATTY = 1<<16;
424    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
425
426    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
427
428    private static final int[] EMPTY_INT_ARRAY = new int[0];
429
430    /**
431     * Timeout (in milliseconds) after which the watchdog should declare that
432     * our handler thread is wedged.  The usual default for such things is one
433     * minute but we sometimes do very lengthy I/O operations on this thread,
434     * such as installing multi-gigabyte applications, so ours needs to be longer.
435     */
436    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
437
438    /**
439     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
440     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
441     * settings entry if available, otherwise we use the hardcoded default.  If it's been
442     * more than this long since the last fstrim, we force one during the boot sequence.
443     *
444     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
445     * one gets run at the next available charging+idle time.  This final mandatory
446     * no-fstrim check kicks in only of the other scheduling criteria is never met.
447     */
448    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
449
450    /**
451     * Whether verification is enabled by default.
452     */
453    private static final boolean DEFAULT_VERIFY_ENABLE = true;
454
455    /**
456     * The default maximum time to wait for the verification agent to return in
457     * milliseconds.
458     */
459    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
460
461    /**
462     * The default response for package verification timeout.
463     *
464     * This can be either PackageManager.VERIFICATION_ALLOW or
465     * PackageManager.VERIFICATION_REJECT.
466     */
467    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
468
469    static final String PLATFORM_PACKAGE_NAME = "android";
470
471    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
472
473    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
474            DEFAULT_CONTAINER_PACKAGE,
475            "com.android.defcontainer.DefaultContainerService");
476
477    private static final String KILL_APP_REASON_GIDS_CHANGED =
478            "permission grant or revoke changed gids";
479
480    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
481            "permissions revoked";
482
483    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
484
485    private static final String PACKAGE_SCHEME = "package";
486
487    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
488    /**
489     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
490     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
491     * VENDOR_OVERLAY_DIR.
492     */
493    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
494    /**
495     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
496     * is in VENDOR_OVERLAY_THEME_PROPERTY.
497     */
498    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
499            = "persist.vendor.overlay.theme";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** Special library name that skips shared libraries check during compilation. */
548    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
549
550    /** All dangerous permission names in the same order as the events in MetricsEvent */
551    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
552            Manifest.permission.READ_CALENDAR,
553            Manifest.permission.WRITE_CALENDAR,
554            Manifest.permission.CAMERA,
555            Manifest.permission.READ_CONTACTS,
556            Manifest.permission.WRITE_CONTACTS,
557            Manifest.permission.GET_ACCOUNTS,
558            Manifest.permission.ACCESS_FINE_LOCATION,
559            Manifest.permission.ACCESS_COARSE_LOCATION,
560            Manifest.permission.RECORD_AUDIO,
561            Manifest.permission.READ_PHONE_STATE,
562            Manifest.permission.CALL_PHONE,
563            Manifest.permission.READ_CALL_LOG,
564            Manifest.permission.WRITE_CALL_LOG,
565            Manifest.permission.ADD_VOICEMAIL,
566            Manifest.permission.USE_SIP,
567            Manifest.permission.PROCESS_OUTGOING_CALLS,
568            Manifest.permission.READ_CELL_BROADCASTS,
569            Manifest.permission.BODY_SENSORS,
570            Manifest.permission.SEND_SMS,
571            Manifest.permission.RECEIVE_SMS,
572            Manifest.permission.READ_SMS,
573            Manifest.permission.RECEIVE_WAP_PUSH,
574            Manifest.permission.RECEIVE_MMS,
575            Manifest.permission.READ_EXTERNAL_STORAGE,
576            Manifest.permission.WRITE_EXTERNAL_STORAGE,
577            Manifest.permission.READ_PHONE_NUMBER);
578
579
580    /**
581     * Version number for the package parser cache. Increment this whenever the format or
582     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
583     */
584    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
585
586    /**
587     * Whether the package parser cache is enabled.
588     */
589    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
590
591    final ServiceThread mHandlerThread;
592
593    final PackageHandler mHandler;
594
595    private final ProcessLoggingHandler mProcessLoggingHandler;
596
597    /**
598     * Messages for {@link #mHandler} that need to wait for system ready before
599     * being dispatched.
600     */
601    private ArrayList<Message> mPostSystemReadyMessages;
602
603    final int mSdkVersion = Build.VERSION.SDK_INT;
604
605    final Context mContext;
606    final boolean mFactoryTest;
607    final boolean mOnlyCore;
608    final DisplayMetrics mMetrics;
609    final int mDefParseFlags;
610    final String[] mSeparateProcesses;
611    final boolean mIsUpgrade;
612    final boolean mIsPreNUpgrade;
613    final boolean mIsPreNMR1Upgrade;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628    final File mEphemeralInstallDir;
629
630    /**
631     * Directory to which applications installed internally have their
632     * 32 bit native libraries copied.
633     */
634    private File mAppLib32InstallDir;
635
636    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
637    // apps.
638    final File mDrmAppPrivateInstallDir;
639
640    // ----------------------------------------------------------------
641
642    // Lock for state used when installing and doing other long running
643    // operations.  Methods that must be called with this lock held have
644    // the suffix "LI".
645    final Object mInstallLock = new Object();
646
647    // ----------------------------------------------------------------
648
649    // Keys are String (package name), values are Package.  This also serves
650    // as the lock for the global state.  Methods that must be called with
651    // this lock held have the prefix "LP".
652    @GuardedBy("mPackages")
653    final ArrayMap<String, PackageParser.Package> mPackages =
654            new ArrayMap<String, PackageParser.Package>();
655
656    final ArrayMap<String, Set<String>> mKnownCodebase =
657            new ArrayMap<String, Set<String>>();
658
659    // Tracks available target package names -> overlay package paths.
660    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
661        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    public static final class SharedLibraryEntry {
724        public final String path;
725        public final String apk;
726        public final SharedLibraryInfo info;
727
728        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
729                String declaringPackageName, int declaringPackageVersionCode) {
730            path = _path;
731            apk = _apk;
732            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
733                    declaringPackageName, declaringPackageVersionCode), null);
734        }
735    }
736
737    // Currently known shared libraries.
738    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
739    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
740            new ArrayMap<>();
741
742    // All available activities, for your resolving pleasure.
743    final ActivityIntentResolver mActivities =
744            new ActivityIntentResolver();
745
746    // All available receivers, for your resolving pleasure.
747    final ActivityIntentResolver mReceivers =
748            new ActivityIntentResolver();
749
750    // All available services, for your resolving pleasure.
751    final ServiceIntentResolver mServices = new ServiceIntentResolver();
752
753    // All available providers, for your resolving pleasure.
754    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
755
756    // Mapping from provider base names (first directory in content URI codePath)
757    // to the provider information.
758    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
759            new ArrayMap<String, PackageParser.Provider>();
760
761    // Mapping from instrumentation class names to info about them.
762    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
763            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
764
765    // Mapping from permission names to info about them.
766    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
767            new ArrayMap<String, PackageParser.PermissionGroup>();
768
769    // Packages whose data we have transfered into another package, thus
770    // should no longer exist.
771    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
772
773    // Broadcast actions that are only available to the system.
774    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
775
776    /** List of packages waiting for verification. */
777    final SparseArray<PackageVerificationState> mPendingVerification
778            = new SparseArray<PackageVerificationState>();
779
780    /** Set of packages associated with each app op permission. */
781    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
782
783    final PackageInstallerService mInstallerService;
784
785    private final PackageDexOptimizer mPackageDexOptimizer;
786    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
787    // is used by other apps).
788    private final DexManager mDexManager;
789
790    private AtomicInteger mNextMoveId = new AtomicInteger();
791    private final MoveCallbacks mMoveCallbacks;
792
793    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
794
795    // Cache of users who need badging.
796    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
797
798    /** Token for keys in mPendingVerification. */
799    private int mPendingVerificationToken = 0;
800
801    volatile boolean mSystemReady;
802    volatile boolean mSafeMode;
803    volatile boolean mHasSystemUidErrors;
804
805    ApplicationInfo mAndroidApplication;
806    final ActivityInfo mResolveActivity = new ActivityInfo();
807    final ResolveInfo mResolveInfo = new ResolveInfo();
808    ComponentName mResolveComponentName;
809    PackageParser.Package mPlatformPackage;
810    ComponentName mCustomResolverComponentName;
811
812    boolean mResolverReplaced = false;
813
814    private final @Nullable ComponentName mIntentFilterVerifierComponent;
815    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
816
817    private int mIntentFilterVerificationToken = 0;
818
819    /** The service connection to the ephemeral resolver */
820    final EphemeralResolverConnection mEphemeralResolverConnection;
821
822    /** Component used to install ephemeral applications */
823    ComponentName mEphemeralInstallerComponent;
824    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
825    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
826
827    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
828            = new SparseArray<IntentFilterVerificationState>();
829
830    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
831
832    // List of packages names to keep cached, even if they are uninstalled for all users
833    private List<String> mKeepUninstalledPackages;
834
835    private UserManagerInternal mUserManagerInternal;
836
837    private File mCacheDir;
838
839    private ArraySet<String> mPrivappPermissionsViolations;
840
841    private static class IFVerificationParams {
842        PackageParser.Package pkg;
843        boolean replacing;
844        int userId;
845        int verifierUid;
846
847        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
848                int _userId, int _verifierUid) {
849            pkg = _pkg;
850            replacing = _replacing;
851            userId = _userId;
852            replacing = _replacing;
853            verifierUid = _verifierUid;
854        }
855    }
856
857    private interface IntentFilterVerifier<T extends IntentFilter> {
858        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
859                                               T filter, String packageName);
860        void startVerifications(int userId);
861        void receiveVerificationResponse(int verificationId);
862    }
863
864    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
865        private Context mContext;
866        private ComponentName mIntentFilterVerifierComponent;
867        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
868
869        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
870            mContext = context;
871            mIntentFilterVerifierComponent = verifierComponent;
872        }
873
874        private String getDefaultScheme() {
875            return IntentFilter.SCHEME_HTTPS;
876        }
877
878        @Override
879        public void startVerifications(int userId) {
880            // Launch verifications requests
881            int count = mCurrentIntentFilterVerifications.size();
882            for (int n=0; n<count; n++) {
883                int verificationId = mCurrentIntentFilterVerifications.get(n);
884                final IntentFilterVerificationState ivs =
885                        mIntentFilterVerificationStates.get(verificationId);
886
887                String packageName = ivs.getPackageName();
888
889                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
890                final int filterCount = filters.size();
891                ArraySet<String> domainsSet = new ArraySet<>();
892                for (int m=0; m<filterCount; m++) {
893                    PackageParser.ActivityIntentInfo filter = filters.get(m);
894                    domainsSet.addAll(filter.getHostsList());
895                }
896                synchronized (mPackages) {
897                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
898                            packageName, domainsSet) != null) {
899                        scheduleWriteSettingsLocked();
900                    }
901                }
902                sendVerificationRequest(userId, verificationId, ivs);
903            }
904            mCurrentIntentFilterVerifications.clear();
905        }
906
907        private void sendVerificationRequest(int userId, int verificationId,
908                IntentFilterVerificationState ivs) {
909
910            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
911            verificationIntent.putExtra(
912                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
913                    verificationId);
914            verificationIntent.putExtra(
915                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
916                    getDefaultScheme());
917            verificationIntent.putExtra(
918                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
919                    ivs.getHostsString());
920            verificationIntent.putExtra(
921                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
922                    ivs.getPackageName());
923            verificationIntent.setComponent(mIntentFilterVerifierComponent);
924            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
925
926            UserHandle user = new UserHandle(userId);
927            mContext.sendBroadcastAsUser(verificationIntent, user);
928            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
929                    "Sending IntentFilter verification broadcast");
930        }
931
932        public void receiveVerificationResponse(int verificationId) {
933            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
934
935            final boolean verified = ivs.isVerified();
936
937            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
938            final int count = filters.size();
939            if (DEBUG_DOMAIN_VERIFICATION) {
940                Slog.i(TAG, "Received verification response " + verificationId
941                        + " for " + count + " filters, verified=" + verified);
942            }
943            for (int n=0; n<count; n++) {
944                PackageParser.ActivityIntentInfo filter = filters.get(n);
945                filter.setVerified(verified);
946
947                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
948                        + " verified with result:" + verified + " and hosts:"
949                        + ivs.getHostsString());
950            }
951
952            mIntentFilterVerificationStates.remove(verificationId);
953
954            final String packageName = ivs.getPackageName();
955            IntentFilterVerificationInfo ivi = null;
956
957            synchronized (mPackages) {
958                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
959            }
960            if (ivi == null) {
961                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
962                        + verificationId + " packageName:" + packageName);
963                return;
964            }
965            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
966                    "Updating IntentFilterVerificationInfo for package " + packageName
967                            +" verificationId:" + verificationId);
968
969            synchronized (mPackages) {
970                if (verified) {
971                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
972                } else {
973                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
974                }
975                scheduleWriteSettingsLocked();
976
977                final int userId = ivs.getUserId();
978                if (userId != UserHandle.USER_ALL) {
979                    final int userStatus =
980                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
981
982                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
983                    boolean needUpdate = false;
984
985                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
986                    // already been set by the User thru the Disambiguation dialog
987                    switch (userStatus) {
988                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
989                            if (verified) {
990                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
991                            } else {
992                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
993                            }
994                            needUpdate = true;
995                            break;
996
997                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
998                            if (verified) {
999                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1000                                needUpdate = true;
1001                            }
1002                            break;
1003
1004                        default:
1005                            // Nothing to do
1006                    }
1007
1008                    if (needUpdate) {
1009                        mSettings.updateIntentFilterVerificationStatusLPw(
1010                                packageName, updatedStatus, userId);
1011                        scheduleWritePackageRestrictionsLocked(userId);
1012                    }
1013                }
1014            }
1015        }
1016
1017        @Override
1018        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1019                    ActivityIntentInfo filter, String packageName) {
1020            if (!hasValidDomains(filter)) {
1021                return false;
1022            }
1023            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1024            if (ivs == null) {
1025                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1026                        packageName);
1027            }
1028            if (DEBUG_DOMAIN_VERIFICATION) {
1029                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1030            }
1031            ivs.addFilter(filter);
1032            return true;
1033        }
1034
1035        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1036                int userId, int verificationId, String packageName) {
1037            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1038                    verifierUid, userId, packageName);
1039            ivs.setPendingState();
1040            synchronized (mPackages) {
1041                mIntentFilterVerificationStates.append(verificationId, ivs);
1042                mCurrentIntentFilterVerifications.add(verificationId);
1043            }
1044            return ivs;
1045        }
1046    }
1047
1048    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1049        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1050                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1051                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1052    }
1053
1054    // Set of pending broadcasts for aggregating enable/disable of components.
1055    static class PendingPackageBroadcasts {
1056        // for each user id, a map of <package name -> components within that package>
1057        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1058
1059        public PendingPackageBroadcasts() {
1060            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1061        }
1062
1063        public ArrayList<String> get(int userId, String packageName) {
1064            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1065            return packages.get(packageName);
1066        }
1067
1068        public void put(int userId, String packageName, ArrayList<String> components) {
1069            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1070            packages.put(packageName, components);
1071        }
1072
1073        public void remove(int userId, String packageName) {
1074            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1075            if (packages != null) {
1076                packages.remove(packageName);
1077            }
1078        }
1079
1080        public void remove(int userId) {
1081            mUidMap.remove(userId);
1082        }
1083
1084        public int userIdCount() {
1085            return mUidMap.size();
1086        }
1087
1088        public int userIdAt(int n) {
1089            return mUidMap.keyAt(n);
1090        }
1091
1092        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1093            return mUidMap.get(userId);
1094        }
1095
1096        public int size() {
1097            // total number of pending broadcast entries across all userIds
1098            int num = 0;
1099            for (int i = 0; i< mUidMap.size(); i++) {
1100                num += mUidMap.valueAt(i).size();
1101            }
1102            return num;
1103        }
1104
1105        public void clear() {
1106            mUidMap.clear();
1107        }
1108
1109        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1110            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1111            if (map == null) {
1112                map = new ArrayMap<String, ArrayList<String>>();
1113                mUidMap.put(userId, map);
1114            }
1115            return map;
1116        }
1117    }
1118    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1119
1120    // Service Connection to remote media container service to copy
1121    // package uri's from external media onto secure containers
1122    // or internal storage.
1123    private IMediaContainerService mContainerService = null;
1124
1125    static final int SEND_PENDING_BROADCAST = 1;
1126    static final int MCS_BOUND = 3;
1127    static final int END_COPY = 4;
1128    static final int INIT_COPY = 5;
1129    static final int MCS_UNBIND = 6;
1130    static final int START_CLEANING_PACKAGE = 7;
1131    static final int FIND_INSTALL_LOC = 8;
1132    static final int POST_INSTALL = 9;
1133    static final int MCS_RECONNECT = 10;
1134    static final int MCS_GIVE_UP = 11;
1135    static final int UPDATED_MEDIA_STATUS = 12;
1136    static final int WRITE_SETTINGS = 13;
1137    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1138    static final int PACKAGE_VERIFIED = 15;
1139    static final int CHECK_PENDING_VERIFICATION = 16;
1140    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1141    static final int INTENT_FILTER_VERIFIED = 18;
1142    static final int WRITE_PACKAGE_LIST = 19;
1143    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1144
1145    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1146
1147    // Delay time in millisecs
1148    static final int BROADCAST_DELAY = 10 * 1000;
1149
1150    static UserManagerService sUserManager;
1151
1152    // Stores a list of users whose package restrictions file needs to be updated
1153    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1154
1155    final private DefaultContainerConnection mDefContainerConn =
1156            new DefaultContainerConnection();
1157    class DefaultContainerConnection implements ServiceConnection {
1158        public void onServiceConnected(ComponentName name, IBinder service) {
1159            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1160            final IMediaContainerService imcs = IMediaContainerService.Stub
1161                    .asInterface(Binder.allowBlocking(service));
1162            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1163        }
1164
1165        public void onServiceDisconnected(ComponentName name) {
1166            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1167        }
1168    }
1169
1170    // Recordkeeping of restore-after-install operations that are currently in flight
1171    // between the Package Manager and the Backup Manager
1172    static class PostInstallData {
1173        public InstallArgs args;
1174        public PackageInstalledInfo res;
1175
1176        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1177            args = _a;
1178            res = _r;
1179        }
1180    }
1181
1182    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1183    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1184
1185    // XML tags for backup/restore of various bits of state
1186    private static final String TAG_PREFERRED_BACKUP = "pa";
1187    private static final String TAG_DEFAULT_APPS = "da";
1188    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1189
1190    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1191    private static final String TAG_ALL_GRANTS = "rt-grants";
1192    private static final String TAG_GRANT = "grant";
1193    private static final String ATTR_PACKAGE_NAME = "pkg";
1194
1195    private static final String TAG_PERMISSION = "perm";
1196    private static final String ATTR_PERMISSION_NAME = "name";
1197    private static final String ATTR_IS_GRANTED = "g";
1198    private static final String ATTR_USER_SET = "set";
1199    private static final String ATTR_USER_FIXED = "fixed";
1200    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1201
1202    // System/policy permission grants are not backed up
1203    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1204            FLAG_PERMISSION_POLICY_FIXED
1205            | FLAG_PERMISSION_SYSTEM_FIXED
1206            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1207
1208    // And we back up these user-adjusted states
1209    private static final int USER_RUNTIME_GRANT_MASK =
1210            FLAG_PERMISSION_USER_SET
1211            | FLAG_PERMISSION_USER_FIXED
1212            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1213
1214    final @Nullable String mRequiredVerifierPackage;
1215    final @NonNull String mRequiredInstallerPackage;
1216    final @NonNull String mRequiredUninstallerPackage;
1217    final @Nullable String mSetupWizardPackage;
1218    final @Nullable String mStorageManagerPackage;
1219    final @NonNull String mServicesSystemSharedLibraryPackageName;
1220    final @NonNull String mSharedSystemSharedLibraryPackageName;
1221
1222    final boolean mPermissionReviewRequired;
1223
1224    private final PackageUsage mPackageUsage = new PackageUsage();
1225    private final CompilerStats mCompilerStats = new CompilerStats();
1226
1227    class PackageHandler extends Handler {
1228        private boolean mBound = false;
1229        final ArrayList<HandlerParams> mPendingInstalls =
1230            new ArrayList<HandlerParams>();
1231
1232        private boolean connectToService() {
1233            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1234                    " DefaultContainerService");
1235            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1236            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1237            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1238                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1239                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1240                mBound = true;
1241                return true;
1242            }
1243            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1244            return false;
1245        }
1246
1247        private void disconnectService() {
1248            mContainerService = null;
1249            mBound = false;
1250            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1251            mContext.unbindService(mDefContainerConn);
1252            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1253        }
1254
1255        PackageHandler(Looper looper) {
1256            super(looper);
1257        }
1258
1259        public void handleMessage(Message msg) {
1260            try {
1261                doHandleMessage(msg);
1262            } finally {
1263                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1264            }
1265        }
1266
1267        void doHandleMessage(Message msg) {
1268            switch (msg.what) {
1269                case INIT_COPY: {
1270                    HandlerParams params = (HandlerParams) msg.obj;
1271                    int idx = mPendingInstalls.size();
1272                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1273                    // If a bind was already initiated we dont really
1274                    // need to do anything. The pending install
1275                    // will be processed later on.
1276                    if (!mBound) {
1277                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1278                                System.identityHashCode(mHandler));
1279                        // If this is the only one pending we might
1280                        // have to bind to the service again.
1281                        if (!connectToService()) {
1282                            Slog.e(TAG, "Failed to bind to media container service");
1283                            params.serviceError();
1284                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1285                                    System.identityHashCode(mHandler));
1286                            if (params.traceMethod != null) {
1287                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1288                                        params.traceCookie);
1289                            }
1290                            return;
1291                        } else {
1292                            // Once we bind to the service, the first
1293                            // pending request will be processed.
1294                            mPendingInstalls.add(idx, params);
1295                        }
1296                    } else {
1297                        mPendingInstalls.add(idx, params);
1298                        // Already bound to the service. Just make
1299                        // sure we trigger off processing the first request.
1300                        if (idx == 0) {
1301                            mHandler.sendEmptyMessage(MCS_BOUND);
1302                        }
1303                    }
1304                    break;
1305                }
1306                case MCS_BOUND: {
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1308                    if (msg.obj != null) {
1309                        mContainerService = (IMediaContainerService) msg.obj;
1310                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1311                                System.identityHashCode(mHandler));
1312                    }
1313                    if (mContainerService == null) {
1314                        if (!mBound) {
1315                            // Something seriously wrong since we are not bound and we are not
1316                            // waiting for connection. Bail out.
1317                            Slog.e(TAG, "Cannot bind to media container service");
1318                            for (HandlerParams params : mPendingInstalls) {
1319                                // Indicate service bind error
1320                                params.serviceError();
1321                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1322                                        System.identityHashCode(params));
1323                                if (params.traceMethod != null) {
1324                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1325                                            params.traceMethod, params.traceCookie);
1326                                }
1327                                return;
1328                            }
1329                            mPendingInstalls.clear();
1330                        } else {
1331                            Slog.w(TAG, "Waiting to connect to media container service");
1332                        }
1333                    } else if (mPendingInstalls.size() > 0) {
1334                        HandlerParams params = mPendingInstalls.get(0);
1335                        if (params != null) {
1336                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1337                                    System.identityHashCode(params));
1338                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1339                            if (params.startCopy()) {
1340                                // We are done...  look for more work or to
1341                                // go idle.
1342                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1343                                        "Checking for more work or unbind...");
1344                                // Delete pending install
1345                                if (mPendingInstalls.size() > 0) {
1346                                    mPendingInstalls.remove(0);
1347                                }
1348                                if (mPendingInstalls.size() == 0) {
1349                                    if (mBound) {
1350                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1351                                                "Posting delayed MCS_UNBIND");
1352                                        removeMessages(MCS_UNBIND);
1353                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1354                                        // Unbind after a little delay, to avoid
1355                                        // continual thrashing.
1356                                        sendMessageDelayed(ubmsg, 10000);
1357                                    }
1358                                } else {
1359                                    // There are more pending requests in queue.
1360                                    // Just post MCS_BOUND message to trigger processing
1361                                    // of next pending install.
1362                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1363                                            "Posting MCS_BOUND for next work");
1364                                    mHandler.sendEmptyMessage(MCS_BOUND);
1365                                }
1366                            }
1367                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1368                        }
1369                    } else {
1370                        // Should never happen ideally.
1371                        Slog.w(TAG, "Empty queue");
1372                    }
1373                    break;
1374                }
1375                case MCS_RECONNECT: {
1376                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1377                    if (mPendingInstalls.size() > 0) {
1378                        if (mBound) {
1379                            disconnectService();
1380                        }
1381                        if (!connectToService()) {
1382                            Slog.e(TAG, "Failed to bind to media container service");
1383                            for (HandlerParams params : mPendingInstalls) {
1384                                // Indicate service bind error
1385                                params.serviceError();
1386                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1387                                        System.identityHashCode(params));
1388                            }
1389                            mPendingInstalls.clear();
1390                        }
1391                    }
1392                    break;
1393                }
1394                case MCS_UNBIND: {
1395                    // If there is no actual work left, then time to unbind.
1396                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1397
1398                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1399                        if (mBound) {
1400                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1401
1402                            disconnectService();
1403                        }
1404                    } else if (mPendingInstalls.size() > 0) {
1405                        // There are more pending requests in queue.
1406                        // Just post MCS_BOUND message to trigger processing
1407                        // of next pending install.
1408                        mHandler.sendEmptyMessage(MCS_BOUND);
1409                    }
1410
1411                    break;
1412                }
1413                case MCS_GIVE_UP: {
1414                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1415                    HandlerParams params = mPendingInstalls.remove(0);
1416                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1417                            System.identityHashCode(params));
1418                    break;
1419                }
1420                case SEND_PENDING_BROADCAST: {
1421                    String packages[];
1422                    ArrayList<String> components[];
1423                    int size = 0;
1424                    int uids[];
1425                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426                    synchronized (mPackages) {
1427                        if (mPendingBroadcasts == null) {
1428                            return;
1429                        }
1430                        size = mPendingBroadcasts.size();
1431                        if (size <= 0) {
1432                            // Nothing to be done. Just return
1433                            return;
1434                        }
1435                        packages = new String[size];
1436                        components = new ArrayList[size];
1437                        uids = new int[size];
1438                        int i = 0;  // filling out the above arrays
1439
1440                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1441                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1442                            Iterator<Map.Entry<String, ArrayList<String>>> it
1443                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1444                                            .entrySet().iterator();
1445                            while (it.hasNext() && i < size) {
1446                                Map.Entry<String, ArrayList<String>> ent = it.next();
1447                                packages[i] = ent.getKey();
1448                                components[i] = ent.getValue();
1449                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1450                                uids[i] = (ps != null)
1451                                        ? UserHandle.getUid(packageUserId, ps.appId)
1452                                        : -1;
1453                                i++;
1454                            }
1455                        }
1456                        size = i;
1457                        mPendingBroadcasts.clear();
1458                    }
1459                    // Send broadcasts
1460                    for (int i = 0; i < size; i++) {
1461                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1462                    }
1463                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1464                    break;
1465                }
1466                case START_CLEANING_PACKAGE: {
1467                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1468                    final String packageName = (String)msg.obj;
1469                    final int userId = msg.arg1;
1470                    final boolean andCode = msg.arg2 != 0;
1471                    synchronized (mPackages) {
1472                        if (userId == UserHandle.USER_ALL) {
1473                            int[] users = sUserManager.getUserIds();
1474                            for (int user : users) {
1475                                mSettings.addPackageToCleanLPw(
1476                                        new PackageCleanItem(user, packageName, andCode));
1477                            }
1478                        } else {
1479                            mSettings.addPackageToCleanLPw(
1480                                    new PackageCleanItem(userId, packageName, andCode));
1481                        }
1482                    }
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                    startCleaningPackages();
1485                } break;
1486                case POST_INSTALL: {
1487                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1488
1489                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1490                    final boolean didRestore = (msg.arg2 != 0);
1491                    mRunningInstalls.delete(msg.arg1);
1492
1493                    if (data != null) {
1494                        InstallArgs args = data.args;
1495                        PackageInstalledInfo parentRes = data.res;
1496
1497                        final boolean grantPermissions = (args.installFlags
1498                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1499                        final boolean killApp = (args.installFlags
1500                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1501                        final String[] grantedPermissions = args.installGrantPermissions;
1502
1503                        // Handle the parent package
1504                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1505                                grantedPermissions, didRestore, args.installerPackageName,
1506                                args.observer);
1507
1508                        // Handle the child packages
1509                        final int childCount = (parentRes.addedChildPackages != null)
1510                                ? parentRes.addedChildPackages.size() : 0;
1511                        for (int i = 0; i < childCount; i++) {
1512                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1513                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1514                                    grantedPermissions, false, args.installerPackageName,
1515                                    args.observer);
1516                        }
1517
1518                        // Log tracing if needed
1519                        if (args.traceMethod != null) {
1520                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1521                                    args.traceCookie);
1522                        }
1523                    } else {
1524                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1525                    }
1526
1527                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1528                } break;
1529                case UPDATED_MEDIA_STATUS: {
1530                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1531                    boolean reportStatus = msg.arg1 == 1;
1532                    boolean doGc = msg.arg2 == 1;
1533                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1534                    if (doGc) {
1535                        // Force a gc to clear up stale containers.
1536                        Runtime.getRuntime().gc();
1537                    }
1538                    if (msg.obj != null) {
1539                        @SuppressWarnings("unchecked")
1540                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1541                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1542                        // Unload containers
1543                        unloadAllContainers(args);
1544                    }
1545                    if (reportStatus) {
1546                        try {
1547                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                    "Invoking StorageManagerService call back");
1549                            PackageHelper.getStorageManager().finishMediaUpdate();
1550                        } catch (RemoteException e) {
1551                            Log.e(TAG, "StorageManagerService not running?");
1552                        }
1553                    }
1554                } break;
1555                case WRITE_SETTINGS: {
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1557                    synchronized (mPackages) {
1558                        removeMessages(WRITE_SETTINGS);
1559                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1560                        mSettings.writeLPr();
1561                        mDirtyUsers.clear();
1562                    }
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1564                } break;
1565                case WRITE_PACKAGE_RESTRICTIONS: {
1566                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1567                    synchronized (mPackages) {
1568                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1569                        for (int userId : mDirtyUsers) {
1570                            mSettings.writePackageRestrictionsLPr(userId);
1571                        }
1572                        mDirtyUsers.clear();
1573                    }
1574                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1575                } break;
1576                case WRITE_PACKAGE_LIST: {
1577                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1578                    synchronized (mPackages) {
1579                        removeMessages(WRITE_PACKAGE_LIST);
1580                        mSettings.writePackageListLPr(msg.arg1);
1581                    }
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                } break;
1584                case CHECK_PENDING_VERIFICATION: {
1585                    final int verificationId = msg.arg1;
1586                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1587
1588                    if ((state != null) && !state.timeoutExtended()) {
1589                        final InstallArgs args = state.getInstallArgs();
1590                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1591
1592                        Slog.i(TAG, "Verification timed out for " + originUri);
1593                        mPendingVerification.remove(verificationId);
1594
1595                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1596
1597                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1598                            Slog.i(TAG, "Continuing with installation of " + originUri);
1599                            state.setVerifierResponse(Binder.getCallingUid(),
1600                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    PackageManager.VERIFICATION_ALLOW,
1603                                    state.getInstallArgs().getUser());
1604                            try {
1605                                ret = args.copyApk(mContainerService, true);
1606                            } catch (RemoteException e) {
1607                                Slog.e(TAG, "Could not contact the ContainerService");
1608                            }
1609                        } else {
1610                            broadcastPackageVerified(verificationId, originUri,
1611                                    PackageManager.VERIFICATION_REJECT,
1612                                    state.getInstallArgs().getUser());
1613                        }
1614
1615                        Trace.asyncTraceEnd(
1616                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1617
1618                        processPendingInstall(args, ret);
1619                        mHandler.sendEmptyMessage(MCS_UNBIND);
1620                    }
1621                    break;
1622                }
1623                case PACKAGE_VERIFIED: {
1624                    final int verificationId = msg.arg1;
1625
1626                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1627                    if (state == null) {
1628                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1629                        break;
1630                    }
1631
1632                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1633
1634                    state.setVerifierResponse(response.callerUid, response.code);
1635
1636                    if (state.isVerificationComplete()) {
1637                        mPendingVerification.remove(verificationId);
1638
1639                        final InstallArgs args = state.getInstallArgs();
1640                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1641
1642                        int ret;
1643                        if (state.isInstallAllowed()) {
1644                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1645                            broadcastPackageVerified(verificationId, originUri,
1646                                    response.code, state.getInstallArgs().getUser());
1647                            try {
1648                                ret = args.copyApk(mContainerService, true);
1649                            } catch (RemoteException e) {
1650                                Slog.e(TAG, "Could not contact the ContainerService");
1651                            }
1652                        } else {
1653                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1654                        }
1655
1656                        Trace.asyncTraceEnd(
1657                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1658
1659                        processPendingInstall(args, ret);
1660                        mHandler.sendEmptyMessage(MCS_UNBIND);
1661                    }
1662
1663                    break;
1664                }
1665                case START_INTENT_FILTER_VERIFICATIONS: {
1666                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1667                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1668                            params.replacing, params.pkg);
1669                    break;
1670                }
1671                case INTENT_FILTER_VERIFIED: {
1672                    final int verificationId = msg.arg1;
1673
1674                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1675                            verificationId);
1676                    if (state == null) {
1677                        Slog.w(TAG, "Invalid IntentFilter verification token "
1678                                + verificationId + " received");
1679                        break;
1680                    }
1681
1682                    final int userId = state.getUserId();
1683
1684                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1685                            "Processing IntentFilter verification with token:"
1686                            + verificationId + " and userId:" + userId);
1687
1688                    final IntentFilterVerificationResponse response =
1689                            (IntentFilterVerificationResponse) msg.obj;
1690
1691                    state.setVerifierResponse(response.callerUid, response.code);
1692
1693                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1694                            "IntentFilter verification with token:" + verificationId
1695                            + " and userId:" + userId
1696                            + " is settings verifier response with response code:"
1697                            + response.code);
1698
1699                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1700                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1701                                + response.getFailedDomainsString());
1702                    }
1703
1704                    if (state.isVerificationComplete()) {
1705                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1706                    } else {
1707                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1708                                "IntentFilter verification with token:" + verificationId
1709                                + " was not said to be complete");
1710                    }
1711
1712                    break;
1713                }
1714                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1715                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1716                            mEphemeralResolverConnection,
1717                            (EphemeralRequest) msg.obj,
1718                            mEphemeralInstallerActivity,
1719                            mHandler);
1720                }
1721            }
1722        }
1723    }
1724
1725    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1726            boolean killApp, String[] grantedPermissions,
1727            boolean launchedForRestore, String installerPackage,
1728            IPackageInstallObserver2 installObserver) {
1729        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1730            // Send the removed broadcasts
1731            if (res.removedInfo != null) {
1732                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1733            }
1734
1735            // Now that we successfully installed the package, grant runtime
1736            // permissions if requested before broadcasting the install. Also
1737            // for legacy apps in permission review mode we clear the permission
1738            // review flag which is used to emulate runtime permissions for
1739            // legacy apps.
1740            if (grantPermissions) {
1741                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1742            }
1743
1744            final boolean update = res.removedInfo != null
1745                    && res.removedInfo.removedPackage != null;
1746
1747            // If this is the first time we have child packages for a disabled privileged
1748            // app that had no children, we grant requested runtime permissions to the new
1749            // children if the parent on the system image had them already granted.
1750            if (res.pkg.parentPackage != null) {
1751                synchronized (mPackages) {
1752                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1753                }
1754            }
1755
1756            synchronized (mPackages) {
1757                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1758            }
1759
1760            final String packageName = res.pkg.applicationInfo.packageName;
1761
1762            // Determine the set of users who are adding this package for
1763            // the first time vs. those who are seeing an update.
1764            int[] firstUsers = EMPTY_INT_ARRAY;
1765            int[] updateUsers = EMPTY_INT_ARRAY;
1766            if (res.origUsers == null || res.origUsers.length == 0) {
1767                firstUsers = res.newUsers;
1768            } else {
1769                for (int newUser : res.newUsers) {
1770                    boolean isNew = true;
1771                    for (int origUser : res.origUsers) {
1772                        if (origUser == newUser) {
1773                            isNew = false;
1774                            break;
1775                        }
1776                    }
1777                    if (isNew) {
1778                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1779                    } else {
1780                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1781                    }
1782                }
1783            }
1784
1785            // Send installed broadcasts if the install/update is not ephemeral
1786            // and the package is not a static shared lib.
1787            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1788                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1789
1790                // Send added for users that see the package for the first time
1791                // sendPackageAddedForNewUsers also deals with system apps
1792                int appId = UserHandle.getAppId(res.uid);
1793                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1794                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1795
1796                // Send added for users that don't see the package for the first time
1797                Bundle extras = new Bundle(1);
1798                extras.putInt(Intent.EXTRA_UID, res.uid);
1799                if (update) {
1800                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1801                }
1802                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1803                        extras, 0 /*flags*/, null /*targetPackage*/,
1804                        null /*finishedReceiver*/, updateUsers);
1805
1806                // Send replaced for users that don't see the package for the first time
1807                if (update) {
1808                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1809                            packageName, extras, 0 /*flags*/,
1810                            null /*targetPackage*/, null /*finishedReceiver*/,
1811                            updateUsers);
1812                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1813                            null /*package*/, null /*extras*/, 0 /*flags*/,
1814                            packageName /*targetPackage*/,
1815                            null /*finishedReceiver*/, updateUsers);
1816                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1817                    // First-install and we did a restore, so we're responsible for the
1818                    // first-launch broadcast.
1819                    if (DEBUG_BACKUP) {
1820                        Slog.i(TAG, "Post-restore of " + packageName
1821                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1822                    }
1823                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1824                }
1825
1826                // Send broadcast package appeared if forward locked/external for all users
1827                // treat asec-hosted packages like removable media on upgrade
1828                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1829                    if (DEBUG_INSTALL) {
1830                        Slog.i(TAG, "upgrading pkg " + res.pkg
1831                                + " is ASEC-hosted -> AVAILABLE");
1832                    }
1833                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1834                    ArrayList<String> pkgList = new ArrayList<>(1);
1835                    pkgList.add(packageName);
1836                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1837                }
1838            }
1839
1840            // Work that needs to happen on first install within each user
1841            if (firstUsers != null && firstUsers.length > 0) {
1842                synchronized (mPackages) {
1843                    for (int userId : firstUsers) {
1844                        // If this app is a browser and it's newly-installed for some
1845                        // users, clear any default-browser state in those users. The
1846                        // app's nature doesn't depend on the user, so we can just check
1847                        // its browser nature in any user and generalize.
1848                        if (packageIsBrowser(packageName, userId)) {
1849                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1850                        }
1851
1852                        // We may also need to apply pending (restored) runtime
1853                        // permission grants within these users.
1854                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1855                    }
1856                }
1857            }
1858
1859            // Log current value of "unknown sources" setting
1860            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1861                    getUnknownSourcesSettings());
1862
1863            // Force a gc to clear up things
1864            Runtime.getRuntime().gc();
1865
1866            // Remove the replaced package's older resources safely now
1867            // We delete after a gc for applications  on sdcard.
1868            if (res.removedInfo != null && res.removedInfo.args != null) {
1869                synchronized (mInstallLock) {
1870                    res.removedInfo.args.doPostDeleteLI(true);
1871                }
1872            }
1873
1874            if (!isEphemeral(res.pkg)) {
1875                // Notify DexManager that the package was installed for new users.
1876                // The updated users should already be indexed and the package code paths
1877                // should not change.
1878                // Don't notify the manager for ephemeral apps as they are not expected to
1879                // survive long enough to benefit of background optimizations.
1880                for (int userId : firstUsers) {
1881                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1882                    mDexManager.notifyPackageInstalled(info, userId);
1883                }
1884            }
1885        }
1886
1887        // If someone is watching installs - notify them
1888        if (installObserver != null) {
1889            try {
1890                Bundle extras = extrasForInstallResult(res);
1891                installObserver.onPackageInstalled(res.name, res.returnCode,
1892                        res.returnMsg, extras);
1893            } catch (RemoteException e) {
1894                Slog.i(TAG, "Observer no longer exists.");
1895            }
1896        }
1897    }
1898
1899    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1900            PackageParser.Package pkg) {
1901        if (pkg.parentPackage == null) {
1902            return;
1903        }
1904        if (pkg.requestedPermissions == null) {
1905            return;
1906        }
1907        final PackageSetting disabledSysParentPs = mSettings
1908                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1909        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1910                || !disabledSysParentPs.isPrivileged()
1911                || (disabledSysParentPs.childPackageNames != null
1912                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1913            return;
1914        }
1915        final int[] allUserIds = sUserManager.getUserIds();
1916        final int permCount = pkg.requestedPermissions.size();
1917        for (int i = 0; i < permCount; i++) {
1918            String permission = pkg.requestedPermissions.get(i);
1919            BasePermission bp = mSettings.mPermissions.get(permission);
1920            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1921                continue;
1922            }
1923            for (int userId : allUserIds) {
1924                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1925                        permission, userId)) {
1926                    grantRuntimePermission(pkg.packageName, permission, userId);
1927                }
1928            }
1929        }
1930    }
1931
1932    private StorageEventListener mStorageListener = new StorageEventListener() {
1933        @Override
1934        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1935            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1936                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1937                    final String volumeUuid = vol.getFsUuid();
1938
1939                    // Clean up any users or apps that were removed or recreated
1940                    // while this volume was missing
1941                    sUserManager.reconcileUsers(volumeUuid);
1942                    reconcileApps(volumeUuid);
1943
1944                    // Clean up any install sessions that expired or were
1945                    // cancelled while this volume was missing
1946                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1947
1948                    loadPrivatePackages(vol);
1949
1950                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1951                    unloadPrivatePackages(vol);
1952                }
1953            }
1954
1955            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1956                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1957                    updateExternalMediaStatus(true, false);
1958                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1959                    updateExternalMediaStatus(false, false);
1960                }
1961            }
1962        }
1963
1964        @Override
1965        public void onVolumeForgotten(String fsUuid) {
1966            if (TextUtils.isEmpty(fsUuid)) {
1967                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1968                return;
1969            }
1970
1971            // Remove any apps installed on the forgotten volume
1972            synchronized (mPackages) {
1973                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1974                for (PackageSetting ps : packages) {
1975                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1976                    deletePackageVersioned(new VersionedPackage(ps.name,
1977                            PackageManager.VERSION_CODE_HIGHEST),
1978                            new LegacyPackageDeleteObserver(null).getBinder(),
1979                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1980                    // Try very hard to release any references to this package
1981                    // so we don't risk the system server being killed due to
1982                    // open FDs
1983                    AttributeCache.instance().removePackage(ps.name);
1984                }
1985
1986                mSettings.onVolumeForgotten(fsUuid);
1987                mSettings.writeLPr();
1988            }
1989        }
1990    };
1991
1992    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1993            String[] grantedPermissions) {
1994        for (int userId : userIds) {
1995            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1996        }
1997    }
1998
1999    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2000            String[] grantedPermissions) {
2001        SettingBase sb = (SettingBase) pkg.mExtras;
2002        if (sb == null) {
2003            return;
2004        }
2005
2006        PermissionsState permissionsState = sb.getPermissionsState();
2007
2008        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2009                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2010
2011        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2012                >= Build.VERSION_CODES.M;
2013
2014        for (String permission : pkg.requestedPermissions) {
2015            final BasePermission bp;
2016            synchronized (mPackages) {
2017                bp = mSettings.mPermissions.get(permission);
2018            }
2019            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2020                    && (grantedPermissions == null
2021                           || ArrayUtils.contains(grantedPermissions, permission))) {
2022                final int flags = permissionsState.getPermissionFlags(permission, userId);
2023                if (supportsRuntimePermissions) {
2024                    // Installer cannot change immutable permissions.
2025                    if ((flags & immutableFlags) == 0) {
2026                        grantRuntimePermission(pkg.packageName, permission, userId);
2027                    }
2028                } else if (mPermissionReviewRequired) {
2029                    // In permission review mode we clear the review flag when we
2030                    // are asked to install the app with all permissions granted.
2031                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2032                        updatePermissionFlags(permission, pkg.packageName,
2033                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2034                    }
2035                }
2036            }
2037        }
2038    }
2039
2040    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2041        Bundle extras = null;
2042        switch (res.returnCode) {
2043            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2044                extras = new Bundle();
2045                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2046                        res.origPermission);
2047                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2048                        res.origPackage);
2049                break;
2050            }
2051            case PackageManager.INSTALL_SUCCEEDED: {
2052                extras = new Bundle();
2053                extras.putBoolean(Intent.EXTRA_REPLACING,
2054                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2055                break;
2056            }
2057        }
2058        return extras;
2059    }
2060
2061    void scheduleWriteSettingsLocked() {
2062        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2063            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2064        }
2065    }
2066
2067    void scheduleWritePackageListLocked(int userId) {
2068        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2069            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2070            msg.arg1 = userId;
2071            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2072        }
2073    }
2074
2075    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2076        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2077        scheduleWritePackageRestrictionsLocked(userId);
2078    }
2079
2080    void scheduleWritePackageRestrictionsLocked(int userId) {
2081        final int[] userIds = (userId == UserHandle.USER_ALL)
2082                ? sUserManager.getUserIds() : new int[]{userId};
2083        for (int nextUserId : userIds) {
2084            if (!sUserManager.exists(nextUserId)) return;
2085            mDirtyUsers.add(nextUserId);
2086            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2087                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2088            }
2089        }
2090    }
2091
2092    public static PackageManagerService main(Context context, Installer installer,
2093            boolean factoryTest, boolean onlyCore) {
2094        // Self-check for initial settings.
2095        PackageManagerServiceCompilerMapping.checkProperties();
2096
2097        PackageManagerService m = new PackageManagerService(context, installer,
2098                factoryTest, onlyCore);
2099        m.enableSystemUserPackages();
2100        ServiceManager.addService("package", m);
2101        return m;
2102    }
2103
2104    private void enableSystemUserPackages() {
2105        if (!UserManager.isSplitSystemUser()) {
2106            return;
2107        }
2108        // For system user, enable apps based on the following conditions:
2109        // - app is whitelisted or belong to one of these groups:
2110        //   -- system app which has no launcher icons
2111        //   -- system app which has INTERACT_ACROSS_USERS permission
2112        //   -- system IME app
2113        // - app is not in the blacklist
2114        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2115        Set<String> enableApps = new ArraySet<>();
2116        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2117                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2118                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2119        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2120        enableApps.addAll(wlApps);
2121        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2122                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2123        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2124        enableApps.removeAll(blApps);
2125        Log.i(TAG, "Applications installed for system user: " + enableApps);
2126        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2127                UserHandle.SYSTEM);
2128        final int allAppsSize = allAps.size();
2129        synchronized (mPackages) {
2130            for (int i = 0; i < allAppsSize; i++) {
2131                String pName = allAps.get(i);
2132                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2133                // Should not happen, but we shouldn't be failing if it does
2134                if (pkgSetting == null) {
2135                    continue;
2136                }
2137                boolean install = enableApps.contains(pName);
2138                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2139                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2140                            + " for system user");
2141                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2142                }
2143            }
2144        }
2145    }
2146
2147    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2148        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2149                Context.DISPLAY_SERVICE);
2150        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2151    }
2152
2153    /**
2154     * Requests that files preopted on a secondary system partition be copied to the data partition
2155     * if possible.  Note that the actual copying of the files is accomplished by init for security
2156     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2157     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2158     */
2159    private static void requestCopyPreoptedFiles() {
2160        final int WAIT_TIME_MS = 100;
2161        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2162        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2163            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2164            // We will wait for up to 100 seconds.
2165            final long timeStart = SystemClock.uptimeMillis();
2166            final long timeEnd = timeStart + 100 * 1000;
2167            long timeNow = timeStart;
2168            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2169                try {
2170                    Thread.sleep(WAIT_TIME_MS);
2171                } catch (InterruptedException e) {
2172                    // Do nothing
2173                }
2174                timeNow = SystemClock.uptimeMillis();
2175                if (timeNow > timeEnd) {
2176                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2177                    Slog.wtf(TAG, "cppreopt did not finish!");
2178                    break;
2179                }
2180            }
2181
2182            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2183        }
2184    }
2185
2186    public PackageManagerService(Context context, Installer installer,
2187            boolean factoryTest, boolean onlyCore) {
2188        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2189        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2190                SystemClock.uptimeMillis());
2191
2192        if (mSdkVersion <= 0) {
2193            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2194        }
2195
2196        mContext = context;
2197
2198        mPermissionReviewRequired = context.getResources().getBoolean(
2199                R.bool.config_permissionReviewRequired);
2200
2201        mFactoryTest = factoryTest;
2202        mOnlyCore = onlyCore;
2203        mMetrics = new DisplayMetrics();
2204        mSettings = new Settings(mPackages);
2205        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2216                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2217
2218        String separateProcesses = SystemProperties.get("debug.separate_processes");
2219        if (separateProcesses != null && separateProcesses.length() > 0) {
2220            if ("*".equals(separateProcesses)) {
2221                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2222                mSeparateProcesses = null;
2223                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2224            } else {
2225                mDefParseFlags = 0;
2226                mSeparateProcesses = separateProcesses.split(",");
2227                Slog.w(TAG, "Running with debug.separate_processes: "
2228                        + separateProcesses);
2229            }
2230        } else {
2231            mDefParseFlags = 0;
2232            mSeparateProcesses = null;
2233        }
2234
2235        mInstaller = installer;
2236        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2237                "*dexopt*");
2238        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2239        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2240
2241        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2242                FgThread.get().getLooper());
2243
2244        getDefaultDisplayMetrics(context, mMetrics);
2245
2246        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2247        SystemConfig systemConfig = SystemConfig.getInstance();
2248        mGlobalGids = systemConfig.getGlobalGids();
2249        mSystemPermissions = systemConfig.getSystemPermissions();
2250        mAvailableFeatures = systemConfig.getAvailableFeatures();
2251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2252
2253        mProtectedPackages = new ProtectedPackages(mContext);
2254
2255        synchronized (mInstallLock) {
2256        // writer
2257        synchronized (mPackages) {
2258            mHandlerThread = new ServiceThread(TAG,
2259                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2260            mHandlerThread.start();
2261            mHandler = new PackageHandler(mHandlerThread.getLooper());
2262            mProcessLoggingHandler = new ProcessLoggingHandler();
2263            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2264
2265            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2266            mInstantAppRegistry = new InstantAppRegistry(this);
2267
2268            File dataDir = Environment.getDataDirectory();
2269            mAppInstallDir = new File(dataDir, "app");
2270            mAppLib32InstallDir = new File(dataDir, "app-lib");
2271            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2272            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2273            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2274            sUserManager = new UserManagerService(context, this,
2275                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2276
2277            // Propagate permission configuration in to package manager.
2278            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2279                    = systemConfig.getPermissions();
2280            for (int i=0; i<permConfig.size(); i++) {
2281                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2282                BasePermission bp = mSettings.mPermissions.get(perm.name);
2283                if (bp == null) {
2284                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2285                    mSettings.mPermissions.put(perm.name, bp);
2286                }
2287                if (perm.gids != null) {
2288                    bp.setGids(perm.gids, perm.perUser);
2289                }
2290            }
2291
2292            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2293            final int builtInLibCount = libConfig.size();
2294            for (int i = 0; i < builtInLibCount; i++) {
2295                String name = libConfig.keyAt(i);
2296                String path = libConfig.valueAt(i);
2297                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2298                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2299            }
2300
2301            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2302
2303            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2304            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2305            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2306
2307            // Clean up orphaned packages for which the code path doesn't exist
2308            // and they are an update to a system app - caused by bug/32321269
2309            final int packageSettingCount = mSettings.mPackages.size();
2310            for (int i = packageSettingCount - 1; i >= 0; i--) {
2311                PackageSetting ps = mSettings.mPackages.valueAt(i);
2312                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2313                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2314                    mSettings.mPackages.removeAt(i);
2315                    mSettings.enableSystemPackageLPw(ps.name);
2316                }
2317            }
2318
2319            if (mFirstBoot) {
2320                requestCopyPreoptedFiles();
2321            }
2322
2323            String customResolverActivity = Resources.getSystem().getString(
2324                    R.string.config_customResolverActivity);
2325            if (TextUtils.isEmpty(customResolverActivity)) {
2326                customResolverActivity = null;
2327            } else {
2328                mCustomResolverComponentName = ComponentName.unflattenFromString(
2329                        customResolverActivity);
2330            }
2331
2332            long startTime = SystemClock.uptimeMillis();
2333
2334            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2335                    startTime);
2336
2337            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2338            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2339
2340            if (bootClassPath == null) {
2341                Slog.w(TAG, "No BOOTCLASSPATH found!");
2342            }
2343
2344            if (systemServerClassPath == null) {
2345                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2346            }
2347
2348            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2349            final String[] dexCodeInstructionSets =
2350                    getDexCodeInstructionSets(
2351                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2352
2353            /**
2354             * Ensure all external libraries have had dexopt run on them.
2355             */
2356            if (mSharedLibraries.size() > 0) {
2357                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2358                // NOTE: For now, we're compiling these system "shared libraries"
2359                // (and framework jars) into all available architectures. It's possible
2360                // to compile them only when we come across an app that uses them (there's
2361                // already logic for that in scanPackageLI) but that adds some complexity.
2362                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2363                    final int libCount = mSharedLibraries.size();
2364                    for (int i = 0; i < libCount; i++) {
2365                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2366                        final int versionCount = versionedLib.size();
2367                        for (int j = 0; j < versionCount; j++) {
2368                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2369                            final String libPath = libEntry.path != null
2370                                    ? libEntry.path : libEntry.apk;
2371                            if (libPath == null) {
2372                                continue;
2373                            }
2374                            try {
2375                                // Shared libraries do not have profiles so we perform a full
2376                                // AOT compilation (if needed).
2377                                int dexoptNeeded = DexFile.getDexOptNeeded(
2378                                        libPath, dexCodeInstructionSet,
2379                                        getCompilerFilterForReason(REASON_SHARED_APK),
2380                                        false /* newProfile */);
2381                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2382                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2383                                            dexCodeInstructionSet, dexoptNeeded, null,
2384                                            DEXOPT_PUBLIC,
2385                                            getCompilerFilterForReason(REASON_SHARED_APK),
2386                                            StorageManager.UUID_PRIVATE_INTERNAL,
2387                                            SKIP_SHARED_LIBRARY_CHECK);
2388                                }
2389                            } catch (FileNotFoundException e) {
2390                                Slog.w(TAG, "Library not found: " + libPath);
2391                            } catch (IOException | InstallerException e) {
2392                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2393                                        + e.getMessage());
2394                            }
2395                        }
2396                    }
2397                }
2398                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2399            }
2400
2401            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2402
2403            final VersionInfo ver = mSettings.getInternalVersion();
2404            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2405
2406            // when upgrading from pre-M, promote system app permissions from install to runtime
2407            mPromoteSystemApps =
2408                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2409
2410            // When upgrading from pre-N, we need to handle package extraction like first boot,
2411            // as there is no profiling data available.
2412            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2413
2414            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2415
2416            // save off the names of pre-existing system packages prior to scanning; we don't
2417            // want to automatically grant runtime permissions for new system apps
2418            if (mPromoteSystemApps) {
2419                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2420                while (pkgSettingIter.hasNext()) {
2421                    PackageSetting ps = pkgSettingIter.next();
2422                    if (isSystemApp(ps)) {
2423                        mExistingSystemPackages.add(ps.name);
2424                    }
2425                }
2426            }
2427
2428            mCacheDir = preparePackageParserCache(mIsUpgrade);
2429
2430            // Set flag to monitor and not change apk file paths when
2431            // scanning install directories.
2432            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2433
2434            if (mIsUpgrade || mFirstBoot) {
2435                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2436            }
2437
2438            // Collect vendor overlay packages. (Do this before scanning any apps.)
2439            // For security and version matching reason, only consider
2440            // overlay packages if they reside in the right directory.
2441            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2442            if (overlayThemeDir.isEmpty()) {
2443                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2444            }
2445            if (!overlayThemeDir.isEmpty()) {
2446                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2447                        | PackageParser.PARSE_IS_SYSTEM
2448                        | PackageParser.PARSE_IS_SYSTEM_DIR
2449                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2450            }
2451            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR
2454                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2455
2456            // Find base frameworks (resource packages without code).
2457            scanDirTracedLI(frameworkDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR
2460                    | PackageParser.PARSE_IS_PRIVILEGED,
2461                    scanFlags | SCAN_NO_DEX, 0);
2462
2463            // Collected privileged system packages.
2464            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2465            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR
2468                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2469
2470            // Collect ordinary system packages.
2471            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2472            scanDirTracedLI(systemAppDir, mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2475
2476            // Collect all vendor packages.
2477            File vendorAppDir = new File("/vendor/app");
2478            try {
2479                vendorAppDir = vendorAppDir.getCanonicalFile();
2480            } catch (IOException e) {
2481                // failed to look up canonical path, continue with original one
2482            }
2483            scanDirTracedLI(vendorAppDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2486
2487            // Collect all OEM packages.
2488            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2489            scanDirTracedLI(oemAppDir, mDefParseFlags
2490                    | PackageParser.PARSE_IS_SYSTEM
2491                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2492
2493            // Prune any system packages that no longer exist.
2494            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2495            if (!mOnlyCore) {
2496                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2497                while (psit.hasNext()) {
2498                    PackageSetting ps = psit.next();
2499
2500                    /*
2501                     * If this is not a system app, it can't be a
2502                     * disable system app.
2503                     */
2504                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2505                        continue;
2506                    }
2507
2508                    /*
2509                     * If the package is scanned, it's not erased.
2510                     */
2511                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2512                    if (scannedPkg != null) {
2513                        /*
2514                         * If the system app is both scanned and in the
2515                         * disabled packages list, then it must have been
2516                         * added via OTA. Remove it from the currently
2517                         * scanned package so the previously user-installed
2518                         * application can be scanned.
2519                         */
2520                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2521                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2522                                    + ps.name + "; removing system app.  Last known codePath="
2523                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2524                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2525                                    + scannedPkg.mVersionCode);
2526                            removePackageLI(scannedPkg, true);
2527                            mExpectingBetter.put(ps.name, ps.codePath);
2528                        }
2529
2530                        continue;
2531                    }
2532
2533                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2534                        psit.remove();
2535                        logCriticalInfo(Log.WARN, "System package " + ps.name
2536                                + " no longer exists; it's data will be wiped");
2537                        // Actual deletion of code and data will be handled by later
2538                        // reconciliation step
2539                    } else {
2540                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2541                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2542                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2543                        }
2544                    }
2545                }
2546            }
2547
2548            //look for any incomplete package installations
2549            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2550            for (int i = 0; i < deletePkgsList.size(); i++) {
2551                // Actual deletion of code and data will be handled by later
2552                // reconciliation step
2553                final String packageName = deletePkgsList.get(i).name;
2554                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2555                synchronized (mPackages) {
2556                    mSettings.removePackageLPw(packageName);
2557                }
2558            }
2559
2560            //delete tmp files
2561            deleteTempPackageFiles();
2562
2563            // Remove any shared userIDs that have no associated packages
2564            mSettings.pruneSharedUsersLPw();
2565
2566            if (!mOnlyCore) {
2567                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2568                        SystemClock.uptimeMillis());
2569                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2570
2571                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2572                        | PackageParser.PARSE_FORWARD_LOCK,
2573                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2574
2575                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2576                        | PackageParser.PARSE_IS_EPHEMERAL,
2577                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2578
2579                /**
2580                 * Remove disable package settings for any updated system
2581                 * apps that were removed via an OTA. If they're not a
2582                 * previously-updated app, remove them completely.
2583                 * Otherwise, just revoke their system-level permissions.
2584                 */
2585                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2586                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2587                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2588
2589                    String msg;
2590                    if (deletedPkg == null) {
2591                        msg = "Updated system package " + deletedAppName
2592                                + " no longer exists; it's data will be wiped";
2593                        // Actual deletion of code and data will be handled by later
2594                        // reconciliation step
2595                    } else {
2596                        msg = "Updated system app + " + deletedAppName
2597                                + " no longer present; removing system privileges for "
2598                                + deletedAppName;
2599
2600                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2601
2602                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2603                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2604                    }
2605                    logCriticalInfo(Log.WARN, msg);
2606                }
2607
2608                /**
2609                 * Make sure all system apps that we expected to appear on
2610                 * the userdata partition actually showed up. If they never
2611                 * appeared, crawl back and revive the system version.
2612                 */
2613                for (int i = 0; i < mExpectingBetter.size(); i++) {
2614                    final String packageName = mExpectingBetter.keyAt(i);
2615                    if (!mPackages.containsKey(packageName)) {
2616                        final File scanFile = mExpectingBetter.valueAt(i);
2617
2618                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2619                                + " but never showed up; reverting to system");
2620
2621                        int reparseFlags = mDefParseFlags;
2622                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2623                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2624                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2625                                    | PackageParser.PARSE_IS_PRIVILEGED;
2626                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2627                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2628                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2629                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2630                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2631                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2632                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2633                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2634                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2635                        } else {
2636                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2637                            continue;
2638                        }
2639
2640                        mSettings.enableSystemPackageLPw(packageName);
2641
2642                        try {
2643                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2644                        } catch (PackageManagerException e) {
2645                            Slog.e(TAG, "Failed to parse original system package: "
2646                                    + e.getMessage());
2647                        }
2648                    }
2649                }
2650            }
2651            mExpectingBetter.clear();
2652
2653            // Resolve the storage manager.
2654            mStorageManagerPackage = getStorageManagerPackageName();
2655
2656            // Resolve protected action filters. Only the setup wizard is allowed to
2657            // have a high priority filter for these actions.
2658            mSetupWizardPackage = getSetupWizardPackageName();
2659            if (mProtectedFilters.size() > 0) {
2660                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2661                    Slog.i(TAG, "No setup wizard;"
2662                        + " All protected intents capped to priority 0");
2663                }
2664                for (ActivityIntentInfo filter : mProtectedFilters) {
2665                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2666                        if (DEBUG_FILTERS) {
2667                            Slog.i(TAG, "Found setup wizard;"
2668                                + " allow priority " + filter.getPriority() + ";"
2669                                + " package: " + filter.activity.info.packageName
2670                                + " activity: " + filter.activity.className
2671                                + " priority: " + filter.getPriority());
2672                        }
2673                        // skip setup wizard; allow it to keep the high priority filter
2674                        continue;
2675                    }
2676                    Slog.w(TAG, "Protected action; cap priority to 0;"
2677                            + " package: " + filter.activity.info.packageName
2678                            + " activity: " + filter.activity.className
2679                            + " origPrio: " + filter.getPriority());
2680                    filter.setPriority(0);
2681                }
2682            }
2683            mDeferProtectedFilters = false;
2684            mProtectedFilters.clear();
2685
2686            // Now that we know all of the shared libraries, update all clients to have
2687            // the correct library paths.
2688            updateAllSharedLibrariesLPw(null);
2689
2690            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2691                // NOTE: We ignore potential failures here during a system scan (like
2692                // the rest of the commands above) because there's precious little we
2693                // can do about it. A settings error is reported, though.
2694                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2695            }
2696
2697            // Now that we know all the packages we are keeping,
2698            // read and update their last usage times.
2699            mPackageUsage.read(mPackages);
2700            mCompilerStats.read();
2701
2702            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2703                    SystemClock.uptimeMillis());
2704            Slog.i(TAG, "Time to scan packages: "
2705                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2706                    + " seconds");
2707
2708            // If the platform SDK has changed since the last time we booted,
2709            // we need to re-grant app permission to catch any new ones that
2710            // appear.  This is really a hack, and means that apps can in some
2711            // cases get permissions that the user didn't initially explicitly
2712            // allow...  it would be nice to have some better way to handle
2713            // this situation.
2714            int updateFlags = UPDATE_PERMISSIONS_ALL;
2715            if (ver.sdkVersion != mSdkVersion) {
2716                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2717                        + mSdkVersion + "; regranting permissions for internal storage");
2718                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2719            }
2720            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2721            ver.sdkVersion = mSdkVersion;
2722
2723            // If this is the first boot or an update from pre-M, and it is a normal
2724            // boot, then we need to initialize the default preferred apps across
2725            // all defined users.
2726            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2727                for (UserInfo user : sUserManager.getUsers(true)) {
2728                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2729                    applyFactoryDefaultBrowserLPw(user.id);
2730                    primeDomainVerificationsLPw(user.id);
2731                }
2732            }
2733
2734            // Prepare storage for system user really early during boot,
2735            // since core system apps like SettingsProvider and SystemUI
2736            // can't wait for user to start
2737            final int storageFlags;
2738            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2739                storageFlags = StorageManager.FLAG_STORAGE_DE;
2740            } else {
2741                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2742            }
2743            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2744                    storageFlags, true /* migrateAppData */);
2745
2746            // If this is first boot after an OTA, and a normal boot, then
2747            // we need to clear code cache directories.
2748            // Note that we do *not* clear the application profiles. These remain valid
2749            // across OTAs and are used to drive profile verification (post OTA) and
2750            // profile compilation (without waiting to collect a fresh set of profiles).
2751            if (mIsUpgrade && !onlyCore) {
2752                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2753                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2754                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2755                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2756                        // No apps are running this early, so no need to freeze
2757                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2758                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2759                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2760                    }
2761                }
2762                ver.fingerprint = Build.FINGERPRINT;
2763            }
2764
2765            checkDefaultBrowser();
2766
2767            // clear only after permissions and other defaults have been updated
2768            mExistingSystemPackages.clear();
2769            mPromoteSystemApps = false;
2770
2771            // All the changes are done during package scanning.
2772            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2773
2774            // can downgrade to reader
2775            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2776            mSettings.writeLPr();
2777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2778
2779            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2780            // early on (before the package manager declares itself as early) because other
2781            // components in the system server might ask for package contexts for these apps.
2782            //
2783            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2784            // (i.e, that the data partition is unavailable).
2785            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2786                long start = System.nanoTime();
2787                List<PackageParser.Package> coreApps = new ArrayList<>();
2788                for (PackageParser.Package pkg : mPackages.values()) {
2789                    if (pkg.coreApp) {
2790                        coreApps.add(pkg);
2791                    }
2792                }
2793
2794                int[] stats = performDexOptUpgrade(coreApps, false,
2795                        getCompilerFilterForReason(REASON_CORE_APP));
2796
2797                final int elapsedTimeSeconds =
2798                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2799                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2800
2801                if (DEBUG_DEXOPT) {
2802                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2803                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2804                }
2805
2806
2807                // TODO: Should we log these stats to tron too ?
2808                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2809                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2810                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2811                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2812            }
2813
2814            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2815                    SystemClock.uptimeMillis());
2816
2817            if (!mOnlyCore) {
2818                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2819                mRequiredInstallerPackage = getRequiredInstallerLPr();
2820                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2821                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2822                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2823                        mIntentFilterVerifierComponent);
2824                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2825                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2826                        SharedLibraryInfo.VERSION_UNDEFINED);
2827                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2828                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2829                        SharedLibraryInfo.VERSION_UNDEFINED);
2830            } else {
2831                mRequiredVerifierPackage = null;
2832                mRequiredInstallerPackage = null;
2833                mRequiredUninstallerPackage = null;
2834                mIntentFilterVerifierComponent = null;
2835                mIntentFilterVerifier = null;
2836                mServicesSystemSharedLibraryPackageName = null;
2837                mSharedSystemSharedLibraryPackageName = null;
2838            }
2839
2840            mInstallerService = new PackageInstallerService(context, this);
2841
2842            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2843            if (ephemeralResolverComponent != null) {
2844                if (DEBUG_EPHEMERAL) {
2845                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2846                }
2847                mEphemeralResolverConnection =
2848                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2849            } else {
2850                mEphemeralResolverConnection = null;
2851            }
2852            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2853            if (mEphemeralInstallerComponent != null) {
2854                if (DEBUG_EPHEMERAL) {
2855                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2856                }
2857                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2858            }
2859
2860            // Read and update the usage of dex files.
2861            // Do this at the end of PM init so that all the packages have their
2862            // data directory reconciled.
2863            // At this point we know the code paths of the packages, so we can validate
2864            // the disk file and build the internal cache.
2865            // The usage file is expected to be small so loading and verifying it
2866            // should take a fairly small time compare to the other activities (e.g. package
2867            // scanning).
2868            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2869            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2870            for (int userId : currentUserIds) {
2871                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2872            }
2873            mDexManager.load(userPackages);
2874        } // synchronized (mPackages)
2875        } // synchronized (mInstallLock)
2876
2877        // Now after opening every single application zip, make sure they
2878        // are all flushed.  Not really needed, but keeps things nice and
2879        // tidy.
2880        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2881        Runtime.getRuntime().gc();
2882        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2883
2884        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2885        FallbackCategoryProvider.loadFallbacks();
2886        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2887
2888        // The initial scanning above does many calls into installd while
2889        // holding the mPackages lock, but we're mostly interested in yelling
2890        // once we have a booted system.
2891        mInstaller.setWarnIfHeld(mPackages);
2892
2893        // Expose private service for system components to use.
2894        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2896    }
2897
2898    private static File preparePackageParserCache(boolean isUpgrade) {
2899        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2900            return null;
2901        }
2902
2903        // Disable package parsing on eng builds to allow for faster incremental development.
2904        if ("eng".equals(Build.TYPE)) {
2905            return null;
2906        }
2907
2908        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2909            Slog.i(TAG, "Disabling package parser cache due to system property.");
2910            return null;
2911        }
2912
2913        // The base directory for the package parser cache lives under /data/system/.
2914        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2915                "package_cache");
2916        if (cacheBaseDir == null) {
2917            return null;
2918        }
2919
2920        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2921        // This also serves to "GC" unused entries when the package cache version changes (which
2922        // can only happen during upgrades).
2923        if (isUpgrade) {
2924            FileUtils.deleteContents(cacheBaseDir);
2925        }
2926
2927
2928        // Return the versioned package cache directory. This is something like
2929        // "/data/system/package_cache/1"
2930        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2931
2932        // The following is a workaround to aid development on non-numbered userdebug
2933        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2934        // the system partition is newer.
2935        //
2936        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2937        // that starts with "eng." to signify that this is an engineering build and not
2938        // destined for release.
2939        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2940            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2941
2942            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2943            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2944            // in general and should not be used for production changes. In this specific case,
2945            // we know that they will work.
2946            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2947            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2948                FileUtils.deleteContents(cacheBaseDir);
2949                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2950            }
2951        }
2952
2953        return cacheDir;
2954    }
2955
2956    @Override
2957    public boolean isFirstBoot() {
2958        return mFirstBoot;
2959    }
2960
2961    @Override
2962    public boolean isOnlyCoreApps() {
2963        return mOnlyCore;
2964    }
2965
2966    @Override
2967    public boolean isUpgrade() {
2968        return mIsUpgrade;
2969    }
2970
2971    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2972        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2973
2974        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2975                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2976                UserHandle.USER_SYSTEM);
2977        if (matches.size() == 1) {
2978            return matches.get(0).getComponentInfo().packageName;
2979        } else if (matches.size() == 0) {
2980            Log.e(TAG, "There should probably be a verifier, but, none were found");
2981            return null;
2982        }
2983        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2984    }
2985
2986    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2987        synchronized (mPackages) {
2988            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2989            if (libraryEntry == null) {
2990                throw new IllegalStateException("Missing required shared library:" + name);
2991            }
2992            return libraryEntry.apk;
2993        }
2994    }
2995
2996    private @NonNull String getRequiredInstallerLPr() {
2997        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2998        intent.addCategory(Intent.CATEGORY_DEFAULT);
2999        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3000
3001        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3002                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3003                UserHandle.USER_SYSTEM);
3004        if (matches.size() == 1) {
3005            ResolveInfo resolveInfo = matches.get(0);
3006            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3007                throw new RuntimeException("The installer must be a privileged app");
3008            }
3009            return matches.get(0).getComponentInfo().packageName;
3010        } else {
3011            throw new RuntimeException("There must be exactly one installer; found " + matches);
3012        }
3013    }
3014
3015    private @NonNull String getRequiredUninstallerLPr() {
3016        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3017        intent.addCategory(Intent.CATEGORY_DEFAULT);
3018        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3019
3020        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3021                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3022                UserHandle.USER_SYSTEM);
3023        if (resolveInfo == null ||
3024                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3025            throw new RuntimeException("There must be exactly one uninstaller; found "
3026                    + resolveInfo);
3027        }
3028        return resolveInfo.getComponentInfo().packageName;
3029    }
3030
3031    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3032        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3033
3034        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3035                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3036                UserHandle.USER_SYSTEM);
3037        ResolveInfo best = null;
3038        final int N = matches.size();
3039        for (int i = 0; i < N; i++) {
3040            final ResolveInfo cur = matches.get(i);
3041            final String packageName = cur.getComponentInfo().packageName;
3042            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3043                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3044                continue;
3045            }
3046
3047            if (best == null || cur.priority > best.priority) {
3048                best = cur;
3049            }
3050        }
3051
3052        if (best != null) {
3053            return best.getComponentInfo().getComponentName();
3054        } else {
3055            throw new RuntimeException("There must be at least one intent filter verifier");
3056        }
3057    }
3058
3059    private @Nullable ComponentName getEphemeralResolverLPr() {
3060        final String[] packageArray =
3061                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3062        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3063            if (DEBUG_EPHEMERAL) {
3064                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3065            }
3066            return null;
3067        }
3068
3069        final int resolveFlags =
3070                MATCH_DIRECT_BOOT_AWARE
3071                | MATCH_DIRECT_BOOT_UNAWARE
3072                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3073        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3074        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3075                resolveFlags, UserHandle.USER_SYSTEM);
3076
3077        final int N = resolvers.size();
3078        if (N == 0) {
3079            if (DEBUG_EPHEMERAL) {
3080                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3081            }
3082            return null;
3083        }
3084
3085        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3086        for (int i = 0; i < N; i++) {
3087            final ResolveInfo info = resolvers.get(i);
3088
3089            if (info.serviceInfo == null) {
3090                continue;
3091            }
3092
3093            final String packageName = info.serviceInfo.packageName;
3094            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3095                if (DEBUG_EPHEMERAL) {
3096                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3097                            + " pkg: " + packageName + ", info:" + info);
3098                }
3099                continue;
3100            }
3101
3102            if (DEBUG_EPHEMERAL) {
3103                Slog.v(TAG, "Ephemeral resolver found;"
3104                        + " pkg: " + packageName + ", info:" + info);
3105            }
3106            return new ComponentName(packageName, info.serviceInfo.name);
3107        }
3108        if (DEBUG_EPHEMERAL) {
3109            Slog.v(TAG, "Ephemeral resolver NOT found");
3110        }
3111        return null;
3112    }
3113
3114    private @Nullable ComponentName getEphemeralInstallerLPr() {
3115        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3116        intent.addCategory(Intent.CATEGORY_DEFAULT);
3117        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3118
3119        final int resolveFlags =
3120                MATCH_DIRECT_BOOT_AWARE
3121                | MATCH_DIRECT_BOOT_UNAWARE
3122                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3123        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3124                resolveFlags, UserHandle.USER_SYSTEM);
3125        Iterator<ResolveInfo> iter = matches.iterator();
3126        while (iter.hasNext()) {
3127            final ResolveInfo rInfo = iter.next();
3128            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3129            if (ps != null) {
3130                final PermissionsState permissionsState = ps.getPermissionsState();
3131                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3132                    continue;
3133                }
3134            }
3135            iter.remove();
3136        }
3137        if (matches.size() == 0) {
3138            return null;
3139        } else if (matches.size() == 1) {
3140            return matches.get(0).getComponentInfo().getComponentName();
3141        } else {
3142            throw new RuntimeException(
3143                    "There must be at most one ephemeral installer; found " + matches);
3144        }
3145    }
3146
3147    private void primeDomainVerificationsLPw(int userId) {
3148        if (DEBUG_DOMAIN_VERIFICATION) {
3149            Slog.d(TAG, "Priming domain verifications in user " + userId);
3150        }
3151
3152        SystemConfig systemConfig = SystemConfig.getInstance();
3153        ArraySet<String> packages = systemConfig.getLinkedApps();
3154
3155        for (String packageName : packages) {
3156            PackageParser.Package pkg = mPackages.get(packageName);
3157            if (pkg != null) {
3158                if (!pkg.isSystemApp()) {
3159                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3160                    continue;
3161                }
3162
3163                ArraySet<String> domains = null;
3164                for (PackageParser.Activity a : pkg.activities) {
3165                    for (ActivityIntentInfo filter : a.intents) {
3166                        if (hasValidDomains(filter)) {
3167                            if (domains == null) {
3168                                domains = new ArraySet<String>();
3169                            }
3170                            domains.addAll(filter.getHostsList());
3171                        }
3172                    }
3173                }
3174
3175                if (domains != null && domains.size() > 0) {
3176                    if (DEBUG_DOMAIN_VERIFICATION) {
3177                        Slog.v(TAG, "      + " + packageName);
3178                    }
3179                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3180                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3181                    // and then 'always' in the per-user state actually used for intent resolution.
3182                    final IntentFilterVerificationInfo ivi;
3183                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3184                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3185                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3186                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3187                } else {
3188                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3189                            + "' does not handle web links");
3190                }
3191            } else {
3192                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3193            }
3194        }
3195
3196        scheduleWritePackageRestrictionsLocked(userId);
3197        scheduleWriteSettingsLocked();
3198    }
3199
3200    private void applyFactoryDefaultBrowserLPw(int userId) {
3201        // The default browser app's package name is stored in a string resource,
3202        // with a product-specific overlay used for vendor customization.
3203        String browserPkg = mContext.getResources().getString(
3204                com.android.internal.R.string.default_browser);
3205        if (!TextUtils.isEmpty(browserPkg)) {
3206            // non-empty string => required to be a known package
3207            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3208            if (ps == null) {
3209                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3210                browserPkg = null;
3211            } else {
3212                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3213            }
3214        }
3215
3216        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3217        // default.  If there's more than one, just leave everything alone.
3218        if (browserPkg == null) {
3219            calculateDefaultBrowserLPw(userId);
3220        }
3221    }
3222
3223    private void calculateDefaultBrowserLPw(int userId) {
3224        List<String> allBrowsers = resolveAllBrowserApps(userId);
3225        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3226        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3227    }
3228
3229    private List<String> resolveAllBrowserApps(int userId) {
3230        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3231        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3232                PackageManager.MATCH_ALL, userId);
3233
3234        final int count = list.size();
3235        List<String> result = new ArrayList<String>(count);
3236        for (int i=0; i<count; i++) {
3237            ResolveInfo info = list.get(i);
3238            if (info.activityInfo == null
3239                    || !info.handleAllWebDataURI
3240                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3241                    || result.contains(info.activityInfo.packageName)) {
3242                continue;
3243            }
3244            result.add(info.activityInfo.packageName);
3245        }
3246
3247        return result;
3248    }
3249
3250    private boolean packageIsBrowser(String packageName, int userId) {
3251        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3252                PackageManager.MATCH_ALL, userId);
3253        final int N = list.size();
3254        for (int i = 0; i < N; i++) {
3255            ResolveInfo info = list.get(i);
3256            if (packageName.equals(info.activityInfo.packageName)) {
3257                return true;
3258            }
3259        }
3260        return false;
3261    }
3262
3263    private void checkDefaultBrowser() {
3264        final int myUserId = UserHandle.myUserId();
3265        final String packageName = getDefaultBrowserPackageName(myUserId);
3266        if (packageName != null) {
3267            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3268            if (info == null) {
3269                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3270                synchronized (mPackages) {
3271                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3272                }
3273            }
3274        }
3275    }
3276
3277    @Override
3278    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3279            throws RemoteException {
3280        try {
3281            return super.onTransact(code, data, reply, flags);
3282        } catch (RuntimeException e) {
3283            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3284                Slog.wtf(TAG, "Package Manager Crash", e);
3285            }
3286            throw e;
3287        }
3288    }
3289
3290    static int[] appendInts(int[] cur, int[] add) {
3291        if (add == null) return cur;
3292        if (cur == null) return add;
3293        final int N = add.length;
3294        for (int i=0; i<N; i++) {
3295            cur = appendInt(cur, add[i]);
3296        }
3297        return cur;
3298    }
3299
3300    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3301        if (!sUserManager.exists(userId)) return null;
3302        if (ps == null) {
3303            return null;
3304        }
3305        final PackageParser.Package p = ps.pkg;
3306        if (p == null) {
3307            return null;
3308        }
3309        // Filter out ephemeral app metadata:
3310        //   * The system/shell/root can see metadata for any app
3311        //   * An installed app can see metadata for 1) other installed apps
3312        //     and 2) ephemeral apps that have explicitly interacted with it
3313        //   * Ephemeral apps can only see their own metadata
3314        //   * Holding a signature permission allows seeing instant apps
3315        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3316        if (callingAppId != Process.SYSTEM_UID
3317                && callingAppId != Process.SHELL_UID
3318                && callingAppId != Process.ROOT_UID
3319                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3320                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3321            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3322            if (ephemeralPackageName != null) {
3323                // ephemeral apps can only get information on themselves
3324                if (!ephemeralPackageName.equals(p.packageName)) {
3325                    return null;
3326                }
3327            } else {
3328                if (p.applicationInfo.isInstantApp()) {
3329                    // only get access to the ephemeral app if we've been granted access
3330                    if (!mInstantAppRegistry.isInstantAccessGranted(
3331                            userId, callingAppId, ps.appId)) {
3332                        return null;
3333                    }
3334                }
3335            }
3336        }
3337
3338        final PermissionsState permissionsState = ps.getPermissionsState();
3339
3340        // Compute GIDs only if requested
3341        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3342                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3343        // Compute granted permissions only if package has requested permissions
3344        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3345                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3346        final PackageUserState state = ps.readUserState(userId);
3347
3348        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3349                && ps.isSystem()) {
3350            flags |= MATCH_ANY_USER;
3351        }
3352
3353        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3354                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3355
3356        if (packageInfo == null) {
3357            return null;
3358        }
3359
3360        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3361                resolveExternalPackageNameLPr(p);
3362
3363        return packageInfo;
3364    }
3365
3366    @Override
3367    public void checkPackageStartable(String packageName, int userId) {
3368        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3369
3370        synchronized (mPackages) {
3371            final PackageSetting ps = mSettings.mPackages.get(packageName);
3372            if (ps == null) {
3373                throw new SecurityException("Package " + packageName + " was not found!");
3374            }
3375
3376            if (!ps.getInstalled(userId)) {
3377                throw new SecurityException(
3378                        "Package " + packageName + " was not installed for user " + userId + "!");
3379            }
3380
3381            if (mSafeMode && !ps.isSystem()) {
3382                throw new SecurityException("Package " + packageName + " not a system app!");
3383            }
3384
3385            if (mFrozenPackages.contains(packageName)) {
3386                throw new SecurityException("Package " + packageName + " is currently frozen!");
3387            }
3388
3389            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3390                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3391                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3392            }
3393        }
3394    }
3395
3396    @Override
3397    public boolean isPackageAvailable(String packageName, int userId) {
3398        if (!sUserManager.exists(userId)) return false;
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3400                false /* requireFullPermission */, false /* checkShell */, "is package available");
3401        synchronized (mPackages) {
3402            PackageParser.Package p = mPackages.get(packageName);
3403            if (p != null) {
3404                final PackageSetting ps = (PackageSetting) p.mExtras;
3405                if (ps != null) {
3406                    final PackageUserState state = ps.readUserState(userId);
3407                    if (state != null) {
3408                        return PackageParser.isAvailable(state);
3409                    }
3410                }
3411            }
3412        }
3413        return false;
3414    }
3415
3416    @Override
3417    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3418        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3419                flags, userId);
3420    }
3421
3422    @Override
3423    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3424            int flags, int userId) {
3425        return getPackageInfoInternal(versionedPackage.getPackageName(),
3426                // TODO: We will change version code to long, so in the new API it is long
3427                (int) versionedPackage.getVersionCode(), flags, userId);
3428    }
3429
3430    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3431            int flags, int userId) {
3432        if (!sUserManager.exists(userId)) return null;
3433        flags = updateFlagsForPackage(flags, userId, packageName);
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3435                false /* requireFullPermission */, false /* checkShell */, "get package info");
3436
3437        // reader
3438        synchronized (mPackages) {
3439            // Normalize package name to handle renamed packages and static libs
3440            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3441
3442            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3443            if (matchFactoryOnly) {
3444                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3445                if (ps != null) {
3446                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3447                        return null;
3448                    }
3449                    return generatePackageInfo(ps, flags, userId);
3450                }
3451            }
3452
3453            PackageParser.Package p = mPackages.get(packageName);
3454            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3455                return null;
3456            }
3457            if (DEBUG_PACKAGE_INFO)
3458                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3459            if (p != null) {
3460                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3461                        Binder.getCallingUid(), userId)) {
3462                    return null;
3463                }
3464                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3465            }
3466            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3467                final PackageSetting ps = mSettings.mPackages.get(packageName);
3468                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3469                    return null;
3470                }
3471                return generatePackageInfo(ps, flags, userId);
3472            }
3473        }
3474        return null;
3475    }
3476
3477
3478    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3479        // System/shell/root get to see all static libs
3480        final int appId = UserHandle.getAppId(uid);
3481        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3482                || appId == Process.ROOT_UID) {
3483            return false;
3484        }
3485
3486        // No package means no static lib as it is always on internal storage
3487        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3488            return false;
3489        }
3490
3491        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3492                ps.pkg.staticSharedLibVersion);
3493        if (libEntry == null) {
3494            return false;
3495        }
3496
3497        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3498        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3499        if (uidPackageNames == null) {
3500            return true;
3501        }
3502
3503        for (String uidPackageName : uidPackageNames) {
3504            if (ps.name.equals(uidPackageName)) {
3505                return false;
3506            }
3507            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3508            if (uidPs != null) {
3509                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3510                        libEntry.info.getName());
3511                if (index < 0) {
3512                    continue;
3513                }
3514                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3515                    return false;
3516                }
3517            }
3518        }
3519        return true;
3520    }
3521
3522    @Override
3523    public String[] currentToCanonicalPackageNames(String[] names) {
3524        String[] out = new String[names.length];
3525        // reader
3526        synchronized (mPackages) {
3527            for (int i=names.length-1; i>=0; i--) {
3528                PackageSetting ps = mSettings.mPackages.get(names[i]);
3529                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3530            }
3531        }
3532        return out;
3533    }
3534
3535    @Override
3536    public String[] canonicalToCurrentPackageNames(String[] names) {
3537        String[] out = new String[names.length];
3538        // reader
3539        synchronized (mPackages) {
3540            for (int i=names.length-1; i>=0; i--) {
3541                String cur = mSettings.getRenamedPackageLPr(names[i]);
3542                out[i] = cur != null ? cur : names[i];
3543            }
3544        }
3545        return out;
3546    }
3547
3548    @Override
3549    public int getPackageUid(String packageName, int flags, int userId) {
3550        if (!sUserManager.exists(userId)) return -1;
3551        flags = updateFlagsForPackage(flags, userId, packageName);
3552        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3553                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3554
3555        // reader
3556        synchronized (mPackages) {
3557            final PackageParser.Package p = mPackages.get(packageName);
3558            if (p != null && p.isMatch(flags)) {
3559                return UserHandle.getUid(userId, p.applicationInfo.uid);
3560            }
3561            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3562                final PackageSetting ps = mSettings.mPackages.get(packageName);
3563                if (ps != null && ps.isMatch(flags)) {
3564                    return UserHandle.getUid(userId, ps.appId);
3565                }
3566            }
3567        }
3568
3569        return -1;
3570    }
3571
3572    @Override
3573    public int[] getPackageGids(String packageName, int flags, int userId) {
3574        if (!sUserManager.exists(userId)) return null;
3575        flags = updateFlagsForPackage(flags, userId, packageName);
3576        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3577                false /* requireFullPermission */, false /* checkShell */,
3578                "getPackageGids");
3579
3580        // reader
3581        synchronized (mPackages) {
3582            final PackageParser.Package p = mPackages.get(packageName);
3583            if (p != null && p.isMatch(flags)) {
3584                PackageSetting ps = (PackageSetting) p.mExtras;
3585                // TODO: Shouldn't this be checking for package installed state for userId and
3586                // return null?
3587                return ps.getPermissionsState().computeGids(userId);
3588            }
3589            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3590                final PackageSetting ps = mSettings.mPackages.get(packageName);
3591                if (ps != null && ps.isMatch(flags)) {
3592                    return ps.getPermissionsState().computeGids(userId);
3593                }
3594            }
3595        }
3596
3597        return null;
3598    }
3599
3600    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3601        if (bp.perm != null) {
3602            return PackageParser.generatePermissionInfo(bp.perm, flags);
3603        }
3604        PermissionInfo pi = new PermissionInfo();
3605        pi.name = bp.name;
3606        pi.packageName = bp.sourcePackage;
3607        pi.nonLocalizedLabel = bp.name;
3608        pi.protectionLevel = bp.protectionLevel;
3609        return pi;
3610    }
3611
3612    @Override
3613    public PermissionInfo getPermissionInfo(String name, int flags) {
3614        // reader
3615        synchronized (mPackages) {
3616            final BasePermission p = mSettings.mPermissions.get(name);
3617            if (p != null) {
3618                return generatePermissionInfo(p, flags);
3619            }
3620            return null;
3621        }
3622    }
3623
3624    @Override
3625    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3626            int flags) {
3627        // reader
3628        synchronized (mPackages) {
3629            if (group != null && !mPermissionGroups.containsKey(group)) {
3630                // This is thrown as NameNotFoundException
3631                return null;
3632            }
3633
3634            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3635            for (BasePermission p : mSettings.mPermissions.values()) {
3636                if (group == null) {
3637                    if (p.perm == null || p.perm.info.group == null) {
3638                        out.add(generatePermissionInfo(p, flags));
3639                    }
3640                } else {
3641                    if (p.perm != null && group.equals(p.perm.info.group)) {
3642                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3643                    }
3644                }
3645            }
3646            return new ParceledListSlice<>(out);
3647        }
3648    }
3649
3650    @Override
3651    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3652        // reader
3653        synchronized (mPackages) {
3654            return PackageParser.generatePermissionGroupInfo(
3655                    mPermissionGroups.get(name), flags);
3656        }
3657    }
3658
3659    @Override
3660    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3661        // reader
3662        synchronized (mPackages) {
3663            final int N = mPermissionGroups.size();
3664            ArrayList<PermissionGroupInfo> out
3665                    = new ArrayList<PermissionGroupInfo>(N);
3666            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3667                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3668            }
3669            return new ParceledListSlice<>(out);
3670        }
3671    }
3672
3673    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3674            int uid, int userId) {
3675        if (!sUserManager.exists(userId)) return null;
3676        PackageSetting ps = mSettings.mPackages.get(packageName);
3677        if (ps != null) {
3678            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3679                return null;
3680            }
3681            if (ps.pkg == null) {
3682                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3683                if (pInfo != null) {
3684                    return pInfo.applicationInfo;
3685                }
3686                return null;
3687            }
3688            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3689                    ps.readUserState(userId), userId);
3690            if (ai != null) {
3691                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3692            }
3693            return ai;
3694        }
3695        return null;
3696    }
3697
3698    @Override
3699    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3700        if (!sUserManager.exists(userId)) return null;
3701        flags = updateFlagsForApplication(flags, userId, packageName);
3702        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3703                false /* requireFullPermission */, false /* checkShell */, "get application info");
3704
3705        // writer
3706        synchronized (mPackages) {
3707            // Normalize package name to handle renamed packages and static libs
3708            packageName = resolveInternalPackageNameLPr(packageName,
3709                    PackageManager.VERSION_CODE_HIGHEST);
3710
3711            PackageParser.Package p = mPackages.get(packageName);
3712            if (DEBUG_PACKAGE_INFO) Log.v(
3713                    TAG, "getApplicationInfo " + packageName
3714                    + ": " + p);
3715            if (p != null) {
3716                PackageSetting ps = mSettings.mPackages.get(packageName);
3717                if (ps == null) return null;
3718                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3719                    return null;
3720                }
3721                // Note: isEnabledLP() does not apply here - always return info
3722                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3723                        p, flags, ps.readUserState(userId), userId);
3724                if (ai != null) {
3725                    ai.packageName = resolveExternalPackageNameLPr(p);
3726                }
3727                return ai;
3728            }
3729            if ("android".equals(packageName)||"system".equals(packageName)) {
3730                return mAndroidApplication;
3731            }
3732            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3733                // Already generates the external package name
3734                return generateApplicationInfoFromSettingsLPw(packageName,
3735                        Binder.getCallingUid(), flags, userId);
3736            }
3737        }
3738        return null;
3739    }
3740
3741    private String normalizePackageNameLPr(String packageName) {
3742        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3743        return normalizedPackageName != null ? normalizedPackageName : packageName;
3744    }
3745
3746    @Override
3747    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3748            final IPackageDataObserver observer) {
3749        mContext.enforceCallingOrSelfPermission(
3750                android.Manifest.permission.CLEAR_APP_CACHE, null);
3751        // Queue up an async operation since clearing cache may take a little while.
3752        mHandler.post(new Runnable() {
3753            public void run() {
3754                mHandler.removeCallbacks(this);
3755                boolean success = true;
3756                synchronized (mInstallLock) {
3757                    try {
3758                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3759                    } catch (InstallerException e) {
3760                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3761                        success = false;
3762                    }
3763                }
3764                if (observer != null) {
3765                    try {
3766                        observer.onRemoveCompleted(null, success);
3767                    } catch (RemoteException e) {
3768                        Slog.w(TAG, "RemoveException when invoking call back");
3769                    }
3770                }
3771            }
3772        });
3773    }
3774
3775    @Override
3776    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3777            final IntentSender pi) {
3778        mContext.enforceCallingOrSelfPermission(
3779                android.Manifest.permission.CLEAR_APP_CACHE, null);
3780        // Queue up an async operation since clearing cache may take a little while.
3781        mHandler.post(new Runnable() {
3782            public void run() {
3783                mHandler.removeCallbacks(this);
3784                boolean success = true;
3785                synchronized (mInstallLock) {
3786                    try {
3787                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3788                    } catch (InstallerException e) {
3789                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3790                        success = false;
3791                    }
3792                }
3793                if(pi != null) {
3794                    try {
3795                        // Callback via pending intent
3796                        int code = success ? 1 : 0;
3797                        pi.sendIntent(null, code, null,
3798                                null, null);
3799                    } catch (SendIntentException e1) {
3800                        Slog.i(TAG, "Failed to send pending intent");
3801                    }
3802                }
3803            }
3804        });
3805    }
3806
3807    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3808        synchronized (mInstallLock) {
3809            try {
3810                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3811            } catch (InstallerException e) {
3812                throw new IOException("Failed to free enough space", e);
3813            }
3814        }
3815    }
3816
3817    /**
3818     * Update given flags based on encryption status of current user.
3819     */
3820    private int updateFlags(int flags, int userId) {
3821        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3822                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3823            // Caller expressed an explicit opinion about what encryption
3824            // aware/unaware components they want to see, so fall through and
3825            // give them what they want
3826        } else {
3827            // Caller expressed no opinion, so match based on user state
3828            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3829                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3830            } else {
3831                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3832            }
3833        }
3834        return flags;
3835    }
3836
3837    private UserManagerInternal getUserManagerInternal() {
3838        if (mUserManagerInternal == null) {
3839            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3840        }
3841        return mUserManagerInternal;
3842    }
3843
3844    /**
3845     * Update given flags when being used to request {@link PackageInfo}.
3846     */
3847    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3848        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3849        boolean triaged = true;
3850        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3851                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3852            // Caller is asking for component details, so they'd better be
3853            // asking for specific encryption matching behavior, or be triaged
3854            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3855                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3856                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3857                triaged = false;
3858            }
3859        }
3860        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3861                | PackageManager.MATCH_SYSTEM_ONLY
3862                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3863            triaged = false;
3864        }
3865        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3866            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3867                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3868                    + Debug.getCallers(5));
3869        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3870                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3871            // If the caller wants all packages and has a restricted profile associated with it,
3872            // then match all users. This is to make sure that launchers that need to access work
3873            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3874            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3875            flags |= PackageManager.MATCH_ANY_USER;
3876        }
3877        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3878            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3879                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3880        }
3881        return updateFlags(flags, userId);
3882    }
3883
3884    /**
3885     * Update given flags when being used to request {@link ApplicationInfo}.
3886     */
3887    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3888        return updateFlagsForPackage(flags, userId, cookie);
3889    }
3890
3891    /**
3892     * Update given flags when being used to request {@link ComponentInfo}.
3893     */
3894    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3895        if (cookie instanceof Intent) {
3896            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3897                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3898            }
3899        }
3900
3901        boolean triaged = true;
3902        // Caller is asking for component details, so they'd better be
3903        // asking for specific encryption matching behavior, or be triaged
3904        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3905                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3906                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3907            triaged = false;
3908        }
3909        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3910            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3911                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3912        }
3913
3914        return updateFlags(flags, userId);
3915    }
3916
3917    /**
3918     * Update given intent when being used to request {@link ResolveInfo}.
3919     */
3920    private Intent updateIntentForResolve(Intent intent) {
3921        if (intent.getSelector() != null) {
3922            intent = intent.getSelector();
3923        }
3924        if (DEBUG_PREFERRED) {
3925            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3926        }
3927        return intent;
3928    }
3929
3930    /**
3931     * Update given flags when being used to request {@link ResolveInfo}.
3932     */
3933    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3934        // Safe mode means we shouldn't match any third-party components
3935        if (mSafeMode) {
3936            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3937        }
3938        final int callingUid = Binder.getCallingUid();
3939        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3940            // The system sees all components
3941            flags |= PackageManager.MATCH_EPHEMERAL;
3942        } else if (getEphemeralPackageName(callingUid) != null) {
3943            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3944            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3945            flags |= PackageManager.MATCH_EPHEMERAL;
3946        } else {
3947            // Otherwise, prevent leaking ephemeral components
3948            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3949            flags &= ~PackageManager.MATCH_EPHEMERAL;
3950        }
3951        return updateFlagsForComponent(flags, userId, cookie);
3952    }
3953
3954    @Override
3955    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        flags = updateFlagsForComponent(flags, userId, component);
3958        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3959                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3960        synchronized (mPackages) {
3961            PackageParser.Activity a = mActivities.mActivities.get(component);
3962
3963            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3964            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3965                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3966                if (ps == null) return null;
3967                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3968                        userId);
3969            }
3970            if (mResolveComponentName.equals(component)) {
3971                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3972                        new PackageUserState(), userId);
3973            }
3974        }
3975        return null;
3976    }
3977
3978    @Override
3979    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3980            String resolvedType) {
3981        synchronized (mPackages) {
3982            if (component.equals(mResolveComponentName)) {
3983                // The resolver supports EVERYTHING!
3984                return true;
3985            }
3986            PackageParser.Activity a = mActivities.mActivities.get(component);
3987            if (a == null) {
3988                return false;
3989            }
3990            for (int i=0; i<a.intents.size(); i++) {
3991                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3992                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3993                    return true;
3994                }
3995            }
3996            return false;
3997        }
3998    }
3999
4000    @Override
4001    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4002        if (!sUserManager.exists(userId)) return null;
4003        flags = updateFlagsForComponent(flags, userId, component);
4004        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4005                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4006        synchronized (mPackages) {
4007            PackageParser.Activity a = mReceivers.mActivities.get(component);
4008            if (DEBUG_PACKAGE_INFO) Log.v(
4009                TAG, "getReceiverInfo " + component + ": " + a);
4010            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4011                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4012                if (ps == null) return null;
4013                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4014                        userId);
4015            }
4016        }
4017        return null;
4018    }
4019
4020    @Override
4021    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4022        if (!sUserManager.exists(userId)) return null;
4023        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4024
4025        flags = updateFlagsForPackage(flags, userId, null);
4026
4027        final boolean canSeeStaticLibraries =
4028                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4029                        == PERMISSION_GRANTED
4030                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4031                        == PERMISSION_GRANTED
4032                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4033                        == PERMISSION_GRANTED
4034                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4035                        == PERMISSION_GRANTED;
4036
4037        synchronized (mPackages) {
4038            List<SharedLibraryInfo> result = null;
4039
4040            final int libCount = mSharedLibraries.size();
4041            for (int i = 0; i < libCount; i++) {
4042                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4043                if (versionedLib == null) {
4044                    continue;
4045                }
4046
4047                final int versionCount = versionedLib.size();
4048                for (int j = 0; j < versionCount; j++) {
4049                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4050                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4051                        break;
4052                    }
4053                    final long identity = Binder.clearCallingIdentity();
4054                    try {
4055                        // TODO: We will change version code to long, so in the new API it is long
4056                        PackageInfo packageInfo = getPackageInfoVersioned(
4057                                libInfo.getDeclaringPackage(), flags, userId);
4058                        if (packageInfo == null) {
4059                            continue;
4060                        }
4061                    } finally {
4062                        Binder.restoreCallingIdentity(identity);
4063                    }
4064
4065                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4066                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4067                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4068
4069                    if (result == null) {
4070                        result = new ArrayList<>();
4071                    }
4072                    result.add(resLibInfo);
4073                }
4074            }
4075
4076            return result != null ? new ParceledListSlice<>(result) : null;
4077        }
4078    }
4079
4080    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4081            SharedLibraryInfo libInfo, int flags, int userId) {
4082        List<VersionedPackage> versionedPackages = null;
4083        final int packageCount = mSettings.mPackages.size();
4084        for (int i = 0; i < packageCount; i++) {
4085            PackageSetting ps = mSettings.mPackages.valueAt(i);
4086
4087            if (ps == null) {
4088                continue;
4089            }
4090
4091            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4092                continue;
4093            }
4094
4095            final String libName = libInfo.getName();
4096            if (libInfo.isStatic()) {
4097                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4098                if (libIdx < 0) {
4099                    continue;
4100                }
4101                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4102                    continue;
4103                }
4104                if (versionedPackages == null) {
4105                    versionedPackages = new ArrayList<>();
4106                }
4107                // If the dependent is a static shared lib, use the public package name
4108                String dependentPackageName = ps.name;
4109                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4110                    dependentPackageName = ps.pkg.manifestPackageName;
4111                }
4112                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4113            } else if (ps.pkg != null) {
4114                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4115                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4116                    if (versionedPackages == null) {
4117                        versionedPackages = new ArrayList<>();
4118                    }
4119                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4120                }
4121            }
4122        }
4123
4124        return versionedPackages;
4125    }
4126
4127    @Override
4128    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        flags = updateFlagsForComponent(flags, userId, component);
4131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4132                false /* requireFullPermission */, false /* checkShell */, "get service info");
4133        synchronized (mPackages) {
4134            PackageParser.Service s = mServices.mServices.get(component);
4135            if (DEBUG_PACKAGE_INFO) Log.v(
4136                TAG, "getServiceInfo " + component + ": " + s);
4137            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4138                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4139                if (ps == null) return null;
4140                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4141                        userId);
4142            }
4143        }
4144        return null;
4145    }
4146
4147    @Override
4148    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4149        if (!sUserManager.exists(userId)) return null;
4150        flags = updateFlagsForComponent(flags, userId, component);
4151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4152                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4153        synchronized (mPackages) {
4154            PackageParser.Provider p = mProviders.mProviders.get(component);
4155            if (DEBUG_PACKAGE_INFO) Log.v(
4156                TAG, "getProviderInfo " + component + ": " + p);
4157            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4158                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4159                if (ps == null) return null;
4160                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4161                        userId);
4162            }
4163        }
4164        return null;
4165    }
4166
4167    @Override
4168    public String[] getSystemSharedLibraryNames() {
4169        synchronized (mPackages) {
4170            Set<String> libs = null;
4171            final int libCount = mSharedLibraries.size();
4172            for (int i = 0; i < libCount; i++) {
4173                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4174                if (versionedLib == null) {
4175                    continue;
4176                }
4177                final int versionCount = versionedLib.size();
4178                for (int j = 0; j < versionCount; j++) {
4179                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4180                    if (!libEntry.info.isStatic()) {
4181                        if (libs == null) {
4182                            libs = new ArraySet<>();
4183                        }
4184                        libs.add(libEntry.info.getName());
4185                        break;
4186                    }
4187                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4188                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4189                            UserHandle.getUserId(Binder.getCallingUid()))) {
4190                        if (libs == null) {
4191                            libs = new ArraySet<>();
4192                        }
4193                        libs.add(libEntry.info.getName());
4194                        break;
4195                    }
4196                }
4197            }
4198
4199            if (libs != null) {
4200                String[] libsArray = new String[libs.size()];
4201                libs.toArray(libsArray);
4202                return libsArray;
4203            }
4204
4205            return null;
4206        }
4207    }
4208
4209    @Override
4210    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4211        synchronized (mPackages) {
4212            return mServicesSystemSharedLibraryPackageName;
4213        }
4214    }
4215
4216    @Override
4217    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4218        synchronized (mPackages) {
4219            return mSharedSystemSharedLibraryPackageName;
4220        }
4221    }
4222
4223    @Override
4224    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4225        ArrayList<FeatureInfo> res;
4226        synchronized (mAvailableFeatures) {
4227            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4228            res.addAll(mAvailableFeatures.values());
4229        }
4230        final FeatureInfo fi = new FeatureInfo();
4231        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4232                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4233        res.add(fi);
4234
4235        return new ParceledListSlice<>(res);
4236    }
4237
4238    @Override
4239    public boolean hasSystemFeature(String name, int version) {
4240        synchronized (mAvailableFeatures) {
4241            final FeatureInfo feat = mAvailableFeatures.get(name);
4242            if (feat == null) {
4243                return false;
4244            } else {
4245                return feat.version >= version;
4246            }
4247        }
4248    }
4249
4250    @Override
4251    public int checkPermission(String permName, String pkgName, int userId) {
4252        if (!sUserManager.exists(userId)) {
4253            return PackageManager.PERMISSION_DENIED;
4254        }
4255
4256        synchronized (mPackages) {
4257            final PackageParser.Package p = mPackages.get(pkgName);
4258            if (p != null && p.mExtras != null) {
4259                final PackageSetting ps = (PackageSetting) p.mExtras;
4260                final PermissionsState permissionsState = ps.getPermissionsState();
4261                if (permissionsState.hasPermission(permName, userId)) {
4262                    return PackageManager.PERMISSION_GRANTED;
4263                }
4264                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4265                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4266                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4267                    return PackageManager.PERMISSION_GRANTED;
4268                }
4269            }
4270        }
4271
4272        return PackageManager.PERMISSION_DENIED;
4273    }
4274
4275    @Override
4276    public int checkUidPermission(String permName, int uid) {
4277        final int userId = UserHandle.getUserId(uid);
4278
4279        if (!sUserManager.exists(userId)) {
4280            return PackageManager.PERMISSION_DENIED;
4281        }
4282
4283        synchronized (mPackages) {
4284            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4285            if (obj != null) {
4286                final SettingBase ps = (SettingBase) obj;
4287                final PermissionsState permissionsState = ps.getPermissionsState();
4288                if (permissionsState.hasPermission(permName, userId)) {
4289                    return PackageManager.PERMISSION_GRANTED;
4290                }
4291                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4292                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4293                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4294                    return PackageManager.PERMISSION_GRANTED;
4295                }
4296            } else {
4297                ArraySet<String> perms = mSystemPermissions.get(uid);
4298                if (perms != null) {
4299                    if (perms.contains(permName)) {
4300                        return PackageManager.PERMISSION_GRANTED;
4301                    }
4302                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4303                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4304                        return PackageManager.PERMISSION_GRANTED;
4305                    }
4306                }
4307            }
4308        }
4309
4310        return PackageManager.PERMISSION_DENIED;
4311    }
4312
4313    @Override
4314    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4315        if (UserHandle.getCallingUserId() != userId) {
4316            mContext.enforceCallingPermission(
4317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4318                    "isPermissionRevokedByPolicy for user " + userId);
4319        }
4320
4321        if (checkPermission(permission, packageName, userId)
4322                == PackageManager.PERMISSION_GRANTED) {
4323            return false;
4324        }
4325
4326        final long identity = Binder.clearCallingIdentity();
4327        try {
4328            final int flags = getPermissionFlags(permission, packageName, userId);
4329            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4330        } finally {
4331            Binder.restoreCallingIdentity(identity);
4332        }
4333    }
4334
4335    @Override
4336    public String getPermissionControllerPackageName() {
4337        synchronized (mPackages) {
4338            return mRequiredInstallerPackage;
4339        }
4340    }
4341
4342    /**
4343     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4344     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4345     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4346     * @param message the message to log on security exception
4347     */
4348    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4349            boolean checkShell, String message) {
4350        if (userId < 0) {
4351            throw new IllegalArgumentException("Invalid userId " + userId);
4352        }
4353        if (checkShell) {
4354            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4355        }
4356        if (userId == UserHandle.getUserId(callingUid)) return;
4357        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4358            if (requireFullPermission) {
4359                mContext.enforceCallingOrSelfPermission(
4360                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4361            } else {
4362                try {
4363                    mContext.enforceCallingOrSelfPermission(
4364                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4365                } catch (SecurityException se) {
4366                    mContext.enforceCallingOrSelfPermission(
4367                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4368                }
4369            }
4370        }
4371    }
4372
4373    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4374        if (callingUid == Process.SHELL_UID) {
4375            if (userHandle >= 0
4376                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4377                throw new SecurityException("Shell does not have permission to access user "
4378                        + userHandle);
4379            } else if (userHandle < 0) {
4380                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4381                        + Debug.getCallers(3));
4382            }
4383        }
4384    }
4385
4386    private BasePermission findPermissionTreeLP(String permName) {
4387        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4388            if (permName.startsWith(bp.name) &&
4389                    permName.length() > bp.name.length() &&
4390                    permName.charAt(bp.name.length()) == '.') {
4391                return bp;
4392            }
4393        }
4394        return null;
4395    }
4396
4397    private BasePermission checkPermissionTreeLP(String permName) {
4398        if (permName != null) {
4399            BasePermission bp = findPermissionTreeLP(permName);
4400            if (bp != null) {
4401                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4402                    return bp;
4403                }
4404                throw new SecurityException("Calling uid "
4405                        + Binder.getCallingUid()
4406                        + " is not allowed to add to permission tree "
4407                        + bp.name + " owned by uid " + bp.uid);
4408            }
4409        }
4410        throw new SecurityException("No permission tree found for " + permName);
4411    }
4412
4413    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4414        if (s1 == null) {
4415            return s2 == null;
4416        }
4417        if (s2 == null) {
4418            return false;
4419        }
4420        if (s1.getClass() != s2.getClass()) {
4421            return false;
4422        }
4423        return s1.equals(s2);
4424    }
4425
4426    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4427        if (pi1.icon != pi2.icon) return false;
4428        if (pi1.logo != pi2.logo) return false;
4429        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4430        if (!compareStrings(pi1.name, pi2.name)) return false;
4431        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4432        // We'll take care of setting this one.
4433        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4434        // These are not currently stored in settings.
4435        //if (!compareStrings(pi1.group, pi2.group)) return false;
4436        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4437        //if (pi1.labelRes != pi2.labelRes) return false;
4438        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4439        return true;
4440    }
4441
4442    int permissionInfoFootprint(PermissionInfo info) {
4443        int size = info.name.length();
4444        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4445        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4446        return size;
4447    }
4448
4449    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4450        int size = 0;
4451        for (BasePermission perm : mSettings.mPermissions.values()) {
4452            if (perm.uid == tree.uid) {
4453                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4454            }
4455        }
4456        return size;
4457    }
4458
4459    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4460        // We calculate the max size of permissions defined by this uid and throw
4461        // if that plus the size of 'info' would exceed our stated maximum.
4462        if (tree.uid != Process.SYSTEM_UID) {
4463            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4464            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4465                throw new SecurityException("Permission tree size cap exceeded");
4466            }
4467        }
4468    }
4469
4470    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4471        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4472            throw new SecurityException("Label must be specified in permission");
4473        }
4474        BasePermission tree = checkPermissionTreeLP(info.name);
4475        BasePermission bp = mSettings.mPermissions.get(info.name);
4476        boolean added = bp == null;
4477        boolean changed = true;
4478        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4479        if (added) {
4480            enforcePermissionCapLocked(info, tree);
4481            bp = new BasePermission(info.name, tree.sourcePackage,
4482                    BasePermission.TYPE_DYNAMIC);
4483        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4484            throw new SecurityException(
4485                    "Not allowed to modify non-dynamic permission "
4486                    + info.name);
4487        } else {
4488            if (bp.protectionLevel == fixedLevel
4489                    && bp.perm.owner.equals(tree.perm.owner)
4490                    && bp.uid == tree.uid
4491                    && comparePermissionInfos(bp.perm.info, info)) {
4492                changed = false;
4493            }
4494        }
4495        bp.protectionLevel = fixedLevel;
4496        info = new PermissionInfo(info);
4497        info.protectionLevel = fixedLevel;
4498        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4499        bp.perm.info.packageName = tree.perm.info.packageName;
4500        bp.uid = tree.uid;
4501        if (added) {
4502            mSettings.mPermissions.put(info.name, bp);
4503        }
4504        if (changed) {
4505            if (!async) {
4506                mSettings.writeLPr();
4507            } else {
4508                scheduleWriteSettingsLocked();
4509            }
4510        }
4511        return added;
4512    }
4513
4514    @Override
4515    public boolean addPermission(PermissionInfo info) {
4516        synchronized (mPackages) {
4517            return addPermissionLocked(info, false);
4518        }
4519    }
4520
4521    @Override
4522    public boolean addPermissionAsync(PermissionInfo info) {
4523        synchronized (mPackages) {
4524            return addPermissionLocked(info, true);
4525        }
4526    }
4527
4528    @Override
4529    public void removePermission(String name) {
4530        synchronized (mPackages) {
4531            checkPermissionTreeLP(name);
4532            BasePermission bp = mSettings.mPermissions.get(name);
4533            if (bp != null) {
4534                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4535                    throw new SecurityException(
4536                            "Not allowed to modify non-dynamic permission "
4537                            + name);
4538                }
4539                mSettings.mPermissions.remove(name);
4540                mSettings.writeLPr();
4541            }
4542        }
4543    }
4544
4545    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4546            BasePermission bp) {
4547        int index = pkg.requestedPermissions.indexOf(bp.name);
4548        if (index == -1) {
4549            throw new SecurityException("Package " + pkg.packageName
4550                    + " has not requested permission " + bp.name);
4551        }
4552        if (!bp.isRuntime() && !bp.isDevelopment()) {
4553            throw new SecurityException("Permission " + bp.name
4554                    + " is not a changeable permission type");
4555        }
4556    }
4557
4558    @Override
4559    public void grantRuntimePermission(String packageName, String name, final int userId) {
4560        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4561    }
4562
4563    private void grantRuntimePermission(String packageName, String name, final int userId,
4564            boolean overridePolicy) {
4565        if (!sUserManager.exists(userId)) {
4566            Log.e(TAG, "No such user:" + userId);
4567            return;
4568        }
4569
4570        mContext.enforceCallingOrSelfPermission(
4571                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4572                "grantRuntimePermission");
4573
4574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4575                true /* requireFullPermission */, true /* checkShell */,
4576                "grantRuntimePermission");
4577
4578        final int uid;
4579        final SettingBase sb;
4580
4581        synchronized (mPackages) {
4582            final PackageParser.Package pkg = mPackages.get(packageName);
4583            if (pkg == null) {
4584                throw new IllegalArgumentException("Unknown package: " + packageName);
4585            }
4586
4587            final BasePermission bp = mSettings.mPermissions.get(name);
4588            if (bp == null) {
4589                throw new IllegalArgumentException("Unknown permission: " + name);
4590            }
4591
4592            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4593
4594            // If a permission review is required for legacy apps we represent
4595            // their permissions as always granted runtime ones since we need
4596            // to keep the review required permission flag per user while an
4597            // install permission's state is shared across all users.
4598            if (mPermissionReviewRequired
4599                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4600                    && bp.isRuntime()) {
4601                return;
4602            }
4603
4604            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4605            sb = (SettingBase) pkg.mExtras;
4606            if (sb == null) {
4607                throw new IllegalArgumentException("Unknown package: " + packageName);
4608            }
4609
4610            final PermissionsState permissionsState = sb.getPermissionsState();
4611
4612            final int flags = permissionsState.getPermissionFlags(name, userId);
4613            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4614                throw new SecurityException("Cannot grant system fixed permission "
4615                        + name + " for package " + packageName);
4616            }
4617            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4618                throw new SecurityException("Cannot grant policy fixed permission "
4619                        + name + " for package " + packageName);
4620            }
4621
4622            if (bp.isDevelopment()) {
4623                // Development permissions must be handled specially, since they are not
4624                // normal runtime permissions.  For now they apply to all users.
4625                if (permissionsState.grantInstallPermission(bp) !=
4626                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4627                    scheduleWriteSettingsLocked();
4628                }
4629                return;
4630            }
4631
4632            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4633                throw new SecurityException("Cannot grant non-ephemeral permission"
4634                        + name + " for package " + packageName);
4635            }
4636
4637            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4638                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4639                return;
4640            }
4641
4642            final int result = permissionsState.grantRuntimePermission(bp, userId);
4643            switch (result) {
4644                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4645                    return;
4646                }
4647
4648                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4649                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4650                    mHandler.post(new Runnable() {
4651                        @Override
4652                        public void run() {
4653                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4654                        }
4655                    });
4656                }
4657                break;
4658            }
4659
4660            if (bp.isRuntime()) {
4661                logPermissionGranted(mContext, name, packageName);
4662            }
4663
4664            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4665
4666            // Not critical if that is lost - app has to request again.
4667            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4668        }
4669
4670        // Only need to do this if user is initialized. Otherwise it's a new user
4671        // and there are no processes running as the user yet and there's no need
4672        // to make an expensive call to remount processes for the changed permissions.
4673        if (READ_EXTERNAL_STORAGE.equals(name)
4674                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4675            final long token = Binder.clearCallingIdentity();
4676            try {
4677                if (sUserManager.isInitialized(userId)) {
4678                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4679                            StorageManagerInternal.class);
4680                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4681                }
4682            } finally {
4683                Binder.restoreCallingIdentity(token);
4684            }
4685        }
4686    }
4687
4688    @Override
4689    public void revokeRuntimePermission(String packageName, String name, int userId) {
4690        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4691    }
4692
4693    private void revokeRuntimePermission(String packageName, String name, int userId,
4694            boolean overridePolicy) {
4695        if (!sUserManager.exists(userId)) {
4696            Log.e(TAG, "No such user:" + userId);
4697            return;
4698        }
4699
4700        mContext.enforceCallingOrSelfPermission(
4701                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4702                "revokeRuntimePermission");
4703
4704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4705                true /* requireFullPermission */, true /* checkShell */,
4706                "revokeRuntimePermission");
4707
4708        final int appId;
4709
4710        synchronized (mPackages) {
4711            final PackageParser.Package pkg = mPackages.get(packageName);
4712            if (pkg == null) {
4713                throw new IllegalArgumentException("Unknown package: " + packageName);
4714            }
4715
4716            final BasePermission bp = mSettings.mPermissions.get(name);
4717            if (bp == null) {
4718                throw new IllegalArgumentException("Unknown permission: " + name);
4719            }
4720
4721            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4722
4723            // If a permission review is required for legacy apps we represent
4724            // their permissions as always granted runtime ones since we need
4725            // to keep the review required permission flag per user while an
4726            // install permission's state is shared across all users.
4727            if (mPermissionReviewRequired
4728                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4729                    && bp.isRuntime()) {
4730                return;
4731            }
4732
4733            SettingBase sb = (SettingBase) pkg.mExtras;
4734            if (sb == null) {
4735                throw new IllegalArgumentException("Unknown package: " + packageName);
4736            }
4737
4738            final PermissionsState permissionsState = sb.getPermissionsState();
4739
4740            final int flags = permissionsState.getPermissionFlags(name, userId);
4741            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4742                throw new SecurityException("Cannot revoke system fixed permission "
4743                        + name + " for package " + packageName);
4744            }
4745            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4746                throw new SecurityException("Cannot revoke policy fixed permission "
4747                        + name + " for package " + packageName);
4748            }
4749
4750            if (bp.isDevelopment()) {
4751                // Development permissions must be handled specially, since they are not
4752                // normal runtime permissions.  For now they apply to all users.
4753                if (permissionsState.revokeInstallPermission(bp) !=
4754                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4755                    scheduleWriteSettingsLocked();
4756                }
4757                return;
4758            }
4759
4760            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4761                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4762                return;
4763            }
4764
4765            if (bp.isRuntime()) {
4766                logPermissionRevoked(mContext, name, packageName);
4767            }
4768
4769            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4770
4771            // Critical, after this call app should never have the permission.
4772            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4773
4774            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4775        }
4776
4777        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4778    }
4779
4780    /**
4781     * Get the first event id for the permission.
4782     *
4783     * <p>There are four events for each permission: <ul>
4784     *     <li>Request permission: first id + 0</li>
4785     *     <li>Grant permission: first id + 1</li>
4786     *     <li>Request for permission denied: first id + 2</li>
4787     *     <li>Revoke permission: first id + 3</li>
4788     * </ul></p>
4789     *
4790     * @param name name of the permission
4791     *
4792     * @return The first event id for the permission
4793     */
4794    private static int getBaseEventId(@NonNull String name) {
4795        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4796
4797        if (eventIdIndex == -1) {
4798            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4799                    || "user".equals(Build.TYPE)) {
4800                Log.i(TAG, "Unknown permission " + name);
4801
4802                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4803            } else {
4804                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4805                //
4806                // Also update
4807                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4808                // - metrics_constants.proto
4809                throw new IllegalStateException("Unknown permission " + name);
4810            }
4811        }
4812
4813        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4814    }
4815
4816    /**
4817     * Log that a permission was revoked.
4818     *
4819     * @param context Context of the caller
4820     * @param name name of the permission
4821     * @param packageName package permission if for
4822     */
4823    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4824            @NonNull String packageName) {
4825        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4826    }
4827
4828    /**
4829     * Log that a permission request was granted.
4830     *
4831     * @param context Context of the caller
4832     * @param name name of the permission
4833     * @param packageName package permission if for
4834     */
4835    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4836            @NonNull String packageName) {
4837        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4838    }
4839
4840    @Override
4841    public void resetRuntimePermissions() {
4842        mContext.enforceCallingOrSelfPermission(
4843                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4844                "revokeRuntimePermission");
4845
4846        int callingUid = Binder.getCallingUid();
4847        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4848            mContext.enforceCallingOrSelfPermission(
4849                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4850                    "resetRuntimePermissions");
4851        }
4852
4853        synchronized (mPackages) {
4854            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4855            for (int userId : UserManagerService.getInstance().getUserIds()) {
4856                final int packageCount = mPackages.size();
4857                for (int i = 0; i < packageCount; i++) {
4858                    PackageParser.Package pkg = mPackages.valueAt(i);
4859                    if (!(pkg.mExtras instanceof PackageSetting)) {
4860                        continue;
4861                    }
4862                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4863                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4864                }
4865            }
4866        }
4867    }
4868
4869    @Override
4870    public int getPermissionFlags(String name, String packageName, int userId) {
4871        if (!sUserManager.exists(userId)) {
4872            return 0;
4873        }
4874
4875        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4876
4877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4878                true /* requireFullPermission */, false /* checkShell */,
4879                "getPermissionFlags");
4880
4881        synchronized (mPackages) {
4882            final PackageParser.Package pkg = mPackages.get(packageName);
4883            if (pkg == null) {
4884                return 0;
4885            }
4886
4887            final BasePermission bp = mSettings.mPermissions.get(name);
4888            if (bp == null) {
4889                return 0;
4890            }
4891
4892            SettingBase sb = (SettingBase) pkg.mExtras;
4893            if (sb == null) {
4894                return 0;
4895            }
4896
4897            PermissionsState permissionsState = sb.getPermissionsState();
4898            return permissionsState.getPermissionFlags(name, userId);
4899        }
4900    }
4901
4902    @Override
4903    public void updatePermissionFlags(String name, String packageName, int flagMask,
4904            int flagValues, int userId) {
4905        if (!sUserManager.exists(userId)) {
4906            return;
4907        }
4908
4909        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4910
4911        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4912                true /* requireFullPermission */, true /* checkShell */,
4913                "updatePermissionFlags");
4914
4915        // Only the system can change these flags and nothing else.
4916        if (getCallingUid() != Process.SYSTEM_UID) {
4917            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4918            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4919            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4920            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4921            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4922        }
4923
4924        synchronized (mPackages) {
4925            final PackageParser.Package pkg = mPackages.get(packageName);
4926            if (pkg == null) {
4927                throw new IllegalArgumentException("Unknown package: " + packageName);
4928            }
4929
4930            final BasePermission bp = mSettings.mPermissions.get(name);
4931            if (bp == null) {
4932                throw new IllegalArgumentException("Unknown permission: " + name);
4933            }
4934
4935            SettingBase sb = (SettingBase) pkg.mExtras;
4936            if (sb == null) {
4937                throw new IllegalArgumentException("Unknown package: " + packageName);
4938            }
4939
4940            PermissionsState permissionsState = sb.getPermissionsState();
4941
4942            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4943
4944            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4945                // Install and runtime permissions are stored in different places,
4946                // so figure out what permission changed and persist the change.
4947                if (permissionsState.getInstallPermissionState(name) != null) {
4948                    scheduleWriteSettingsLocked();
4949                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4950                        || hadState) {
4951                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4952                }
4953            }
4954        }
4955    }
4956
4957    /**
4958     * Update the permission flags for all packages and runtime permissions of a user in order
4959     * to allow device or profile owner to remove POLICY_FIXED.
4960     */
4961    @Override
4962    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4963        if (!sUserManager.exists(userId)) {
4964            return;
4965        }
4966
4967        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4968
4969        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4970                true /* requireFullPermission */, true /* checkShell */,
4971                "updatePermissionFlagsForAllApps");
4972
4973        // Only the system can change system fixed flags.
4974        if (getCallingUid() != Process.SYSTEM_UID) {
4975            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4976            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4977        }
4978
4979        synchronized (mPackages) {
4980            boolean changed = false;
4981            final int packageCount = mPackages.size();
4982            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4983                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4984                SettingBase sb = (SettingBase) pkg.mExtras;
4985                if (sb == null) {
4986                    continue;
4987                }
4988                PermissionsState permissionsState = sb.getPermissionsState();
4989                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4990                        userId, flagMask, flagValues);
4991            }
4992            if (changed) {
4993                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4994            }
4995        }
4996    }
4997
4998    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4999        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5000                != PackageManager.PERMISSION_GRANTED
5001            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5002                != PackageManager.PERMISSION_GRANTED) {
5003            throw new SecurityException(message + " requires "
5004                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5005                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5006        }
5007    }
5008
5009    @Override
5010    public boolean shouldShowRequestPermissionRationale(String permissionName,
5011            String packageName, int userId) {
5012        if (UserHandle.getCallingUserId() != userId) {
5013            mContext.enforceCallingPermission(
5014                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5015                    "canShowRequestPermissionRationale for user " + userId);
5016        }
5017
5018        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5019        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5020            return false;
5021        }
5022
5023        if (checkPermission(permissionName, packageName, userId)
5024                == PackageManager.PERMISSION_GRANTED) {
5025            return false;
5026        }
5027
5028        final int flags;
5029
5030        final long identity = Binder.clearCallingIdentity();
5031        try {
5032            flags = getPermissionFlags(permissionName,
5033                    packageName, userId);
5034        } finally {
5035            Binder.restoreCallingIdentity(identity);
5036        }
5037
5038        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5039                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5040                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5041
5042        if ((flags & fixedFlags) != 0) {
5043            return false;
5044        }
5045
5046        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5047    }
5048
5049    @Override
5050    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5051        mContext.enforceCallingOrSelfPermission(
5052                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5053                "addOnPermissionsChangeListener");
5054
5055        synchronized (mPackages) {
5056            mOnPermissionChangeListeners.addListenerLocked(listener);
5057        }
5058    }
5059
5060    @Override
5061    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5062        synchronized (mPackages) {
5063            mOnPermissionChangeListeners.removeListenerLocked(listener);
5064        }
5065    }
5066
5067    @Override
5068    public boolean isProtectedBroadcast(String actionName) {
5069        synchronized (mPackages) {
5070            if (mProtectedBroadcasts.contains(actionName)) {
5071                return true;
5072            } else if (actionName != null) {
5073                // TODO: remove these terrible hacks
5074                if (actionName.startsWith("android.net.netmon.lingerExpired")
5075                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5076                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5077                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5078                    return true;
5079                }
5080            }
5081        }
5082        return false;
5083    }
5084
5085    @Override
5086    public int checkSignatures(String pkg1, String pkg2) {
5087        synchronized (mPackages) {
5088            final PackageParser.Package p1 = mPackages.get(pkg1);
5089            final PackageParser.Package p2 = mPackages.get(pkg2);
5090            if (p1 == null || p1.mExtras == null
5091                    || p2 == null || p2.mExtras == null) {
5092                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5093            }
5094            return compareSignatures(p1.mSignatures, p2.mSignatures);
5095        }
5096    }
5097
5098    @Override
5099    public int checkUidSignatures(int uid1, int uid2) {
5100        // Map to base uids.
5101        uid1 = UserHandle.getAppId(uid1);
5102        uid2 = UserHandle.getAppId(uid2);
5103        // reader
5104        synchronized (mPackages) {
5105            Signature[] s1;
5106            Signature[] s2;
5107            Object obj = mSettings.getUserIdLPr(uid1);
5108            if (obj != null) {
5109                if (obj instanceof SharedUserSetting) {
5110                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5111                } else if (obj instanceof PackageSetting) {
5112                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5113                } else {
5114                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5115                }
5116            } else {
5117                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5118            }
5119            obj = mSettings.getUserIdLPr(uid2);
5120            if (obj != null) {
5121                if (obj instanceof SharedUserSetting) {
5122                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5123                } else if (obj instanceof PackageSetting) {
5124                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5125                } else {
5126                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5127                }
5128            } else {
5129                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5130            }
5131            return compareSignatures(s1, s2);
5132        }
5133    }
5134
5135    /**
5136     * This method should typically only be used when granting or revoking
5137     * permissions, since the app may immediately restart after this call.
5138     * <p>
5139     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5140     * guard your work against the app being relaunched.
5141     */
5142    private void killUid(int appId, int userId, String reason) {
5143        final long identity = Binder.clearCallingIdentity();
5144        try {
5145            IActivityManager am = ActivityManager.getService();
5146            if (am != null) {
5147                try {
5148                    am.killUid(appId, userId, reason);
5149                } catch (RemoteException e) {
5150                    /* ignore - same process */
5151                }
5152            }
5153        } finally {
5154            Binder.restoreCallingIdentity(identity);
5155        }
5156    }
5157
5158    /**
5159     * Compares two sets of signatures. Returns:
5160     * <br />
5161     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5162     * <br />
5163     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5164     * <br />
5165     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5166     * <br />
5167     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5168     * <br />
5169     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5170     */
5171    static int compareSignatures(Signature[] s1, Signature[] s2) {
5172        if (s1 == null) {
5173            return s2 == null
5174                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5175                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5176        }
5177
5178        if (s2 == null) {
5179            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5180        }
5181
5182        if (s1.length != s2.length) {
5183            return PackageManager.SIGNATURE_NO_MATCH;
5184        }
5185
5186        // Since both signature sets are of size 1, we can compare without HashSets.
5187        if (s1.length == 1) {
5188            return s1[0].equals(s2[0]) ?
5189                    PackageManager.SIGNATURE_MATCH :
5190                    PackageManager.SIGNATURE_NO_MATCH;
5191        }
5192
5193        ArraySet<Signature> set1 = new ArraySet<Signature>();
5194        for (Signature sig : s1) {
5195            set1.add(sig);
5196        }
5197        ArraySet<Signature> set2 = new ArraySet<Signature>();
5198        for (Signature sig : s2) {
5199            set2.add(sig);
5200        }
5201        // Make sure s2 contains all signatures in s1.
5202        if (set1.equals(set2)) {
5203            return PackageManager.SIGNATURE_MATCH;
5204        }
5205        return PackageManager.SIGNATURE_NO_MATCH;
5206    }
5207
5208    /**
5209     * If the database version for this type of package (internal storage or
5210     * external storage) is less than the version where package signatures
5211     * were updated, return true.
5212     */
5213    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5214        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5215        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5216    }
5217
5218    /**
5219     * Used for backward compatibility to make sure any packages with
5220     * certificate chains get upgraded to the new style. {@code existingSigs}
5221     * will be in the old format (since they were stored on disk from before the
5222     * system upgrade) and {@code scannedSigs} will be in the newer format.
5223     */
5224    private int compareSignaturesCompat(PackageSignatures existingSigs,
5225            PackageParser.Package scannedPkg) {
5226        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5227            return PackageManager.SIGNATURE_NO_MATCH;
5228        }
5229
5230        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5231        for (Signature sig : existingSigs.mSignatures) {
5232            existingSet.add(sig);
5233        }
5234        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5235        for (Signature sig : scannedPkg.mSignatures) {
5236            try {
5237                Signature[] chainSignatures = sig.getChainSignatures();
5238                for (Signature chainSig : chainSignatures) {
5239                    scannedCompatSet.add(chainSig);
5240                }
5241            } catch (CertificateEncodingException e) {
5242                scannedCompatSet.add(sig);
5243            }
5244        }
5245        /*
5246         * Make sure the expanded scanned set contains all signatures in the
5247         * existing one.
5248         */
5249        if (scannedCompatSet.equals(existingSet)) {
5250            // Migrate the old signatures to the new scheme.
5251            existingSigs.assignSignatures(scannedPkg.mSignatures);
5252            // The new KeySets will be re-added later in the scanning process.
5253            synchronized (mPackages) {
5254                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5255            }
5256            return PackageManager.SIGNATURE_MATCH;
5257        }
5258        return PackageManager.SIGNATURE_NO_MATCH;
5259    }
5260
5261    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5262        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5263        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5264    }
5265
5266    private int compareSignaturesRecover(PackageSignatures existingSigs,
5267            PackageParser.Package scannedPkg) {
5268        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5269            return PackageManager.SIGNATURE_NO_MATCH;
5270        }
5271
5272        String msg = null;
5273        try {
5274            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5275                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5276                        + scannedPkg.packageName);
5277                return PackageManager.SIGNATURE_MATCH;
5278            }
5279        } catch (CertificateException e) {
5280            msg = e.getMessage();
5281        }
5282
5283        logCriticalInfo(Log.INFO,
5284                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5285        return PackageManager.SIGNATURE_NO_MATCH;
5286    }
5287
5288    @Override
5289    public List<String> getAllPackages() {
5290        synchronized (mPackages) {
5291            return new ArrayList<String>(mPackages.keySet());
5292        }
5293    }
5294
5295    @Override
5296    public String[] getPackagesForUid(int uid) {
5297        final int userId = UserHandle.getUserId(uid);
5298        uid = UserHandle.getAppId(uid);
5299        // reader
5300        synchronized (mPackages) {
5301            Object obj = mSettings.getUserIdLPr(uid);
5302            if (obj instanceof SharedUserSetting) {
5303                final SharedUserSetting sus = (SharedUserSetting) obj;
5304                final int N = sus.packages.size();
5305                String[] res = new String[N];
5306                final Iterator<PackageSetting> it = sus.packages.iterator();
5307                int i = 0;
5308                while (it.hasNext()) {
5309                    PackageSetting ps = it.next();
5310                    if (ps.getInstalled(userId)) {
5311                        res[i++] = ps.name;
5312                    } else {
5313                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5314                    }
5315                }
5316                return res;
5317            } else if (obj instanceof PackageSetting) {
5318                final PackageSetting ps = (PackageSetting) obj;
5319                if (ps.getInstalled(userId)) {
5320                    return new String[]{ps.name};
5321                }
5322            }
5323        }
5324        return null;
5325    }
5326
5327    @Override
5328    public String getNameForUid(int uid) {
5329        // reader
5330        synchronized (mPackages) {
5331            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5332            if (obj instanceof SharedUserSetting) {
5333                final SharedUserSetting sus = (SharedUserSetting) obj;
5334                return sus.name + ":" + sus.userId;
5335            } else if (obj instanceof PackageSetting) {
5336                final PackageSetting ps = (PackageSetting) obj;
5337                return ps.name;
5338            }
5339        }
5340        return null;
5341    }
5342
5343    @Override
5344    public int getUidForSharedUser(String sharedUserName) {
5345        if(sharedUserName == null) {
5346            return -1;
5347        }
5348        // reader
5349        synchronized (mPackages) {
5350            SharedUserSetting suid;
5351            try {
5352                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5353                if (suid != null) {
5354                    return suid.userId;
5355                }
5356            } catch (PackageManagerException ignore) {
5357                // can't happen, but, still need to catch it
5358            }
5359            return -1;
5360        }
5361    }
5362
5363    @Override
5364    public int getFlagsForUid(int uid) {
5365        synchronized (mPackages) {
5366            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5367            if (obj instanceof SharedUserSetting) {
5368                final SharedUserSetting sus = (SharedUserSetting) obj;
5369                return sus.pkgFlags;
5370            } else if (obj instanceof PackageSetting) {
5371                final PackageSetting ps = (PackageSetting) obj;
5372                return ps.pkgFlags;
5373            }
5374        }
5375        return 0;
5376    }
5377
5378    @Override
5379    public int getPrivateFlagsForUid(int uid) {
5380        synchronized (mPackages) {
5381            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5382            if (obj instanceof SharedUserSetting) {
5383                final SharedUserSetting sus = (SharedUserSetting) obj;
5384                return sus.pkgPrivateFlags;
5385            } else if (obj instanceof PackageSetting) {
5386                final PackageSetting ps = (PackageSetting) obj;
5387                return ps.pkgPrivateFlags;
5388            }
5389        }
5390        return 0;
5391    }
5392
5393    @Override
5394    public boolean isUidPrivileged(int uid) {
5395        uid = UserHandle.getAppId(uid);
5396        // reader
5397        synchronized (mPackages) {
5398            Object obj = mSettings.getUserIdLPr(uid);
5399            if (obj instanceof SharedUserSetting) {
5400                final SharedUserSetting sus = (SharedUserSetting) obj;
5401                final Iterator<PackageSetting> it = sus.packages.iterator();
5402                while (it.hasNext()) {
5403                    if (it.next().isPrivileged()) {
5404                        return true;
5405                    }
5406                }
5407            } else if (obj instanceof PackageSetting) {
5408                final PackageSetting ps = (PackageSetting) obj;
5409                return ps.isPrivileged();
5410            }
5411        }
5412        return false;
5413    }
5414
5415    @Override
5416    public String[] getAppOpPermissionPackages(String permissionName) {
5417        synchronized (mPackages) {
5418            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5419            if (pkgs == null) {
5420                return null;
5421            }
5422            return pkgs.toArray(new String[pkgs.size()]);
5423        }
5424    }
5425
5426    @Override
5427    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5428            int flags, int userId) {
5429        try {
5430            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5431
5432            if (!sUserManager.exists(userId)) return null;
5433            flags = updateFlagsForResolve(flags, userId, intent);
5434            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5435                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5436
5437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5438            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5439                    flags, userId);
5440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5441
5442            final ResolveInfo bestChoice =
5443                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5444            return bestChoice;
5445        } finally {
5446            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5447        }
5448    }
5449
5450    @Override
5451    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5452        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5453            throw new SecurityException(
5454                    "findPersistentPreferredActivity can only be run by the system");
5455        }
5456        if (!sUserManager.exists(userId)) {
5457            return null;
5458        }
5459        intent = updateIntentForResolve(intent);
5460        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5461        final int flags = updateFlagsForResolve(0, userId, intent);
5462        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5463                userId);
5464        synchronized (mPackages) {
5465            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5466                    userId);
5467        }
5468    }
5469
5470    @Override
5471    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5472            IntentFilter filter, int match, ComponentName activity) {
5473        final int userId = UserHandle.getCallingUserId();
5474        if (DEBUG_PREFERRED) {
5475            Log.v(TAG, "setLastChosenActivity intent=" + intent
5476                + " resolvedType=" + resolvedType
5477                + " flags=" + flags
5478                + " filter=" + filter
5479                + " match=" + match
5480                + " activity=" + activity);
5481            filter.dump(new PrintStreamPrinter(System.out), "    ");
5482        }
5483        intent.setComponent(null);
5484        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5485                userId);
5486        // Find any earlier preferred or last chosen entries and nuke them
5487        findPreferredActivity(intent, resolvedType,
5488                flags, query, 0, false, true, false, userId);
5489        // Add the new activity as the last chosen for this filter
5490        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5491                "Setting last chosen");
5492    }
5493
5494    @Override
5495    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5496        final int userId = UserHandle.getCallingUserId();
5497        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5498        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5499                userId);
5500        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5501                false, false, false, userId);
5502    }
5503
5504    private boolean isEphemeralDisabled() {
5505        // ephemeral apps have been disabled across the board
5506        if (DISABLE_EPHEMERAL_APPS) {
5507            return true;
5508        }
5509        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5510        if (!mSystemReady) {
5511            return true;
5512        }
5513        // we can't get a content resolver until the system is ready; these checks must happen last
5514        final ContentResolver resolver = mContext.getContentResolver();
5515        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5516            return true;
5517        }
5518        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5519    }
5520
5521    private boolean isEphemeralAllowed(
5522            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5523            boolean skipPackageCheck) {
5524        // Short circuit and return early if possible.
5525        if (isEphemeralDisabled()) {
5526            return false;
5527        }
5528        final int callingUser = UserHandle.getCallingUserId();
5529        if (callingUser != UserHandle.USER_SYSTEM) {
5530            return false;
5531        }
5532        if (mEphemeralResolverConnection == null) {
5533            return false;
5534        }
5535        if (mEphemeralInstallerComponent == null) {
5536            return false;
5537        }
5538        if (intent.getComponent() != null) {
5539            return false;
5540        }
5541        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5542            return false;
5543        }
5544        if (!skipPackageCheck && intent.getPackage() != null) {
5545            return false;
5546        }
5547        final boolean isWebUri = hasWebURI(intent);
5548        if (!isWebUri || intent.getData().getHost() == null) {
5549            return false;
5550        }
5551        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5552        synchronized (mPackages) {
5553            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5554            for (int n = 0; n < count; n++) {
5555                ResolveInfo info = resolvedActivities.get(n);
5556                String packageName = info.activityInfo.packageName;
5557                PackageSetting ps = mSettings.mPackages.get(packageName);
5558                if (ps != null) {
5559                    // Try to get the status from User settings first
5560                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5561                    int status = (int) (packedStatus >> 32);
5562                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5563                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5564                        if (DEBUG_EPHEMERAL) {
5565                            Slog.v(TAG, "DENY ephemeral apps;"
5566                                + " pkg: " + packageName + ", status: " + status);
5567                        }
5568                        return false;
5569                    }
5570                }
5571            }
5572        }
5573        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5574        return true;
5575    }
5576
5577    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5578            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5579            int userId) {
5580        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5581                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5582                        callingPackage, userId));
5583        mHandler.sendMessage(msg);
5584    }
5585
5586    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5587            int flags, List<ResolveInfo> query, int userId) {
5588        if (query != null) {
5589            final int N = query.size();
5590            if (N == 1) {
5591                return query.get(0);
5592            } else if (N > 1) {
5593                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5594                // If there is more than one activity with the same priority,
5595                // then let the user decide between them.
5596                ResolveInfo r0 = query.get(0);
5597                ResolveInfo r1 = query.get(1);
5598                if (DEBUG_INTENT_MATCHING || debug) {
5599                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5600                            + r1.activityInfo.name + "=" + r1.priority);
5601                }
5602                // If the first activity has a higher priority, or a different
5603                // default, then it is always desirable to pick it.
5604                if (r0.priority != r1.priority
5605                        || r0.preferredOrder != r1.preferredOrder
5606                        || r0.isDefault != r1.isDefault) {
5607                    return query.get(0);
5608                }
5609                // If we have saved a preference for a preferred activity for
5610                // this Intent, use that.
5611                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5612                        flags, query, r0.priority, true, false, debug, userId);
5613                if (ri != null) {
5614                    return ri;
5615                }
5616                ri = new ResolveInfo(mResolveInfo);
5617                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5618                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5619                // If all of the options come from the same package, show the application's
5620                // label and icon instead of the generic resolver's.
5621                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5622                // and then throw away the ResolveInfo itself, meaning that the caller loses
5623                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5624                // a fallback for this case; we only set the target package's resources on
5625                // the ResolveInfo, not the ActivityInfo.
5626                final String intentPackage = intent.getPackage();
5627                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5628                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5629                    ri.resolvePackageName = intentPackage;
5630                    if (userNeedsBadging(userId)) {
5631                        ri.noResourceId = true;
5632                    } else {
5633                        ri.icon = appi.icon;
5634                    }
5635                    ri.iconResourceId = appi.icon;
5636                    ri.labelRes = appi.labelRes;
5637                }
5638                ri.activityInfo.applicationInfo = new ApplicationInfo(
5639                        ri.activityInfo.applicationInfo);
5640                if (userId != 0) {
5641                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5642                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5643                }
5644                // Make sure that the resolver is displayable in car mode
5645                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5646                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5647                return ri;
5648            }
5649        }
5650        return null;
5651    }
5652
5653    /**
5654     * Return true if the given list is not empty and all of its contents have
5655     * an activityInfo with the given package name.
5656     */
5657    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5658        if (ArrayUtils.isEmpty(list)) {
5659            return false;
5660        }
5661        for (int i = 0, N = list.size(); i < N; i++) {
5662            final ResolveInfo ri = list.get(i);
5663            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5664            if (ai == null || !packageName.equals(ai.packageName)) {
5665                return false;
5666            }
5667        }
5668        return true;
5669    }
5670
5671    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5672            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5673        final int N = query.size();
5674        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5675                .get(userId);
5676        // Get the list of persistent preferred activities that handle the intent
5677        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5678        List<PersistentPreferredActivity> pprefs = ppir != null
5679                ? ppir.queryIntent(intent, resolvedType,
5680                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5681                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5682                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5683                : null;
5684        if (pprefs != null && pprefs.size() > 0) {
5685            final int M = pprefs.size();
5686            for (int i=0; i<M; i++) {
5687                final PersistentPreferredActivity ppa = pprefs.get(i);
5688                if (DEBUG_PREFERRED || debug) {
5689                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5690                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5691                            + "\n  component=" + ppa.mComponent);
5692                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5693                }
5694                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5695                        flags | MATCH_DISABLED_COMPONENTS, userId);
5696                if (DEBUG_PREFERRED || debug) {
5697                    Slog.v(TAG, "Found persistent preferred activity:");
5698                    if (ai != null) {
5699                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5700                    } else {
5701                        Slog.v(TAG, "  null");
5702                    }
5703                }
5704                if (ai == null) {
5705                    // This previously registered persistent preferred activity
5706                    // component is no longer known. Ignore it and do NOT remove it.
5707                    continue;
5708                }
5709                for (int j=0; j<N; j++) {
5710                    final ResolveInfo ri = query.get(j);
5711                    if (!ri.activityInfo.applicationInfo.packageName
5712                            .equals(ai.applicationInfo.packageName)) {
5713                        continue;
5714                    }
5715                    if (!ri.activityInfo.name.equals(ai.name)) {
5716                        continue;
5717                    }
5718                    //  Found a persistent preference that can handle the intent.
5719                    if (DEBUG_PREFERRED || debug) {
5720                        Slog.v(TAG, "Returning persistent preferred activity: " +
5721                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5722                    }
5723                    return ri;
5724                }
5725            }
5726        }
5727        return null;
5728    }
5729
5730    // TODO: handle preferred activities missing while user has amnesia
5731    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5732            List<ResolveInfo> query, int priority, boolean always,
5733            boolean removeMatches, boolean debug, int userId) {
5734        if (!sUserManager.exists(userId)) return null;
5735        flags = updateFlagsForResolve(flags, userId, intent);
5736        intent = updateIntentForResolve(intent);
5737        // writer
5738        synchronized (mPackages) {
5739            // Try to find a matching persistent preferred activity.
5740            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5741                    debug, userId);
5742
5743            // If a persistent preferred activity matched, use it.
5744            if (pri != null) {
5745                return pri;
5746            }
5747
5748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5749            // Get the list of preferred activities that handle the intent
5750            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5751            List<PreferredActivity> prefs = pir != null
5752                    ? pir.queryIntent(intent, resolvedType,
5753                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5754                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5755                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5756                    : null;
5757            if (prefs != null && prefs.size() > 0) {
5758                boolean changed = false;
5759                try {
5760                    // First figure out how good the original match set is.
5761                    // We will only allow preferred activities that came
5762                    // from the same match quality.
5763                    int match = 0;
5764
5765                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5766
5767                    final int N = query.size();
5768                    for (int j=0; j<N; j++) {
5769                        final ResolveInfo ri = query.get(j);
5770                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5771                                + ": 0x" + Integer.toHexString(match));
5772                        if (ri.match > match) {
5773                            match = ri.match;
5774                        }
5775                    }
5776
5777                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5778                            + Integer.toHexString(match));
5779
5780                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5781                    final int M = prefs.size();
5782                    for (int i=0; i<M; i++) {
5783                        final PreferredActivity pa = prefs.get(i);
5784                        if (DEBUG_PREFERRED || debug) {
5785                            Slog.v(TAG, "Checking PreferredActivity ds="
5786                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5787                                    + "\n  component=" + pa.mPref.mComponent);
5788                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5789                        }
5790                        if (pa.mPref.mMatch != match) {
5791                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5792                                    + Integer.toHexString(pa.mPref.mMatch));
5793                            continue;
5794                        }
5795                        // If it's not an "always" type preferred activity and that's what we're
5796                        // looking for, skip it.
5797                        if (always && !pa.mPref.mAlways) {
5798                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5799                            continue;
5800                        }
5801                        final ActivityInfo ai = getActivityInfo(
5802                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5803                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5804                                userId);
5805                        if (DEBUG_PREFERRED || debug) {
5806                            Slog.v(TAG, "Found preferred activity:");
5807                            if (ai != null) {
5808                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5809                            } else {
5810                                Slog.v(TAG, "  null");
5811                            }
5812                        }
5813                        if (ai == null) {
5814                            // This previously registered preferred activity
5815                            // component is no longer known.  Most likely an update
5816                            // to the app was installed and in the new version this
5817                            // component no longer exists.  Clean it up by removing
5818                            // it from the preferred activities list, and skip it.
5819                            Slog.w(TAG, "Removing dangling preferred activity: "
5820                                    + pa.mPref.mComponent);
5821                            pir.removeFilter(pa);
5822                            changed = true;
5823                            continue;
5824                        }
5825                        for (int j=0; j<N; j++) {
5826                            final ResolveInfo ri = query.get(j);
5827                            if (!ri.activityInfo.applicationInfo.packageName
5828                                    .equals(ai.applicationInfo.packageName)) {
5829                                continue;
5830                            }
5831                            if (!ri.activityInfo.name.equals(ai.name)) {
5832                                continue;
5833                            }
5834
5835                            if (removeMatches) {
5836                                pir.removeFilter(pa);
5837                                changed = true;
5838                                if (DEBUG_PREFERRED) {
5839                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5840                                }
5841                                break;
5842                            }
5843
5844                            // Okay we found a previously set preferred or last chosen app.
5845                            // If the result set is different from when this
5846                            // was created, we need to clear it and re-ask the
5847                            // user their preference, if we're looking for an "always" type entry.
5848                            if (always && !pa.mPref.sameSet(query)) {
5849                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5850                                        + intent + " type " + resolvedType);
5851                                if (DEBUG_PREFERRED) {
5852                                    Slog.v(TAG, "Removing preferred activity since set changed "
5853                                            + pa.mPref.mComponent);
5854                                }
5855                                pir.removeFilter(pa);
5856                                // Re-add the filter as a "last chosen" entry (!always)
5857                                PreferredActivity lastChosen = new PreferredActivity(
5858                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5859                                pir.addFilter(lastChosen);
5860                                changed = true;
5861                                return null;
5862                            }
5863
5864                            // Yay! Either the set matched or we're looking for the last chosen
5865                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5866                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5867                            return ri;
5868                        }
5869                    }
5870                } finally {
5871                    if (changed) {
5872                        if (DEBUG_PREFERRED) {
5873                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5874                        }
5875                        scheduleWritePackageRestrictionsLocked(userId);
5876                    }
5877                }
5878            }
5879        }
5880        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5881        return null;
5882    }
5883
5884    /*
5885     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5886     */
5887    @Override
5888    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5889            int targetUserId) {
5890        mContext.enforceCallingOrSelfPermission(
5891                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5892        List<CrossProfileIntentFilter> matches =
5893                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5894        if (matches != null) {
5895            int size = matches.size();
5896            for (int i = 0; i < size; i++) {
5897                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5898            }
5899        }
5900        if (hasWebURI(intent)) {
5901            // cross-profile app linking works only towards the parent.
5902            final UserInfo parent = getProfileParent(sourceUserId);
5903            synchronized(mPackages) {
5904                int flags = updateFlagsForResolve(0, parent.id, intent);
5905                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5906                        intent, resolvedType, flags, sourceUserId, parent.id);
5907                return xpDomainInfo != null;
5908            }
5909        }
5910        return false;
5911    }
5912
5913    private UserInfo getProfileParent(int userId) {
5914        final long identity = Binder.clearCallingIdentity();
5915        try {
5916            return sUserManager.getProfileParent(userId);
5917        } finally {
5918            Binder.restoreCallingIdentity(identity);
5919        }
5920    }
5921
5922    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5923            String resolvedType, int userId) {
5924        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5925        if (resolver != null) {
5926            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5927                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5928        }
5929        return null;
5930    }
5931
5932    @Override
5933    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5934            String resolvedType, int flags, int userId) {
5935        try {
5936            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5937
5938            return new ParceledListSlice<>(
5939                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5940        } finally {
5941            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5942        }
5943    }
5944
5945    /**
5946     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5947     * ephemeral, returns {@code null}.
5948     */
5949    private String getEphemeralPackageName(int callingUid) {
5950        final int appId = UserHandle.getAppId(callingUid);
5951        synchronized (mPackages) {
5952            final Object obj = mSettings.getUserIdLPr(appId);
5953            if (obj instanceof PackageSetting) {
5954                final PackageSetting ps = (PackageSetting) obj;
5955                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
5956            }
5957        }
5958        return null;
5959    }
5960
5961    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5962            String resolvedType, int flags, int userId) {
5963        if (!sUserManager.exists(userId)) return Collections.emptyList();
5964        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5965        flags = updateFlagsForResolve(flags, userId, intent);
5966        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5967                false /* requireFullPermission */, false /* checkShell */,
5968                "query intent activities");
5969        ComponentName comp = intent.getComponent();
5970        if (comp == null) {
5971            if (intent.getSelector() != null) {
5972                intent = intent.getSelector();
5973                comp = intent.getComponent();
5974            }
5975        }
5976
5977        if (comp != null) {
5978            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5979            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5980            if (ai != null) {
5981                // When specifying an explicit component, we prevent the activity from being
5982                // used when either 1) the calling package is normal and the activity is within
5983                // an ephemeral application or 2) the calling package is ephemeral and the
5984                // activity is not visible to ephemeral applications.
5985                boolean matchEphemeral =
5986                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5987                boolean ephemeralVisibleOnly =
5988                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5989                boolean blockResolution =
5990                        (!matchEphemeral && ephemeralPkgName == null
5991                                && (ai.applicationInfo.privateFlags
5992                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5993                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5994                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5995                if (!blockResolution) {
5996                    final ResolveInfo ri = new ResolveInfo();
5997                    ri.activityInfo = ai;
5998                    list.add(ri);
5999                }
6000            }
6001            return list;
6002        }
6003
6004        // reader
6005        boolean sortResult = false;
6006        boolean addEphemeral = false;
6007        List<ResolveInfo> result;
6008        final String pkgName = intent.getPackage();
6009        synchronized (mPackages) {
6010            if (pkgName == null) {
6011                List<CrossProfileIntentFilter> matchingFilters =
6012                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6013                // Check for results that need to skip the current profile.
6014                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6015                        resolvedType, flags, userId);
6016                if (xpResolveInfo != null) {
6017                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6018                    xpResult.add(xpResolveInfo);
6019                    return filterForEphemeral(
6020                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6021                }
6022
6023                // Check for results in the current profile.
6024                result = filterIfNotSystemUser(mActivities.queryIntent(
6025                        intent, resolvedType, flags, userId), userId);
6026                addEphemeral =
6027                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6028
6029                // Check for cross profile results.
6030                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6031                xpResolveInfo = queryCrossProfileIntents(
6032                        matchingFilters, intent, resolvedType, flags, userId,
6033                        hasNonNegativePriorityResult);
6034                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6035                    boolean isVisibleToUser = filterIfNotSystemUser(
6036                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6037                    if (isVisibleToUser) {
6038                        result.add(xpResolveInfo);
6039                        sortResult = true;
6040                    }
6041                }
6042                if (hasWebURI(intent)) {
6043                    CrossProfileDomainInfo xpDomainInfo = null;
6044                    final UserInfo parent = getProfileParent(userId);
6045                    if (parent != null) {
6046                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6047                                flags, userId, parent.id);
6048                    }
6049                    if (xpDomainInfo != null) {
6050                        if (xpResolveInfo != null) {
6051                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6052                            // in the result.
6053                            result.remove(xpResolveInfo);
6054                        }
6055                        if (result.size() == 0 && !addEphemeral) {
6056                            // No result in current profile, but found candidate in parent user.
6057                            // And we are not going to add emphemeral app, so we can return the
6058                            // result straight away.
6059                            result.add(xpDomainInfo.resolveInfo);
6060                            return filterForEphemeral(result, ephemeralPkgName);
6061                        }
6062                    } else if (result.size() <= 1 && !addEphemeral) {
6063                        // No result in parent user and <= 1 result in current profile, and we
6064                        // are not going to add emphemeral app, so we can return the result without
6065                        // further processing.
6066                        return filterForEphemeral(result, ephemeralPkgName);
6067                    }
6068                    // We have more than one candidate (combining results from current and parent
6069                    // profile), so we need filtering and sorting.
6070                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6071                            intent, flags, result, xpDomainInfo, userId);
6072                    sortResult = true;
6073                }
6074            } else {
6075                final PackageParser.Package pkg = mPackages.get(pkgName);
6076                if (pkg != null) {
6077                    result = filterForEphemeral(filterIfNotSystemUser(
6078                            mActivities.queryIntentForPackage(
6079                                    intent, resolvedType, flags, pkg.activities, userId),
6080                            userId), ephemeralPkgName);
6081                } else {
6082                    // the caller wants to resolve for a particular package; however, there
6083                    // were no installed results, so, try to find an ephemeral result
6084                    addEphemeral = isEphemeralAllowed(
6085                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6086                    result = new ArrayList<ResolveInfo>();
6087                }
6088            }
6089        }
6090        if (addEphemeral) {
6091            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6092            final EphemeralRequest requestObject = new EphemeralRequest(
6093                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6094                    null /*launchIntent*/, null /*callingPackage*/, userId);
6095            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6096                    mContext, mEphemeralResolverConnection, requestObject);
6097            if (intentInfo != null) {
6098                if (DEBUG_EPHEMERAL) {
6099                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6100                }
6101                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6102                ephemeralInstaller.ephemeralResponse = intentInfo;
6103                // make sure this resolver is the default
6104                ephemeralInstaller.isDefault = true;
6105                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6106                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6107                // add a non-generic filter
6108                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6109                ephemeralInstaller.filter.addDataPath(
6110                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6111                result.add(ephemeralInstaller);
6112            }
6113            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6114        }
6115        if (sortResult) {
6116            Collections.sort(result, mResolvePrioritySorter);
6117        }
6118        return filterForEphemeral(result, ephemeralPkgName);
6119    }
6120
6121    private static class CrossProfileDomainInfo {
6122        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6123        ResolveInfo resolveInfo;
6124        /* Best domain verification status of the activities found in the other profile */
6125        int bestDomainVerificationStatus;
6126    }
6127
6128    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6129            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6130        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6131                sourceUserId)) {
6132            return null;
6133        }
6134        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6135                resolvedType, flags, parentUserId);
6136
6137        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6138            return null;
6139        }
6140        CrossProfileDomainInfo result = null;
6141        int size = resultTargetUser.size();
6142        for (int i = 0; i < size; i++) {
6143            ResolveInfo riTargetUser = resultTargetUser.get(i);
6144            // Intent filter verification is only for filters that specify a host. So don't return
6145            // those that handle all web uris.
6146            if (riTargetUser.handleAllWebDataURI) {
6147                continue;
6148            }
6149            String packageName = riTargetUser.activityInfo.packageName;
6150            PackageSetting ps = mSettings.mPackages.get(packageName);
6151            if (ps == null) {
6152                continue;
6153            }
6154            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6155            int status = (int)(verificationState >> 32);
6156            if (result == null) {
6157                result = new CrossProfileDomainInfo();
6158                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6159                        sourceUserId, parentUserId);
6160                result.bestDomainVerificationStatus = status;
6161            } else {
6162                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6163                        result.bestDomainVerificationStatus);
6164            }
6165        }
6166        // Don't consider matches with status NEVER across profiles.
6167        if (result != null && result.bestDomainVerificationStatus
6168                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6169            return null;
6170        }
6171        return result;
6172    }
6173
6174    /**
6175     * Verification statuses are ordered from the worse to the best, except for
6176     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6177     */
6178    private int bestDomainVerificationStatus(int status1, int status2) {
6179        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6180            return status2;
6181        }
6182        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6183            return status1;
6184        }
6185        return (int) MathUtils.max(status1, status2);
6186    }
6187
6188    private boolean isUserEnabled(int userId) {
6189        long callingId = Binder.clearCallingIdentity();
6190        try {
6191            UserInfo userInfo = sUserManager.getUserInfo(userId);
6192            return userInfo != null && userInfo.isEnabled();
6193        } finally {
6194            Binder.restoreCallingIdentity(callingId);
6195        }
6196    }
6197
6198    /**
6199     * Filter out activities with systemUserOnly flag set, when current user is not System.
6200     *
6201     * @return filtered list
6202     */
6203    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6204        if (userId == UserHandle.USER_SYSTEM) {
6205            return resolveInfos;
6206        }
6207        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6208            ResolveInfo info = resolveInfos.get(i);
6209            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6210                resolveInfos.remove(i);
6211            }
6212        }
6213        return resolveInfos;
6214    }
6215
6216    /**
6217     * Filters out ephemeral activities.
6218     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6219     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6220     *
6221     * @param resolveInfos The pre-filtered list of resolved activities
6222     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6223     *          is performed.
6224     * @return A filtered list of resolved activities.
6225     */
6226    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6227            String ephemeralPkgName) {
6228        if (ephemeralPkgName == null) {
6229            return resolveInfos;
6230        }
6231        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6232            ResolveInfo info = resolveInfos.get(i);
6233            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6234            // allow activities that are defined in the provided package
6235            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6236                continue;
6237            }
6238            // allow activities that have been explicitly exposed to ephemeral apps
6239            if (!isEphemeralApp
6240                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6241                continue;
6242            }
6243            resolveInfos.remove(i);
6244        }
6245        return resolveInfos;
6246    }
6247
6248    /**
6249     * @param resolveInfos list of resolve infos in descending priority order
6250     * @return if the list contains a resolve info with non-negative priority
6251     */
6252    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6253        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6254    }
6255
6256    private static boolean hasWebURI(Intent intent) {
6257        if (intent.getData() == null) {
6258            return false;
6259        }
6260        final String scheme = intent.getScheme();
6261        if (TextUtils.isEmpty(scheme)) {
6262            return false;
6263        }
6264        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6265    }
6266
6267    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6268            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6269            int userId) {
6270        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6271
6272        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6273            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6274                    candidates.size());
6275        }
6276
6277        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6278        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6279        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6280        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6281        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6282        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6283
6284        synchronized (mPackages) {
6285            final int count = candidates.size();
6286            // First, try to use linked apps. Partition the candidates into four lists:
6287            // one for the final results, one for the "do not use ever", one for "undefined status"
6288            // and finally one for "browser app type".
6289            for (int n=0; n<count; n++) {
6290                ResolveInfo info = candidates.get(n);
6291                String packageName = info.activityInfo.packageName;
6292                PackageSetting ps = mSettings.mPackages.get(packageName);
6293                if (ps != null) {
6294                    // Add to the special match all list (Browser use case)
6295                    if (info.handleAllWebDataURI) {
6296                        matchAllList.add(info);
6297                        continue;
6298                    }
6299                    // Try to get the status from User settings first
6300                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6301                    int status = (int)(packedStatus >> 32);
6302                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6303                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6304                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6305                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6306                                    + " : linkgen=" + linkGeneration);
6307                        }
6308                        // Use link-enabled generation as preferredOrder, i.e.
6309                        // prefer newly-enabled over earlier-enabled.
6310                        info.preferredOrder = linkGeneration;
6311                        alwaysList.add(info);
6312                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6313                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6314                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6315                        }
6316                        neverList.add(info);
6317                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6318                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6319                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6320                        }
6321                        alwaysAskList.add(info);
6322                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6323                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6324                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6325                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6326                        }
6327                        undefinedList.add(info);
6328                    }
6329                }
6330            }
6331
6332            // We'll want to include browser possibilities in a few cases
6333            boolean includeBrowser = false;
6334
6335            // First try to add the "always" resolution(s) for the current user, if any
6336            if (alwaysList.size() > 0) {
6337                result.addAll(alwaysList);
6338            } else {
6339                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6340                result.addAll(undefinedList);
6341                // Maybe add one for the other profile.
6342                if (xpDomainInfo != null && (
6343                        xpDomainInfo.bestDomainVerificationStatus
6344                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6345                    result.add(xpDomainInfo.resolveInfo);
6346                }
6347                includeBrowser = true;
6348            }
6349
6350            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6351            // If there were 'always' entries their preferred order has been set, so we also
6352            // back that off to make the alternatives equivalent
6353            if (alwaysAskList.size() > 0) {
6354                for (ResolveInfo i : result) {
6355                    i.preferredOrder = 0;
6356                }
6357                result.addAll(alwaysAskList);
6358                includeBrowser = true;
6359            }
6360
6361            if (includeBrowser) {
6362                // Also add browsers (all of them or only the default one)
6363                if (DEBUG_DOMAIN_VERIFICATION) {
6364                    Slog.v(TAG, "   ...including browsers in candidate set");
6365                }
6366                if ((matchFlags & MATCH_ALL) != 0) {
6367                    result.addAll(matchAllList);
6368                } else {
6369                    // Browser/generic handling case.  If there's a default browser, go straight
6370                    // to that (but only if there is no other higher-priority match).
6371                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6372                    int maxMatchPrio = 0;
6373                    ResolveInfo defaultBrowserMatch = null;
6374                    final int numCandidates = matchAllList.size();
6375                    for (int n = 0; n < numCandidates; n++) {
6376                        ResolveInfo info = matchAllList.get(n);
6377                        // track the highest overall match priority...
6378                        if (info.priority > maxMatchPrio) {
6379                            maxMatchPrio = info.priority;
6380                        }
6381                        // ...and the highest-priority default browser match
6382                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6383                            if (defaultBrowserMatch == null
6384                                    || (defaultBrowserMatch.priority < info.priority)) {
6385                                if (debug) {
6386                                    Slog.v(TAG, "Considering default browser match " + info);
6387                                }
6388                                defaultBrowserMatch = info;
6389                            }
6390                        }
6391                    }
6392                    if (defaultBrowserMatch != null
6393                            && defaultBrowserMatch.priority >= maxMatchPrio
6394                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6395                    {
6396                        if (debug) {
6397                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6398                        }
6399                        result.add(defaultBrowserMatch);
6400                    } else {
6401                        result.addAll(matchAllList);
6402                    }
6403                }
6404
6405                // If there is nothing selected, add all candidates and remove the ones that the user
6406                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6407                if (result.size() == 0) {
6408                    result.addAll(candidates);
6409                    result.removeAll(neverList);
6410                }
6411            }
6412        }
6413        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6414            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6415                    result.size());
6416            for (ResolveInfo info : result) {
6417                Slog.v(TAG, "  + " + info.activityInfo);
6418            }
6419        }
6420        return result;
6421    }
6422
6423    // Returns a packed value as a long:
6424    //
6425    // high 'int'-sized word: link status: undefined/ask/never/always.
6426    // low 'int'-sized word: relative priority among 'always' results.
6427    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6428        long result = ps.getDomainVerificationStatusForUser(userId);
6429        // if none available, get the master status
6430        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6431            if (ps.getIntentFilterVerificationInfo() != null) {
6432                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6433            }
6434        }
6435        return result;
6436    }
6437
6438    private ResolveInfo querySkipCurrentProfileIntents(
6439            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6440            int flags, int sourceUserId) {
6441        if (matchingFilters != null) {
6442            int size = matchingFilters.size();
6443            for (int i = 0; i < size; i ++) {
6444                CrossProfileIntentFilter filter = matchingFilters.get(i);
6445                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6446                    // Checking if there are activities in the target user that can handle the
6447                    // intent.
6448                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6449                            resolvedType, flags, sourceUserId);
6450                    if (resolveInfo != null) {
6451                        return resolveInfo;
6452                    }
6453                }
6454            }
6455        }
6456        return null;
6457    }
6458
6459    // Return matching ResolveInfo in target user if any.
6460    private ResolveInfo queryCrossProfileIntents(
6461            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6462            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6463        if (matchingFilters != null) {
6464            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6465            // match the same intent. For performance reasons, it is better not to
6466            // run queryIntent twice for the same userId
6467            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6468            int size = matchingFilters.size();
6469            for (int i = 0; i < size; i++) {
6470                CrossProfileIntentFilter filter = matchingFilters.get(i);
6471                int targetUserId = filter.getTargetUserId();
6472                boolean skipCurrentProfile =
6473                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6474                boolean skipCurrentProfileIfNoMatchFound =
6475                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6476                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6477                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6478                    // Checking if there are activities in the target user that can handle the
6479                    // intent.
6480                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6481                            resolvedType, flags, sourceUserId);
6482                    if (resolveInfo != null) return resolveInfo;
6483                    alreadyTriedUserIds.put(targetUserId, true);
6484                }
6485            }
6486        }
6487        return null;
6488    }
6489
6490    /**
6491     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6492     * will forward the intent to the filter's target user.
6493     * Otherwise, returns null.
6494     */
6495    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6496            String resolvedType, int flags, int sourceUserId) {
6497        int targetUserId = filter.getTargetUserId();
6498        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6499                resolvedType, flags, targetUserId);
6500        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6501            // If all the matches in the target profile are suspended, return null.
6502            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6503                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6504                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6505                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6506                            targetUserId);
6507                }
6508            }
6509        }
6510        return null;
6511    }
6512
6513    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6514            int sourceUserId, int targetUserId) {
6515        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6516        long ident = Binder.clearCallingIdentity();
6517        boolean targetIsProfile;
6518        try {
6519            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6520        } finally {
6521            Binder.restoreCallingIdentity(ident);
6522        }
6523        String className;
6524        if (targetIsProfile) {
6525            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6526        } else {
6527            className = FORWARD_INTENT_TO_PARENT;
6528        }
6529        ComponentName forwardingActivityComponentName = new ComponentName(
6530                mAndroidApplication.packageName, className);
6531        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6532                sourceUserId);
6533        if (!targetIsProfile) {
6534            forwardingActivityInfo.showUserIcon = targetUserId;
6535            forwardingResolveInfo.noResourceId = true;
6536        }
6537        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6538        forwardingResolveInfo.priority = 0;
6539        forwardingResolveInfo.preferredOrder = 0;
6540        forwardingResolveInfo.match = 0;
6541        forwardingResolveInfo.isDefault = true;
6542        forwardingResolveInfo.filter = filter;
6543        forwardingResolveInfo.targetUserId = targetUserId;
6544        return forwardingResolveInfo;
6545    }
6546
6547    @Override
6548    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6549            Intent[] specifics, String[] specificTypes, Intent intent,
6550            String resolvedType, int flags, int userId) {
6551        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6552                specificTypes, intent, resolvedType, flags, userId));
6553    }
6554
6555    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6556            Intent[] specifics, String[] specificTypes, Intent intent,
6557            String resolvedType, int flags, int userId) {
6558        if (!sUserManager.exists(userId)) return Collections.emptyList();
6559        flags = updateFlagsForResolve(flags, userId, intent);
6560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6561                false /* requireFullPermission */, false /* checkShell */,
6562                "query intent activity options");
6563        final String resultsAction = intent.getAction();
6564
6565        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6566                | PackageManager.GET_RESOLVED_FILTER, userId);
6567
6568        if (DEBUG_INTENT_MATCHING) {
6569            Log.v(TAG, "Query " + intent + ": " + results);
6570        }
6571
6572        int specificsPos = 0;
6573        int N;
6574
6575        // todo: note that the algorithm used here is O(N^2).  This
6576        // isn't a problem in our current environment, but if we start running
6577        // into situations where we have more than 5 or 10 matches then this
6578        // should probably be changed to something smarter...
6579
6580        // First we go through and resolve each of the specific items
6581        // that were supplied, taking care of removing any corresponding
6582        // duplicate items in the generic resolve list.
6583        if (specifics != null) {
6584            for (int i=0; i<specifics.length; i++) {
6585                final Intent sintent = specifics[i];
6586                if (sintent == null) {
6587                    continue;
6588                }
6589
6590                if (DEBUG_INTENT_MATCHING) {
6591                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6592                }
6593
6594                String action = sintent.getAction();
6595                if (resultsAction != null && resultsAction.equals(action)) {
6596                    // If this action was explicitly requested, then don't
6597                    // remove things that have it.
6598                    action = null;
6599                }
6600
6601                ResolveInfo ri = null;
6602                ActivityInfo ai = null;
6603
6604                ComponentName comp = sintent.getComponent();
6605                if (comp == null) {
6606                    ri = resolveIntent(
6607                        sintent,
6608                        specificTypes != null ? specificTypes[i] : null,
6609                            flags, userId);
6610                    if (ri == null) {
6611                        continue;
6612                    }
6613                    if (ri == mResolveInfo) {
6614                        // ACK!  Must do something better with this.
6615                    }
6616                    ai = ri.activityInfo;
6617                    comp = new ComponentName(ai.applicationInfo.packageName,
6618                            ai.name);
6619                } else {
6620                    ai = getActivityInfo(comp, flags, userId);
6621                    if (ai == null) {
6622                        continue;
6623                    }
6624                }
6625
6626                // Look for any generic query activities that are duplicates
6627                // of this specific one, and remove them from the results.
6628                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6629                N = results.size();
6630                int j;
6631                for (j=specificsPos; j<N; j++) {
6632                    ResolveInfo sri = results.get(j);
6633                    if ((sri.activityInfo.name.equals(comp.getClassName())
6634                            && sri.activityInfo.applicationInfo.packageName.equals(
6635                                    comp.getPackageName()))
6636                        || (action != null && sri.filter.matchAction(action))) {
6637                        results.remove(j);
6638                        if (DEBUG_INTENT_MATCHING) Log.v(
6639                            TAG, "Removing duplicate item from " + j
6640                            + " due to specific " + specificsPos);
6641                        if (ri == null) {
6642                            ri = sri;
6643                        }
6644                        j--;
6645                        N--;
6646                    }
6647                }
6648
6649                // Add this specific item to its proper place.
6650                if (ri == null) {
6651                    ri = new ResolveInfo();
6652                    ri.activityInfo = ai;
6653                }
6654                results.add(specificsPos, ri);
6655                ri.specificIndex = i;
6656                specificsPos++;
6657            }
6658        }
6659
6660        // Now we go through the remaining generic results and remove any
6661        // duplicate actions that are found here.
6662        N = results.size();
6663        for (int i=specificsPos; i<N-1; i++) {
6664            final ResolveInfo rii = results.get(i);
6665            if (rii.filter == null) {
6666                continue;
6667            }
6668
6669            // Iterate over all of the actions of this result's intent
6670            // filter...  typically this should be just one.
6671            final Iterator<String> it = rii.filter.actionsIterator();
6672            if (it == null) {
6673                continue;
6674            }
6675            while (it.hasNext()) {
6676                final String action = it.next();
6677                if (resultsAction != null && resultsAction.equals(action)) {
6678                    // If this action was explicitly requested, then don't
6679                    // remove things that have it.
6680                    continue;
6681                }
6682                for (int j=i+1; j<N; j++) {
6683                    final ResolveInfo rij = results.get(j);
6684                    if (rij.filter != null && rij.filter.hasAction(action)) {
6685                        results.remove(j);
6686                        if (DEBUG_INTENT_MATCHING) Log.v(
6687                            TAG, "Removing duplicate item from " + j
6688                            + " due to action " + action + " at " + i);
6689                        j--;
6690                        N--;
6691                    }
6692                }
6693            }
6694
6695            // If the caller didn't request filter information, drop it now
6696            // so we don't have to marshall/unmarshall it.
6697            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6698                rii.filter = null;
6699            }
6700        }
6701
6702        // Filter out the caller activity if so requested.
6703        if (caller != null) {
6704            N = results.size();
6705            for (int i=0; i<N; i++) {
6706                ActivityInfo ainfo = results.get(i).activityInfo;
6707                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6708                        && caller.getClassName().equals(ainfo.name)) {
6709                    results.remove(i);
6710                    break;
6711                }
6712            }
6713        }
6714
6715        // If the caller didn't request filter information,
6716        // drop them now so we don't have to
6717        // marshall/unmarshall it.
6718        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6719            N = results.size();
6720            for (int i=0; i<N; i++) {
6721                results.get(i).filter = null;
6722            }
6723        }
6724
6725        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6726        return results;
6727    }
6728
6729    @Override
6730    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6731            String resolvedType, int flags, int userId) {
6732        return new ParceledListSlice<>(
6733                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6734    }
6735
6736    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6737            String resolvedType, int flags, int userId) {
6738        if (!sUserManager.exists(userId)) return Collections.emptyList();
6739        flags = updateFlagsForResolve(flags, userId, intent);
6740        ComponentName comp = intent.getComponent();
6741        if (comp == null) {
6742            if (intent.getSelector() != null) {
6743                intent = intent.getSelector();
6744                comp = intent.getComponent();
6745            }
6746        }
6747        if (comp != null) {
6748            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6749            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6750            if (ai != null) {
6751                ResolveInfo ri = new ResolveInfo();
6752                ri.activityInfo = ai;
6753                list.add(ri);
6754            }
6755            return list;
6756        }
6757
6758        // reader
6759        synchronized (mPackages) {
6760            String pkgName = intent.getPackage();
6761            if (pkgName == null) {
6762                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6763            }
6764            final PackageParser.Package pkg = mPackages.get(pkgName);
6765            if (pkg != null) {
6766                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6767                        userId);
6768            }
6769            return Collections.emptyList();
6770        }
6771    }
6772
6773    @Override
6774    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6775        if (!sUserManager.exists(userId)) return null;
6776        flags = updateFlagsForResolve(flags, userId, intent);
6777        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6778        if (query != null) {
6779            if (query.size() >= 1) {
6780                // If there is more than one service with the same priority,
6781                // just arbitrarily pick the first one.
6782                return query.get(0);
6783            }
6784        }
6785        return null;
6786    }
6787
6788    @Override
6789    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6790            String resolvedType, int flags, int userId) {
6791        return new ParceledListSlice<>(
6792                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6793    }
6794
6795    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6796            String resolvedType, int flags, int userId) {
6797        if (!sUserManager.exists(userId)) return Collections.emptyList();
6798        flags = updateFlagsForResolve(flags, userId, intent);
6799        ComponentName comp = intent.getComponent();
6800        if (comp == null) {
6801            if (intent.getSelector() != null) {
6802                intent = intent.getSelector();
6803                comp = intent.getComponent();
6804            }
6805        }
6806        if (comp != null) {
6807            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6808            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6809            if (si != null) {
6810                final ResolveInfo ri = new ResolveInfo();
6811                ri.serviceInfo = si;
6812                list.add(ri);
6813            }
6814            return list;
6815        }
6816
6817        // reader
6818        synchronized (mPackages) {
6819            String pkgName = intent.getPackage();
6820            if (pkgName == null) {
6821                return mServices.queryIntent(intent, resolvedType, flags, userId);
6822            }
6823            final PackageParser.Package pkg = mPackages.get(pkgName);
6824            if (pkg != null) {
6825                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6826                        userId);
6827            }
6828            return Collections.emptyList();
6829        }
6830    }
6831
6832    @Override
6833    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6834            String resolvedType, int flags, int userId) {
6835        return new ParceledListSlice<>(
6836                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6837    }
6838
6839    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6840            Intent intent, String resolvedType, int flags, int userId) {
6841        if (!sUserManager.exists(userId)) return Collections.emptyList();
6842        flags = updateFlagsForResolve(flags, userId, intent);
6843        ComponentName comp = intent.getComponent();
6844        if (comp == null) {
6845            if (intent.getSelector() != null) {
6846                intent = intent.getSelector();
6847                comp = intent.getComponent();
6848            }
6849        }
6850        if (comp != null) {
6851            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6852            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6853            if (pi != null) {
6854                final ResolveInfo ri = new ResolveInfo();
6855                ri.providerInfo = pi;
6856                list.add(ri);
6857            }
6858            return list;
6859        }
6860
6861        // reader
6862        synchronized (mPackages) {
6863            String pkgName = intent.getPackage();
6864            if (pkgName == null) {
6865                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6866            }
6867            final PackageParser.Package pkg = mPackages.get(pkgName);
6868            if (pkg != null) {
6869                return mProviders.queryIntentForPackage(
6870                        intent, resolvedType, flags, pkg.providers, userId);
6871            }
6872            return Collections.emptyList();
6873        }
6874    }
6875
6876    @Override
6877    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6878        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6879        flags = updateFlagsForPackage(flags, userId, null);
6880        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6882                true /* requireFullPermission */, false /* checkShell */,
6883                "get installed packages");
6884
6885        // writer
6886        synchronized (mPackages) {
6887            ArrayList<PackageInfo> list;
6888            if (listUninstalled) {
6889                list = new ArrayList<>(mSettings.mPackages.size());
6890                for (PackageSetting ps : mSettings.mPackages.values()) {
6891                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6892                        continue;
6893                    }
6894                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6895                    if (pi != null) {
6896                        list.add(pi);
6897                    }
6898                }
6899            } else {
6900                list = new ArrayList<>(mPackages.size());
6901                for (PackageParser.Package p : mPackages.values()) {
6902                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6903                            Binder.getCallingUid(), userId)) {
6904                        continue;
6905                    }
6906                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6907                            p.mExtras, flags, userId);
6908                    if (pi != null) {
6909                        list.add(pi);
6910                    }
6911                }
6912            }
6913
6914            return new ParceledListSlice<>(list);
6915        }
6916    }
6917
6918    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6919            String[] permissions, boolean[] tmp, int flags, int userId) {
6920        int numMatch = 0;
6921        final PermissionsState permissionsState = ps.getPermissionsState();
6922        for (int i=0; i<permissions.length; i++) {
6923            final String permission = permissions[i];
6924            if (permissionsState.hasPermission(permission, userId)) {
6925                tmp[i] = true;
6926                numMatch++;
6927            } else {
6928                tmp[i] = false;
6929            }
6930        }
6931        if (numMatch == 0) {
6932            return;
6933        }
6934        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6935
6936        // The above might return null in cases of uninstalled apps or install-state
6937        // skew across users/profiles.
6938        if (pi != null) {
6939            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6940                if (numMatch == permissions.length) {
6941                    pi.requestedPermissions = permissions;
6942                } else {
6943                    pi.requestedPermissions = new String[numMatch];
6944                    numMatch = 0;
6945                    for (int i=0; i<permissions.length; i++) {
6946                        if (tmp[i]) {
6947                            pi.requestedPermissions[numMatch] = permissions[i];
6948                            numMatch++;
6949                        }
6950                    }
6951                }
6952            }
6953            list.add(pi);
6954        }
6955    }
6956
6957    @Override
6958    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6959            String[] permissions, int flags, int userId) {
6960        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6961        flags = updateFlagsForPackage(flags, userId, permissions);
6962        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6963                true /* requireFullPermission */, false /* checkShell */,
6964                "get packages holding permissions");
6965        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6966
6967        // writer
6968        synchronized (mPackages) {
6969            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6970            boolean[] tmpBools = new boolean[permissions.length];
6971            if (listUninstalled) {
6972                for (PackageSetting ps : mSettings.mPackages.values()) {
6973                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6974                            userId);
6975                }
6976            } else {
6977                for (PackageParser.Package pkg : mPackages.values()) {
6978                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6979                    if (ps != null) {
6980                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6981                                userId);
6982                    }
6983                }
6984            }
6985
6986            return new ParceledListSlice<PackageInfo>(list);
6987        }
6988    }
6989
6990    @Override
6991    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6992        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6993        flags = updateFlagsForApplication(flags, userId, null);
6994        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6995
6996        // writer
6997        synchronized (mPackages) {
6998            ArrayList<ApplicationInfo> list;
6999            if (listUninstalled) {
7000                list = new ArrayList<>(mSettings.mPackages.size());
7001                for (PackageSetting ps : mSettings.mPackages.values()) {
7002                    ApplicationInfo ai;
7003                    int effectiveFlags = flags;
7004                    if (ps.isSystem()) {
7005                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7006                    }
7007                    if (ps.pkg != null) {
7008                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7009                            continue;
7010                        }
7011                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7012                                ps.readUserState(userId), userId);
7013                        if (ai != null) {
7014                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7015                        }
7016                    } else {
7017                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7018                        // and already converts to externally visible package name
7019                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7020                                Binder.getCallingUid(), effectiveFlags, userId);
7021                    }
7022                    if (ai != null) {
7023                        list.add(ai);
7024                    }
7025                }
7026            } else {
7027                list = new ArrayList<>(mPackages.size());
7028                for (PackageParser.Package p : mPackages.values()) {
7029                    if (p.mExtras != null) {
7030                        PackageSetting ps = (PackageSetting) p.mExtras;
7031                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7032                            continue;
7033                        }
7034                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7035                                ps.readUserState(userId), userId);
7036                        if (ai != null) {
7037                            ai.packageName = resolveExternalPackageNameLPr(p);
7038                            list.add(ai);
7039                        }
7040                    }
7041                }
7042            }
7043
7044            return new ParceledListSlice<>(list);
7045        }
7046    }
7047
7048    @Override
7049    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7050        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7051            return null;
7052        }
7053
7054        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7055                "getEphemeralApplications");
7056        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7057                true /* requireFullPermission */, false /* checkShell */,
7058                "getEphemeralApplications");
7059        synchronized (mPackages) {
7060            List<InstantAppInfo> instantApps = mInstantAppRegistry
7061                    .getInstantAppsLPr(userId);
7062            if (instantApps != null) {
7063                return new ParceledListSlice<>(instantApps);
7064            }
7065        }
7066        return null;
7067    }
7068
7069    @Override
7070    public boolean isInstantApp(String packageName, int userId) {
7071        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7072                true /* requireFullPermission */, false /* checkShell */,
7073                "isInstantApp");
7074        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7075            return false;
7076        }
7077
7078        if (!isCallerSameApp(packageName)) {
7079            return false;
7080        }
7081        synchronized (mPackages) {
7082            PackageParser.Package pkg = mPackages.get(packageName);
7083            if (pkg != null) {
7084                return pkg.applicationInfo.isInstantApp();
7085            }
7086        }
7087        return false;
7088    }
7089
7090    @Override
7091    public byte[] getInstantAppCookie(String packageName, int userId) {
7092        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7093            return null;
7094        }
7095
7096        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7097                true /* requireFullPermission */, false /* checkShell */,
7098                "getInstantAppCookie");
7099        if (!isCallerSameApp(packageName)) {
7100            return null;
7101        }
7102        synchronized (mPackages) {
7103            return mInstantAppRegistry.getInstantAppCookieLPw(
7104                    packageName, userId);
7105        }
7106    }
7107
7108    @Override
7109    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7110        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7111            return true;
7112        }
7113
7114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7115                true /* requireFullPermission */, true /* checkShell */,
7116                "setInstantAppCookie");
7117        if (!isCallerSameApp(packageName)) {
7118            return false;
7119        }
7120        synchronized (mPackages) {
7121            return mInstantAppRegistry.setInstantAppCookieLPw(
7122                    packageName, cookie, userId);
7123        }
7124    }
7125
7126    @Override
7127    public Bitmap getInstantAppIcon(String packageName, int userId) {
7128        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7129            return null;
7130        }
7131
7132        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7133                "getInstantAppIcon");
7134
7135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7136                true /* requireFullPermission */, false /* checkShell */,
7137                "getInstantAppIcon");
7138
7139        synchronized (mPackages) {
7140            return mInstantAppRegistry.getInstantAppIconLPw(
7141                    packageName, userId);
7142        }
7143    }
7144
7145    private boolean isCallerSameApp(String packageName) {
7146        PackageParser.Package pkg = mPackages.get(packageName);
7147        return pkg != null
7148                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7149    }
7150
7151    @Override
7152    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7153        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7154    }
7155
7156    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7157        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7158
7159        // reader
7160        synchronized (mPackages) {
7161            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7162            final int userId = UserHandle.getCallingUserId();
7163            while (i.hasNext()) {
7164                final PackageParser.Package p = i.next();
7165                if (p.applicationInfo == null) continue;
7166
7167                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7168                        && !p.applicationInfo.isDirectBootAware();
7169                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7170                        && p.applicationInfo.isDirectBootAware();
7171
7172                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7173                        && (!mSafeMode || isSystemApp(p))
7174                        && (matchesUnaware || matchesAware)) {
7175                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7176                    if (ps != null) {
7177                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7178                                ps.readUserState(userId), userId);
7179                        if (ai != null) {
7180                            finalList.add(ai);
7181                        }
7182                    }
7183                }
7184            }
7185        }
7186
7187        return finalList;
7188    }
7189
7190    @Override
7191    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7192        if (!sUserManager.exists(userId)) return null;
7193        flags = updateFlagsForComponent(flags, userId, name);
7194        // reader
7195        synchronized (mPackages) {
7196            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7197            PackageSetting ps = provider != null
7198                    ? mSettings.mPackages.get(provider.owner.packageName)
7199                    : null;
7200            return ps != null
7201                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7202                    ? PackageParser.generateProviderInfo(provider, flags,
7203                            ps.readUserState(userId), userId)
7204                    : null;
7205        }
7206    }
7207
7208    /**
7209     * @deprecated
7210     */
7211    @Deprecated
7212    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7213        // reader
7214        synchronized (mPackages) {
7215            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7216                    .entrySet().iterator();
7217            final int userId = UserHandle.getCallingUserId();
7218            while (i.hasNext()) {
7219                Map.Entry<String, PackageParser.Provider> entry = i.next();
7220                PackageParser.Provider p = entry.getValue();
7221                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7222
7223                if (ps != null && p.syncable
7224                        && (!mSafeMode || (p.info.applicationInfo.flags
7225                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7226                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7227                            ps.readUserState(userId), userId);
7228                    if (info != null) {
7229                        outNames.add(entry.getKey());
7230                        outInfo.add(info);
7231                    }
7232                }
7233            }
7234        }
7235    }
7236
7237    @Override
7238    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7239            int uid, int flags) {
7240        final int userId = processName != null ? UserHandle.getUserId(uid)
7241                : UserHandle.getCallingUserId();
7242        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7243        flags = updateFlagsForComponent(flags, userId, processName);
7244
7245        ArrayList<ProviderInfo> finalList = null;
7246        // reader
7247        synchronized (mPackages) {
7248            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7249            while (i.hasNext()) {
7250                final PackageParser.Provider p = i.next();
7251                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7252                if (ps != null && p.info.authority != null
7253                        && (processName == null
7254                                || (p.info.processName.equals(processName)
7255                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7256                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7257                    if (finalList == null) {
7258                        finalList = new ArrayList<ProviderInfo>(3);
7259                    }
7260                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7261                            ps.readUserState(userId), userId);
7262                    if (info != null) {
7263                        finalList.add(info);
7264                    }
7265                }
7266            }
7267        }
7268
7269        if (finalList != null) {
7270            Collections.sort(finalList, mProviderInitOrderSorter);
7271            return new ParceledListSlice<ProviderInfo>(finalList);
7272        }
7273
7274        return ParceledListSlice.emptyList();
7275    }
7276
7277    @Override
7278    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7279        // reader
7280        synchronized (mPackages) {
7281            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7282            return PackageParser.generateInstrumentationInfo(i, flags);
7283        }
7284    }
7285
7286    @Override
7287    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7288            String targetPackage, int flags) {
7289        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7290    }
7291
7292    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7293            int flags) {
7294        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7295
7296        // reader
7297        synchronized (mPackages) {
7298            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7299            while (i.hasNext()) {
7300                final PackageParser.Instrumentation p = i.next();
7301                if (targetPackage == null
7302                        || targetPackage.equals(p.info.targetPackage)) {
7303                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7304                            flags);
7305                    if (ii != null) {
7306                        finalList.add(ii);
7307                    }
7308                }
7309            }
7310        }
7311
7312        return finalList;
7313    }
7314
7315    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7316        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7317        if (overlays == null) {
7318            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7319            return;
7320        }
7321        for (PackageParser.Package opkg : overlays.values()) {
7322            // Not much to do if idmap fails: we already logged the error
7323            // and we certainly don't want to abort installation of pkg simply
7324            // because an overlay didn't fit properly. For these reasons,
7325            // ignore the return value of createIdmapForPackagePairLI.
7326            createIdmapForPackagePairLI(pkg, opkg);
7327        }
7328    }
7329
7330    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7331            PackageParser.Package opkg) {
7332        if (!opkg.mTrustedOverlay) {
7333            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7334                    opkg.baseCodePath + ": overlay not trusted");
7335            return false;
7336        }
7337        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7338        if (overlaySet == null) {
7339            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7340                    opkg.baseCodePath + " but target package has no known overlays");
7341            return false;
7342        }
7343        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7344        // TODO: generate idmap for split APKs
7345        try {
7346            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7347        } catch (InstallerException e) {
7348            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7349                    + opkg.baseCodePath);
7350            return false;
7351        }
7352        PackageParser.Package[] overlayArray =
7353            overlaySet.values().toArray(new PackageParser.Package[0]);
7354        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7355            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7356                return p1.mOverlayPriority - p2.mOverlayPriority;
7357            }
7358        };
7359        Arrays.sort(overlayArray, cmp);
7360
7361        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7362        int i = 0;
7363        for (PackageParser.Package p : overlayArray) {
7364            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7365        }
7366        return true;
7367    }
7368
7369    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7370        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7371        try {
7372            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7373        } finally {
7374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7375        }
7376    }
7377
7378    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7379        final File[] files = dir.listFiles();
7380        if (ArrayUtils.isEmpty(files)) {
7381            Log.d(TAG, "No files in app dir " + dir);
7382            return;
7383        }
7384
7385        if (DEBUG_PACKAGE_SCANNING) {
7386            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7387                    + " flags=0x" + Integer.toHexString(parseFlags));
7388        }
7389        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7390                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7391
7392        // Submit files for parsing in parallel
7393        int fileCount = 0;
7394        for (File file : files) {
7395            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7396                    && !PackageInstallerService.isStageName(file.getName());
7397            if (!isPackage) {
7398                // Ignore entries which are not packages
7399                continue;
7400            }
7401            parallelPackageParser.submit(file, parseFlags);
7402            fileCount++;
7403        }
7404
7405        // Process results one by one
7406        for (; fileCount > 0; fileCount--) {
7407            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7408            Throwable throwable = parseResult.throwable;
7409            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7410
7411            if (throwable == null) {
7412                // Static shared libraries have synthetic package names
7413                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7414                    renameStaticSharedLibraryPackage(parseResult.pkg);
7415                }
7416                try {
7417                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7418                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7419                                currentTime, null);
7420                    }
7421                } catch (PackageManagerException e) {
7422                    errorCode = e.error;
7423                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7424                }
7425            } else if (throwable instanceof PackageParser.PackageParserException) {
7426                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7427                        throwable;
7428                errorCode = e.error;
7429                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7430            } else {
7431                throw new IllegalStateException("Unexpected exception occurred while parsing "
7432                        + parseResult.scanFile, throwable);
7433            }
7434
7435            // Delete invalid userdata apps
7436            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7437                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7438                logCriticalInfo(Log.WARN,
7439                        "Deleting invalid package at " + parseResult.scanFile);
7440                removeCodePathLI(parseResult.scanFile);
7441            }
7442        }
7443        parallelPackageParser.close();
7444    }
7445
7446    private static File getSettingsProblemFile() {
7447        File dataDir = Environment.getDataDirectory();
7448        File systemDir = new File(dataDir, "system");
7449        File fname = new File(systemDir, "uiderrors.txt");
7450        return fname;
7451    }
7452
7453    static void reportSettingsProblem(int priority, String msg) {
7454        logCriticalInfo(priority, msg);
7455    }
7456
7457    static void logCriticalInfo(int priority, String msg) {
7458        Slog.println(priority, TAG, msg);
7459        EventLogTags.writePmCriticalInfo(msg);
7460        try {
7461            File fname = getSettingsProblemFile();
7462            FileOutputStream out = new FileOutputStream(fname, true);
7463            PrintWriter pw = new FastPrintWriter(out);
7464            SimpleDateFormat formatter = new SimpleDateFormat();
7465            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7466            pw.println(dateString + ": " + msg);
7467            pw.close();
7468            FileUtils.setPermissions(
7469                    fname.toString(),
7470                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7471                    -1, -1);
7472        } catch (java.io.IOException e) {
7473        }
7474    }
7475
7476    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7477        if (srcFile.isDirectory()) {
7478            final File baseFile = new File(pkg.baseCodePath);
7479            long maxModifiedTime = baseFile.lastModified();
7480            if (pkg.splitCodePaths != null) {
7481                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7482                    final File splitFile = new File(pkg.splitCodePaths[i]);
7483                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7484                }
7485            }
7486            return maxModifiedTime;
7487        }
7488        return srcFile.lastModified();
7489    }
7490
7491    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7492            final int policyFlags) throws PackageManagerException {
7493        // When upgrading from pre-N MR1, verify the package time stamp using the package
7494        // directory and not the APK file.
7495        final long lastModifiedTime = mIsPreNMR1Upgrade
7496                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7497        if (ps != null
7498                && ps.codePath.equals(srcFile)
7499                && ps.timeStamp == lastModifiedTime
7500                && !isCompatSignatureUpdateNeeded(pkg)
7501                && !isRecoverSignatureUpdateNeeded(pkg)) {
7502            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7503            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7504            ArraySet<PublicKey> signingKs;
7505            synchronized (mPackages) {
7506                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7507            }
7508            if (ps.signatures.mSignatures != null
7509                    && ps.signatures.mSignatures.length != 0
7510                    && signingKs != null) {
7511                // Optimization: reuse the existing cached certificates
7512                // if the package appears to be unchanged.
7513                pkg.mSignatures = ps.signatures.mSignatures;
7514                pkg.mSigningKeys = signingKs;
7515                return;
7516            }
7517
7518            Slog.w(TAG, "PackageSetting for " + ps.name
7519                    + " is missing signatures.  Collecting certs again to recover them.");
7520        } else {
7521            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7522        }
7523
7524        try {
7525            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7526            PackageParser.collectCertificates(pkg, policyFlags);
7527        } catch (PackageParserException e) {
7528            throw PackageManagerException.from(e);
7529        } finally {
7530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7531        }
7532    }
7533
7534    /**
7535     *  Traces a package scan.
7536     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7537     */
7538    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7539            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7540        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7541        try {
7542            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7543        } finally {
7544            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7545        }
7546    }
7547
7548    /**
7549     *  Scans a package and returns the newly parsed package.
7550     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7551     */
7552    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7553            long currentTime, UserHandle user) throws PackageManagerException {
7554        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7555        PackageParser pp = new PackageParser();
7556        pp.setSeparateProcesses(mSeparateProcesses);
7557        pp.setOnlyCoreApps(mOnlyCore);
7558        pp.setDisplayMetrics(mMetrics);
7559
7560        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7561            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7562        }
7563
7564        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7565        final PackageParser.Package pkg;
7566        try {
7567            pkg = pp.parsePackage(scanFile, parseFlags);
7568        } catch (PackageParserException e) {
7569            throw PackageManagerException.from(e);
7570        } finally {
7571            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7572        }
7573
7574        // Static shared libraries have synthetic package names
7575        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7576            renameStaticSharedLibraryPackage(pkg);
7577        }
7578
7579        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7580    }
7581
7582    /**
7583     *  Scans a package and returns the newly parsed package.
7584     *  @throws PackageManagerException on a parse error.
7585     */
7586    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7587            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7588            throws PackageManagerException {
7589        // If the package has children and this is the first dive in the function
7590        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7591        // packages (parent and children) would be successfully scanned before the
7592        // actual scan since scanning mutates internal state and we want to atomically
7593        // install the package and its children.
7594        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7595            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7596                scanFlags |= SCAN_CHECK_ONLY;
7597            }
7598        } else {
7599            scanFlags &= ~SCAN_CHECK_ONLY;
7600        }
7601
7602        // Scan the parent
7603        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7604                scanFlags, currentTime, user);
7605
7606        // Scan the children
7607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7608        for (int i = 0; i < childCount; i++) {
7609            PackageParser.Package childPackage = pkg.childPackages.get(i);
7610            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7611                    currentTime, user);
7612        }
7613
7614
7615        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7616            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7617        }
7618
7619        return scannedPkg;
7620    }
7621
7622    /**
7623     *  Scans a package and returns the newly parsed package.
7624     *  @throws PackageManagerException on a parse error.
7625     */
7626    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7627            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7628            throws PackageManagerException {
7629        PackageSetting ps = null;
7630        PackageSetting updatedPkg;
7631        // reader
7632        synchronized (mPackages) {
7633            // Look to see if we already know about this package.
7634            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7635            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7636                // This package has been renamed to its original name.  Let's
7637                // use that.
7638                ps = mSettings.getPackageLPr(oldName);
7639            }
7640            // If there was no original package, see one for the real package name.
7641            if (ps == null) {
7642                ps = mSettings.getPackageLPr(pkg.packageName);
7643            }
7644            // Check to see if this package could be hiding/updating a system
7645            // package.  Must look for it either under the original or real
7646            // package name depending on our state.
7647            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7648            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7649
7650            // If this is a package we don't know about on the system partition, we
7651            // may need to remove disabled child packages on the system partition
7652            // or may need to not add child packages if the parent apk is updated
7653            // on the data partition and no longer defines this child package.
7654            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7655                // If this is a parent package for an updated system app and this system
7656                // app got an OTA update which no longer defines some of the child packages
7657                // we have to prune them from the disabled system packages.
7658                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7659                if (disabledPs != null) {
7660                    final int scannedChildCount = (pkg.childPackages != null)
7661                            ? pkg.childPackages.size() : 0;
7662                    final int disabledChildCount = disabledPs.childPackageNames != null
7663                            ? disabledPs.childPackageNames.size() : 0;
7664                    for (int i = 0; i < disabledChildCount; i++) {
7665                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7666                        boolean disabledPackageAvailable = false;
7667                        for (int j = 0; j < scannedChildCount; j++) {
7668                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7669                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7670                                disabledPackageAvailable = true;
7671                                break;
7672                            }
7673                         }
7674                         if (!disabledPackageAvailable) {
7675                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7676                         }
7677                    }
7678                }
7679            }
7680        }
7681
7682        boolean updatedPkgBetter = false;
7683        // First check if this is a system package that may involve an update
7684        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7685            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7686            // it needs to drop FLAG_PRIVILEGED.
7687            if (locationIsPrivileged(scanFile)) {
7688                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7689            } else {
7690                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7691            }
7692
7693            if (ps != null && !ps.codePath.equals(scanFile)) {
7694                // The path has changed from what was last scanned...  check the
7695                // version of the new path against what we have stored to determine
7696                // what to do.
7697                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7698                if (pkg.mVersionCode <= ps.versionCode) {
7699                    // The system package has been updated and the code path does not match
7700                    // Ignore entry. Skip it.
7701                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7702                            + " ignored: updated version " + ps.versionCode
7703                            + " better than this " + pkg.mVersionCode);
7704                    if (!updatedPkg.codePath.equals(scanFile)) {
7705                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7706                                + ps.name + " changing from " + updatedPkg.codePathString
7707                                + " to " + scanFile);
7708                        updatedPkg.codePath = scanFile;
7709                        updatedPkg.codePathString = scanFile.toString();
7710                        updatedPkg.resourcePath = scanFile;
7711                        updatedPkg.resourcePathString = scanFile.toString();
7712                    }
7713                    updatedPkg.pkg = pkg;
7714                    updatedPkg.versionCode = pkg.mVersionCode;
7715
7716                    // Update the disabled system child packages to point to the package too.
7717                    final int childCount = updatedPkg.childPackageNames != null
7718                            ? updatedPkg.childPackageNames.size() : 0;
7719                    for (int i = 0; i < childCount; i++) {
7720                        String childPackageName = updatedPkg.childPackageNames.get(i);
7721                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7722                                childPackageName);
7723                        if (updatedChildPkg != null) {
7724                            updatedChildPkg.pkg = pkg;
7725                            updatedChildPkg.versionCode = pkg.mVersionCode;
7726                        }
7727                    }
7728
7729                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7730                            + scanFile + " ignored: updated version " + ps.versionCode
7731                            + " better than this " + pkg.mVersionCode);
7732                } else {
7733                    // The current app on the system partition is better than
7734                    // what we have updated to on the data partition; switch
7735                    // back to the system partition version.
7736                    // At this point, its safely assumed that package installation for
7737                    // apps in system partition will go through. If not there won't be a working
7738                    // version of the app
7739                    // writer
7740                    synchronized (mPackages) {
7741                        // Just remove the loaded entries from package lists.
7742                        mPackages.remove(ps.name);
7743                    }
7744
7745                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7746                            + " reverting from " + ps.codePathString
7747                            + ": new version " + pkg.mVersionCode
7748                            + " better than installed " + ps.versionCode);
7749
7750                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7751                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7752                    synchronized (mInstallLock) {
7753                        args.cleanUpResourcesLI();
7754                    }
7755                    synchronized (mPackages) {
7756                        mSettings.enableSystemPackageLPw(ps.name);
7757                    }
7758                    updatedPkgBetter = true;
7759                }
7760            }
7761        }
7762
7763        if (updatedPkg != null) {
7764            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7765            // initially
7766            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7767
7768            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7769            // flag set initially
7770            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7771                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7772            }
7773        }
7774
7775        // Verify certificates against what was last scanned
7776        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7777
7778        /*
7779         * A new system app appeared, but we already had a non-system one of the
7780         * same name installed earlier.
7781         */
7782        boolean shouldHideSystemApp = false;
7783        if (updatedPkg == null && ps != null
7784                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7785            /*
7786             * Check to make sure the signatures match first. If they don't,
7787             * wipe the installed application and its data.
7788             */
7789            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7790                    != PackageManager.SIGNATURE_MATCH) {
7791                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7792                        + " signatures don't match existing userdata copy; removing");
7793                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7794                        "scanPackageInternalLI")) {
7795                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7796                }
7797                ps = null;
7798            } else {
7799                /*
7800                 * If the newly-added system app is an older version than the
7801                 * already installed version, hide it. It will be scanned later
7802                 * and re-added like an update.
7803                 */
7804                if (pkg.mVersionCode <= ps.versionCode) {
7805                    shouldHideSystemApp = true;
7806                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7807                            + " but new version " + pkg.mVersionCode + " better than installed "
7808                            + ps.versionCode + "; hiding system");
7809                } else {
7810                    /*
7811                     * The newly found system app is a newer version that the
7812                     * one previously installed. Simply remove the
7813                     * already-installed application and replace it with our own
7814                     * while keeping the application data.
7815                     */
7816                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7817                            + " reverting from " + ps.codePathString + ": new version "
7818                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7819                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7820                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7821                    synchronized (mInstallLock) {
7822                        args.cleanUpResourcesLI();
7823                    }
7824                }
7825            }
7826        }
7827
7828        // The apk is forward locked (not public) if its code and resources
7829        // are kept in different files. (except for app in either system or
7830        // vendor path).
7831        // TODO grab this value from PackageSettings
7832        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7833            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7834                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7835            }
7836        }
7837
7838        // TODO: extend to support forward-locked splits
7839        String resourcePath = null;
7840        String baseResourcePath = null;
7841        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7842            if (ps != null && ps.resourcePathString != null) {
7843                resourcePath = ps.resourcePathString;
7844                baseResourcePath = ps.resourcePathString;
7845            } else {
7846                // Should not happen at all. Just log an error.
7847                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7848            }
7849        } else {
7850            resourcePath = pkg.codePath;
7851            baseResourcePath = pkg.baseCodePath;
7852        }
7853
7854        // Set application objects path explicitly.
7855        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7856        pkg.setApplicationInfoCodePath(pkg.codePath);
7857        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7858        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7859        pkg.setApplicationInfoResourcePath(resourcePath);
7860        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7861        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7862
7863        // Note that we invoke the following method only if we are about to unpack an application
7864        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7865                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7866
7867        /*
7868         * If the system app should be overridden by a previously installed
7869         * data, hide the system app now and let the /data/app scan pick it up
7870         * again.
7871         */
7872        if (shouldHideSystemApp) {
7873            synchronized (mPackages) {
7874                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7875            }
7876        }
7877
7878        return scannedPkg;
7879    }
7880
7881    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7882        // Derive the new package synthetic package name
7883        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7884                + pkg.staticSharedLibVersion);
7885    }
7886
7887    private static String fixProcessName(String defProcessName,
7888            String processName) {
7889        if (processName == null) {
7890            return defProcessName;
7891        }
7892        return processName;
7893    }
7894
7895    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7896            throws PackageManagerException {
7897        if (pkgSetting.signatures.mSignatures != null) {
7898            // Already existing package. Make sure signatures match
7899            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7900                    == PackageManager.SIGNATURE_MATCH;
7901            if (!match) {
7902                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7903                        == PackageManager.SIGNATURE_MATCH;
7904            }
7905            if (!match) {
7906                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7907                        == PackageManager.SIGNATURE_MATCH;
7908            }
7909            if (!match) {
7910                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7911                        + pkg.packageName + " signatures do not match the "
7912                        + "previously installed version; ignoring!");
7913            }
7914        }
7915
7916        // Check for shared user signatures
7917        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7918            // Already existing package. Make sure signatures match
7919            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7920                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7921            if (!match) {
7922                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7923                        == PackageManager.SIGNATURE_MATCH;
7924            }
7925            if (!match) {
7926                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7927                        == PackageManager.SIGNATURE_MATCH;
7928            }
7929            if (!match) {
7930                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7931                        "Package " + pkg.packageName
7932                        + " has no signatures that match those in shared user "
7933                        + pkgSetting.sharedUser.name + "; ignoring!");
7934            }
7935        }
7936    }
7937
7938    /**
7939     * Enforces that only the system UID or root's UID can call a method exposed
7940     * via Binder.
7941     *
7942     * @param message used as message if SecurityException is thrown
7943     * @throws SecurityException if the caller is not system or root
7944     */
7945    private static final void enforceSystemOrRoot(String message) {
7946        final int uid = Binder.getCallingUid();
7947        if (uid != Process.SYSTEM_UID && uid != 0) {
7948            throw new SecurityException(message);
7949        }
7950    }
7951
7952    @Override
7953    public void performFstrimIfNeeded() {
7954        enforceSystemOrRoot("Only the system can request fstrim");
7955
7956        // Before everything else, see whether we need to fstrim.
7957        try {
7958            IStorageManager sm = PackageHelper.getStorageManager();
7959            if (sm != null) {
7960                boolean doTrim = false;
7961                final long interval = android.provider.Settings.Global.getLong(
7962                        mContext.getContentResolver(),
7963                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7964                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7965                if (interval > 0) {
7966                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7967                    if (timeSinceLast > interval) {
7968                        doTrim = true;
7969                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7970                                + "; running immediately");
7971                    }
7972                }
7973                if (doTrim) {
7974                    final boolean dexOptDialogShown;
7975                    synchronized (mPackages) {
7976                        dexOptDialogShown = mDexOptDialogShown;
7977                    }
7978                    if (!isFirstBoot() && dexOptDialogShown) {
7979                        try {
7980                            ActivityManager.getService().showBootMessage(
7981                                    mContext.getResources().getString(
7982                                            R.string.android_upgrading_fstrim), true);
7983                        } catch (RemoteException e) {
7984                        }
7985                    }
7986                    sm.runMaintenance();
7987                }
7988            } else {
7989                Slog.e(TAG, "storageManager service unavailable!");
7990            }
7991        } catch (RemoteException e) {
7992            // Can't happen; StorageManagerService is local
7993        }
7994    }
7995
7996    @Override
7997    public void updatePackagesIfNeeded() {
7998        enforceSystemOrRoot("Only the system can request package update");
7999
8000        // We need to re-extract after an OTA.
8001        boolean causeUpgrade = isUpgrade();
8002
8003        // First boot or factory reset.
8004        // Note: we also handle devices that are upgrading to N right now as if it is their
8005        //       first boot, as they do not have profile data.
8006        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8007
8008        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8009        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8010
8011        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8012            return;
8013        }
8014
8015        List<PackageParser.Package> pkgs;
8016        synchronized (mPackages) {
8017            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8018        }
8019
8020        final long startTime = System.nanoTime();
8021        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8022                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8023
8024        final int elapsedTimeSeconds =
8025                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8026
8027        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8028        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8029        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8030        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8031        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8032    }
8033
8034    /**
8035     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8036     * containing statistics about the invocation. The array consists of three elements,
8037     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8038     * and {@code numberOfPackagesFailed}.
8039     */
8040    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8041            String compilerFilter) {
8042
8043        int numberOfPackagesVisited = 0;
8044        int numberOfPackagesOptimized = 0;
8045        int numberOfPackagesSkipped = 0;
8046        int numberOfPackagesFailed = 0;
8047        final int numberOfPackagesToDexopt = pkgs.size();
8048
8049        for (PackageParser.Package pkg : pkgs) {
8050            numberOfPackagesVisited++;
8051
8052            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8053                if (DEBUG_DEXOPT) {
8054                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8055                }
8056                numberOfPackagesSkipped++;
8057                continue;
8058            }
8059
8060            if (DEBUG_DEXOPT) {
8061                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8062                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8063            }
8064
8065            if (showDialog) {
8066                try {
8067                    ActivityManager.getService().showBootMessage(
8068                            mContext.getResources().getString(R.string.android_upgrading_apk,
8069                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8070                } catch (RemoteException e) {
8071                }
8072                synchronized (mPackages) {
8073                    mDexOptDialogShown = true;
8074                }
8075            }
8076
8077            // If the OTA updates a system app which was previously preopted to a non-preopted state
8078            // the app might end up being verified at runtime. That's because by default the apps
8079            // are verify-profile but for preopted apps there's no profile.
8080            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8081            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8082            // filter (by default interpret-only).
8083            // Note that at this stage unused apps are already filtered.
8084            if (isSystemApp(pkg) &&
8085                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8086                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8087                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8088            }
8089
8090            // checkProfiles is false to avoid merging profiles during boot which
8091            // might interfere with background compilation (b/28612421).
8092            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8093            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8094            // trade-off worth doing to save boot time work.
8095            int dexOptStatus = performDexOptTraced(pkg.packageName,
8096                    false /* checkProfiles */,
8097                    compilerFilter,
8098                    false /* force */);
8099            switch (dexOptStatus) {
8100                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8101                    numberOfPackagesOptimized++;
8102                    break;
8103                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8104                    numberOfPackagesSkipped++;
8105                    break;
8106                case PackageDexOptimizer.DEX_OPT_FAILED:
8107                    numberOfPackagesFailed++;
8108                    break;
8109                default:
8110                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8111                    break;
8112            }
8113        }
8114
8115        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8116                numberOfPackagesFailed };
8117    }
8118
8119    @Override
8120    public void notifyPackageUse(String packageName, int reason) {
8121        synchronized (mPackages) {
8122            PackageParser.Package p = mPackages.get(packageName);
8123            if (p == null) {
8124                return;
8125            }
8126            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8127        }
8128    }
8129
8130    @Override
8131    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8132        int userId = UserHandle.getCallingUserId();
8133        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8134        if (ai == null) {
8135            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8136                + loadingPackageName + ", user=" + userId);
8137            return;
8138        }
8139        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8140    }
8141
8142    // TODO: this is not used nor needed. Delete it.
8143    @Override
8144    public boolean performDexOptIfNeeded(String packageName) {
8145        int dexOptStatus = performDexOptTraced(packageName,
8146                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8147        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8148    }
8149
8150    @Override
8151    public boolean performDexOpt(String packageName,
8152            boolean checkProfiles, int compileReason, boolean force) {
8153        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8154                getCompilerFilterForReason(compileReason), force);
8155        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8156    }
8157
8158    @Override
8159    public boolean performDexOptMode(String packageName,
8160            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8161        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8162                targetCompilerFilter, force);
8163        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8164    }
8165
8166    private int performDexOptTraced(String packageName,
8167                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8168        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8169        try {
8170            return performDexOptInternal(packageName, checkProfiles,
8171                    targetCompilerFilter, force);
8172        } finally {
8173            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8174        }
8175    }
8176
8177    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8178    // if the package can now be considered up to date for the given filter.
8179    private int performDexOptInternal(String packageName,
8180                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8181        PackageParser.Package p;
8182        synchronized (mPackages) {
8183            p = mPackages.get(packageName);
8184            if (p == null) {
8185                // Package could not be found. Report failure.
8186                return PackageDexOptimizer.DEX_OPT_FAILED;
8187            }
8188            mPackageUsage.maybeWriteAsync(mPackages);
8189            mCompilerStats.maybeWriteAsync();
8190        }
8191        long callingId = Binder.clearCallingIdentity();
8192        try {
8193            synchronized (mInstallLock) {
8194                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8195                        targetCompilerFilter, force);
8196            }
8197        } finally {
8198            Binder.restoreCallingIdentity(callingId);
8199        }
8200    }
8201
8202    public ArraySet<String> getOptimizablePackages() {
8203        ArraySet<String> pkgs = new ArraySet<String>();
8204        synchronized (mPackages) {
8205            for (PackageParser.Package p : mPackages.values()) {
8206                if (PackageDexOptimizer.canOptimizePackage(p)) {
8207                    pkgs.add(p.packageName);
8208                }
8209            }
8210        }
8211        return pkgs;
8212    }
8213
8214    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8215            boolean checkProfiles, String targetCompilerFilter,
8216            boolean force) {
8217        // Select the dex optimizer based on the force parameter.
8218        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8219        //       allocate an object here.
8220        PackageDexOptimizer pdo = force
8221                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8222                : mPackageDexOptimizer;
8223
8224        // Optimize all dependencies first. Note: we ignore the return value and march on
8225        // on errors.
8226        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8227        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8228        if (!deps.isEmpty()) {
8229            for (PackageParser.Package depPackage : deps) {
8230                // TODO: Analyze and investigate if we (should) profile libraries.
8231                // Currently this will do a full compilation of the library by default.
8232                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8233                        false /* checkProfiles */,
8234                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8235                        getOrCreateCompilerPackageStats(depPackage));
8236            }
8237        }
8238        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8239                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8240    }
8241
8242    // Performs dexopt on the used secondary dex files belonging to the given package.
8243    // Returns true if all dex files were process successfully (which could mean either dexopt or
8244    // skip). Returns false if any of the files caused errors.
8245    @Override
8246    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8247            boolean force) {
8248        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8249    }
8250
8251    /**
8252     * Reconcile the information we have about the secondary dex files belonging to
8253     * {@code packagName} and the actual dex files. For all dex files that were
8254     * deleted, update the internal records and delete the generated oat files.
8255     */
8256    @Override
8257    public void reconcileSecondaryDexFiles(String packageName) {
8258        mDexManager.reconcileSecondaryDexFiles(packageName);
8259    }
8260
8261    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8262    // a reference there.
8263    /*package*/ DexManager getDexManager() {
8264        return mDexManager;
8265    }
8266
8267    /**
8268     * Execute the background dexopt job immediately.
8269     */
8270    @Override
8271    public boolean runBackgroundDexoptJob() {
8272        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8273    }
8274
8275    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8276        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8277                || p.usesStaticLibraries != null) {
8278            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8279            Set<String> collectedNames = new HashSet<>();
8280            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8281
8282            retValue.remove(p);
8283
8284            return retValue;
8285        } else {
8286            return Collections.emptyList();
8287        }
8288    }
8289
8290    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8291            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8292        if (!collectedNames.contains(p.packageName)) {
8293            collectedNames.add(p.packageName);
8294            collected.add(p);
8295
8296            if (p.usesLibraries != null) {
8297                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8298                        null, collected, collectedNames);
8299            }
8300            if (p.usesOptionalLibraries != null) {
8301                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8302                        null, collected, collectedNames);
8303            }
8304            if (p.usesStaticLibraries != null) {
8305                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8306                        p.usesStaticLibrariesVersions, collected, collectedNames);
8307            }
8308        }
8309    }
8310
8311    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8312            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8313        final int libNameCount = libs.size();
8314        for (int i = 0; i < libNameCount; i++) {
8315            String libName = libs.get(i);
8316            int version = (versions != null && versions.length == libNameCount)
8317                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8318            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8319            if (libPkg != null) {
8320                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8321            }
8322        }
8323    }
8324
8325    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8326        synchronized (mPackages) {
8327            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8328            if (libEntry != null) {
8329                return mPackages.get(libEntry.apk);
8330            }
8331            return null;
8332        }
8333    }
8334
8335    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8336        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8337        if (versionedLib == null) {
8338            return null;
8339        }
8340        return versionedLib.get(version);
8341    }
8342
8343    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8344        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8345                pkg.staticSharedLibName);
8346        if (versionedLib == null) {
8347            return null;
8348        }
8349        int previousLibVersion = -1;
8350        final int versionCount = versionedLib.size();
8351        for (int i = 0; i < versionCount; i++) {
8352            final int libVersion = versionedLib.keyAt(i);
8353            if (libVersion < pkg.staticSharedLibVersion) {
8354                previousLibVersion = Math.max(previousLibVersion, libVersion);
8355            }
8356        }
8357        if (previousLibVersion >= 0) {
8358            return versionedLib.get(previousLibVersion);
8359        }
8360        return null;
8361    }
8362
8363    public void shutdown() {
8364        mPackageUsage.writeNow(mPackages);
8365        mCompilerStats.writeNow();
8366    }
8367
8368    @Override
8369    public void dumpProfiles(String packageName) {
8370        PackageParser.Package pkg;
8371        synchronized (mPackages) {
8372            pkg = mPackages.get(packageName);
8373            if (pkg == null) {
8374                throw new IllegalArgumentException("Unknown package: " + packageName);
8375            }
8376        }
8377        /* Only the shell, root, or the app user should be able to dump profiles. */
8378        int callingUid = Binder.getCallingUid();
8379        if (callingUid != Process.SHELL_UID &&
8380            callingUid != Process.ROOT_UID &&
8381            callingUid != pkg.applicationInfo.uid) {
8382            throw new SecurityException("dumpProfiles");
8383        }
8384
8385        synchronized (mInstallLock) {
8386            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8387            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8388            try {
8389                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8390                String codePaths = TextUtils.join(";", allCodePaths);
8391                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8392            } catch (InstallerException e) {
8393                Slog.w(TAG, "Failed to dump profiles", e);
8394            }
8395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8396        }
8397    }
8398
8399    @Override
8400    public void forceDexOpt(String packageName) {
8401        enforceSystemOrRoot("forceDexOpt");
8402
8403        PackageParser.Package pkg;
8404        synchronized (mPackages) {
8405            pkg = mPackages.get(packageName);
8406            if (pkg == null) {
8407                throw new IllegalArgumentException("Unknown package: " + packageName);
8408            }
8409        }
8410
8411        synchronized (mInstallLock) {
8412            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8413
8414            // Whoever is calling forceDexOpt wants a fully compiled package.
8415            // Don't use profiles since that may cause compilation to be skipped.
8416            final int res = performDexOptInternalWithDependenciesLI(pkg,
8417                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8418                    true /* force */);
8419
8420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8421            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8422                throw new IllegalStateException("Failed to dexopt: " + res);
8423            }
8424        }
8425    }
8426
8427    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8428        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8429            Slog.w(TAG, "Unable to update from " + oldPkg.name
8430                    + " to " + newPkg.packageName
8431                    + ": old package not in system partition");
8432            return false;
8433        } else if (mPackages.get(oldPkg.name) != null) {
8434            Slog.w(TAG, "Unable to update from " + oldPkg.name
8435                    + " to " + newPkg.packageName
8436                    + ": old package still exists");
8437            return false;
8438        }
8439        return true;
8440    }
8441
8442    void removeCodePathLI(File codePath) {
8443        if (codePath.isDirectory()) {
8444            try {
8445                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8446            } catch (InstallerException e) {
8447                Slog.w(TAG, "Failed to remove code path", e);
8448            }
8449        } else {
8450            codePath.delete();
8451        }
8452    }
8453
8454    private int[] resolveUserIds(int userId) {
8455        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8456    }
8457
8458    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8459        if (pkg == null) {
8460            Slog.wtf(TAG, "Package was null!", new Throwable());
8461            return;
8462        }
8463        clearAppDataLeafLIF(pkg, userId, flags);
8464        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8465        for (int i = 0; i < childCount; i++) {
8466            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8467        }
8468    }
8469
8470    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8471        final PackageSetting ps;
8472        synchronized (mPackages) {
8473            ps = mSettings.mPackages.get(pkg.packageName);
8474        }
8475        for (int realUserId : resolveUserIds(userId)) {
8476            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8477            try {
8478                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8479                        ceDataInode);
8480            } catch (InstallerException e) {
8481                Slog.w(TAG, String.valueOf(e));
8482            }
8483        }
8484    }
8485
8486    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8487        if (pkg == null) {
8488            Slog.wtf(TAG, "Package was null!", new Throwable());
8489            return;
8490        }
8491        destroyAppDataLeafLIF(pkg, userId, flags);
8492        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8493        for (int i = 0; i < childCount; i++) {
8494            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8495        }
8496    }
8497
8498    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8499        final PackageSetting ps;
8500        synchronized (mPackages) {
8501            ps = mSettings.mPackages.get(pkg.packageName);
8502        }
8503        for (int realUserId : resolveUserIds(userId)) {
8504            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8505            try {
8506                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8507                        ceDataInode);
8508            } catch (InstallerException e) {
8509                Slog.w(TAG, String.valueOf(e));
8510            }
8511        }
8512    }
8513
8514    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8515        if (pkg == null) {
8516            Slog.wtf(TAG, "Package was null!", new Throwable());
8517            return;
8518        }
8519        destroyAppProfilesLeafLIF(pkg);
8520        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8521        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8522        for (int i = 0; i < childCount; i++) {
8523            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8524            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8525                    true /* removeBaseMarker */);
8526        }
8527    }
8528
8529    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8530            boolean removeBaseMarker) {
8531        if (pkg.isForwardLocked()) {
8532            return;
8533        }
8534
8535        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8536            try {
8537                path = PackageManagerServiceUtils.realpath(new File(path));
8538            } catch (IOException e) {
8539                // TODO: Should we return early here ?
8540                Slog.w(TAG, "Failed to get canonical path", e);
8541                continue;
8542            }
8543
8544            final String useMarker = path.replace('/', '@');
8545            for (int realUserId : resolveUserIds(userId)) {
8546                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8547                if (removeBaseMarker) {
8548                    File foreignUseMark = new File(profileDir, useMarker);
8549                    if (foreignUseMark.exists()) {
8550                        if (!foreignUseMark.delete()) {
8551                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8552                                    + pkg.packageName);
8553                        }
8554                    }
8555                }
8556
8557                File[] markers = profileDir.listFiles();
8558                if (markers != null) {
8559                    final String searchString = "@" + pkg.packageName + "@";
8560                    // We also delete all markers that contain the package name we're
8561                    // uninstalling. These are associated with secondary dex-files belonging
8562                    // to the package. Reconstructing the path of these dex files is messy
8563                    // in general.
8564                    for (File marker : markers) {
8565                        if (marker.getName().indexOf(searchString) > 0) {
8566                            if (!marker.delete()) {
8567                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8568                                    + pkg.packageName);
8569                            }
8570                        }
8571                    }
8572                }
8573            }
8574        }
8575    }
8576
8577    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8578        try {
8579            mInstaller.destroyAppProfiles(pkg.packageName);
8580        } catch (InstallerException e) {
8581            Slog.w(TAG, String.valueOf(e));
8582        }
8583    }
8584
8585    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8586        if (pkg == null) {
8587            Slog.wtf(TAG, "Package was null!", new Throwable());
8588            return;
8589        }
8590        clearAppProfilesLeafLIF(pkg);
8591        // We don't remove the base foreign use marker when clearing profiles because
8592        // we will rename it when the app is updated. Unlike the actual profile contents,
8593        // the foreign use marker is good across installs.
8594        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8595        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8596        for (int i = 0; i < childCount; i++) {
8597            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8598        }
8599    }
8600
8601    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8602        try {
8603            mInstaller.clearAppProfiles(pkg.packageName);
8604        } catch (InstallerException e) {
8605            Slog.w(TAG, String.valueOf(e));
8606        }
8607    }
8608
8609    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8610            long lastUpdateTime) {
8611        // Set parent install/update time
8612        PackageSetting ps = (PackageSetting) pkg.mExtras;
8613        if (ps != null) {
8614            ps.firstInstallTime = firstInstallTime;
8615            ps.lastUpdateTime = lastUpdateTime;
8616        }
8617        // Set children install/update time
8618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8619        for (int i = 0; i < childCount; i++) {
8620            PackageParser.Package childPkg = pkg.childPackages.get(i);
8621            ps = (PackageSetting) childPkg.mExtras;
8622            if (ps != null) {
8623                ps.firstInstallTime = firstInstallTime;
8624                ps.lastUpdateTime = lastUpdateTime;
8625            }
8626        }
8627    }
8628
8629    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8630            PackageParser.Package changingLib) {
8631        if (file.path != null) {
8632            usesLibraryFiles.add(file.path);
8633            return;
8634        }
8635        PackageParser.Package p = mPackages.get(file.apk);
8636        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8637            // If we are doing this while in the middle of updating a library apk,
8638            // then we need to make sure to use that new apk for determining the
8639            // dependencies here.  (We haven't yet finished committing the new apk
8640            // to the package manager state.)
8641            if (p == null || p.packageName.equals(changingLib.packageName)) {
8642                p = changingLib;
8643            }
8644        }
8645        if (p != null) {
8646            usesLibraryFiles.addAll(p.getAllCodePaths());
8647        }
8648    }
8649
8650    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8651            PackageParser.Package changingLib) throws PackageManagerException {
8652        if (pkg == null) {
8653            return;
8654        }
8655        ArraySet<String> usesLibraryFiles = null;
8656        if (pkg.usesLibraries != null) {
8657            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8658                    null, null, pkg.packageName, changingLib, true, null);
8659        }
8660        if (pkg.usesStaticLibraries != null) {
8661            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8662                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8663                    pkg.packageName, changingLib, true, usesLibraryFiles);
8664        }
8665        if (pkg.usesOptionalLibraries != null) {
8666            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8667                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8668        }
8669        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8670            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8671        } else {
8672            pkg.usesLibraryFiles = null;
8673        }
8674    }
8675
8676    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8677            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8678            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8679            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8680            throws PackageManagerException {
8681        final int libCount = requestedLibraries.size();
8682        for (int i = 0; i < libCount; i++) {
8683            final String libName = requestedLibraries.get(i);
8684            final int libVersion = requiredVersions != null ? requiredVersions[i]
8685                    : SharedLibraryInfo.VERSION_UNDEFINED;
8686            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8687            if (libEntry == null) {
8688                if (required) {
8689                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8690                            "Package " + packageName + " requires unavailable shared library "
8691                                    + libName + "; failing!");
8692                } else {
8693                    Slog.w(TAG, "Package " + packageName
8694                            + " desires unavailable shared library "
8695                            + libName + "; ignoring!");
8696                }
8697            } else {
8698                if (requiredVersions != null && requiredCertDigests != null) {
8699                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8700                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8701                            "Package " + packageName + " requires unavailable static shared"
8702                                    + " library " + libName + " version "
8703                                    + libEntry.info.getVersion() + "; failing!");
8704                    }
8705
8706                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8707                    if (libPkg == null) {
8708                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8709                                "Package " + packageName + " requires unavailable static shared"
8710                                        + " library; failing!");
8711                    }
8712
8713                    String expectedCertDigest = requiredCertDigests[i];
8714                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8715                                libPkg.mSignatures[0]);
8716                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8717                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8718                                "Package " + packageName + " requires differently signed" +
8719                                        " static shared library; failing!");
8720                    }
8721                }
8722
8723                if (outUsedLibraries == null) {
8724                    outUsedLibraries = new ArraySet<>();
8725                }
8726                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8727            }
8728        }
8729        return outUsedLibraries;
8730    }
8731
8732    private static boolean hasString(List<String> list, List<String> which) {
8733        if (list == null) {
8734            return false;
8735        }
8736        for (int i=list.size()-1; i>=0; i--) {
8737            for (int j=which.size()-1; j>=0; j--) {
8738                if (which.get(j).equals(list.get(i))) {
8739                    return true;
8740                }
8741            }
8742        }
8743        return false;
8744    }
8745
8746    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8747            PackageParser.Package changingPkg) {
8748        ArrayList<PackageParser.Package> res = null;
8749        for (PackageParser.Package pkg : mPackages.values()) {
8750            if (changingPkg != null
8751                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8752                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8753                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8754                            changingPkg.staticSharedLibName)) {
8755                return null;
8756            }
8757            if (res == null) {
8758                res = new ArrayList<>();
8759            }
8760            res.add(pkg);
8761            try {
8762                updateSharedLibrariesLPr(pkg, changingPkg);
8763            } catch (PackageManagerException e) {
8764                // If a system app update or an app and a required lib missing we
8765                // delete the package and for updated system apps keep the data as
8766                // it is better for the user to reinstall than to be in an limbo
8767                // state. Also libs disappearing under an app should never happen
8768                // - just in case.
8769                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8770                    final int flags = pkg.isUpdatedSystemApp()
8771                            ? PackageManager.DELETE_KEEP_DATA : 0;
8772                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8773                            flags , null, true, null);
8774                }
8775                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8776            }
8777        }
8778        return res;
8779    }
8780
8781    /**
8782     * Derive the value of the {@code cpuAbiOverride} based on the provided
8783     * value and an optional stored value from the package settings.
8784     */
8785    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8786        String cpuAbiOverride = null;
8787
8788        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8789            cpuAbiOverride = null;
8790        } else if (abiOverride != null) {
8791            cpuAbiOverride = abiOverride;
8792        } else if (settings != null) {
8793            cpuAbiOverride = settings.cpuAbiOverrideString;
8794        }
8795
8796        return cpuAbiOverride;
8797    }
8798
8799    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8800            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8801                    throws PackageManagerException {
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8803        // If the package has children and this is the first dive in the function
8804        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8805        // whether all packages (parent and children) would be successfully scanned
8806        // before the actual scan since scanning mutates internal state and we want
8807        // to atomically install the package and its children.
8808        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8809            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8810                scanFlags |= SCAN_CHECK_ONLY;
8811            }
8812        } else {
8813            scanFlags &= ~SCAN_CHECK_ONLY;
8814        }
8815
8816        final PackageParser.Package scannedPkg;
8817        try {
8818            // Scan the parent
8819            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8820            // Scan the children
8821            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8822            for (int i = 0; i < childCount; i++) {
8823                PackageParser.Package childPkg = pkg.childPackages.get(i);
8824                scanPackageLI(childPkg, policyFlags,
8825                        scanFlags, currentTime, user);
8826            }
8827        } finally {
8828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8829        }
8830
8831        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8832            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8833        }
8834
8835        return scannedPkg;
8836    }
8837
8838    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8839            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8840        boolean success = false;
8841        try {
8842            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8843                    currentTime, user);
8844            success = true;
8845            return res;
8846        } finally {
8847            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8848                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8849                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8850                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8851                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8852            }
8853        }
8854    }
8855
8856    /**
8857     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8858     */
8859    private static boolean apkHasCode(String fileName) {
8860        StrictJarFile jarFile = null;
8861        try {
8862            jarFile = new StrictJarFile(fileName,
8863                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8864            return jarFile.findEntry("classes.dex") != null;
8865        } catch (IOException ignore) {
8866        } finally {
8867            try {
8868                if (jarFile != null) {
8869                    jarFile.close();
8870                }
8871            } catch (IOException ignore) {}
8872        }
8873        return false;
8874    }
8875
8876    /**
8877     * Enforces code policy for the package. This ensures that if an APK has
8878     * declared hasCode="true" in its manifest that the APK actually contains
8879     * code.
8880     *
8881     * @throws PackageManagerException If bytecode could not be found when it should exist
8882     */
8883    private static void assertCodePolicy(PackageParser.Package pkg)
8884            throws PackageManagerException {
8885        final boolean shouldHaveCode =
8886                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8887        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8888            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8889                    "Package " + pkg.baseCodePath + " code is missing");
8890        }
8891
8892        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8893            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8894                final boolean splitShouldHaveCode =
8895                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8896                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8897                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8898                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8899                }
8900            }
8901        }
8902    }
8903
8904    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8905            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8906                    throws PackageManagerException {
8907        if (DEBUG_PACKAGE_SCANNING) {
8908            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8909                Log.d(TAG, "Scanning package " + pkg.packageName);
8910        }
8911
8912        applyPolicy(pkg, policyFlags);
8913
8914        assertPackageIsValid(pkg, policyFlags, scanFlags);
8915
8916        // Initialize package source and resource directories
8917        final File scanFile = new File(pkg.codePath);
8918        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8919        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8920
8921        SharedUserSetting suid = null;
8922        PackageSetting pkgSetting = null;
8923
8924        // Getting the package setting may have a side-effect, so if we
8925        // are only checking if scan would succeed, stash a copy of the
8926        // old setting to restore at the end.
8927        PackageSetting nonMutatedPs = null;
8928
8929        // We keep references to the derived CPU Abis from settings in oder to reuse
8930        // them in the case where we're not upgrading or booting for the first time.
8931        String primaryCpuAbiFromSettings = null;
8932        String secondaryCpuAbiFromSettings = null;
8933
8934        // writer
8935        synchronized (mPackages) {
8936            if (pkg.mSharedUserId != null) {
8937                // SIDE EFFECTS; may potentially allocate a new shared user
8938                suid = mSettings.getSharedUserLPw(
8939                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8940                if (DEBUG_PACKAGE_SCANNING) {
8941                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8942                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8943                                + "): packages=" + suid.packages);
8944                }
8945            }
8946
8947            // Check if we are renaming from an original package name.
8948            PackageSetting origPackage = null;
8949            String realName = null;
8950            if (pkg.mOriginalPackages != null) {
8951                // This package may need to be renamed to a previously
8952                // installed name.  Let's check on that...
8953                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8954                if (pkg.mOriginalPackages.contains(renamed)) {
8955                    // This package had originally been installed as the
8956                    // original name, and we have already taken care of
8957                    // transitioning to the new one.  Just update the new
8958                    // one to continue using the old name.
8959                    realName = pkg.mRealPackage;
8960                    if (!pkg.packageName.equals(renamed)) {
8961                        // Callers into this function may have already taken
8962                        // care of renaming the package; only do it here if
8963                        // it is not already done.
8964                        pkg.setPackageName(renamed);
8965                    }
8966                } else {
8967                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8968                        if ((origPackage = mSettings.getPackageLPr(
8969                                pkg.mOriginalPackages.get(i))) != null) {
8970                            // We do have the package already installed under its
8971                            // original name...  should we use it?
8972                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8973                                // New package is not compatible with original.
8974                                origPackage = null;
8975                                continue;
8976                            } else if (origPackage.sharedUser != null) {
8977                                // Make sure uid is compatible between packages.
8978                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8979                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8980                                            + " to " + pkg.packageName + ": old uid "
8981                                            + origPackage.sharedUser.name
8982                                            + " differs from " + pkg.mSharedUserId);
8983                                    origPackage = null;
8984                                    continue;
8985                                }
8986                                // TODO: Add case when shared user id is added [b/28144775]
8987                            } else {
8988                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8989                                        + pkg.packageName + " to old name " + origPackage.name);
8990                            }
8991                            break;
8992                        }
8993                    }
8994                }
8995            }
8996
8997            if (mTransferedPackages.contains(pkg.packageName)) {
8998                Slog.w(TAG, "Package " + pkg.packageName
8999                        + " was transferred to another, but its .apk remains");
9000            }
9001
9002            // See comments in nonMutatedPs declaration
9003            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9004                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9005                if (foundPs != null) {
9006                    nonMutatedPs = new PackageSetting(foundPs);
9007                }
9008            }
9009
9010            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9011                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9012                if (foundPs != null) {
9013                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9014                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9015                }
9016            }
9017
9018            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9019            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9020                PackageManagerService.reportSettingsProblem(Log.WARN,
9021                        "Package " + pkg.packageName + " shared user changed from "
9022                                + (pkgSetting.sharedUser != null
9023                                        ? pkgSetting.sharedUser.name : "<nothing>")
9024                                + " to "
9025                                + (suid != null ? suid.name : "<nothing>")
9026                                + "; replacing with new");
9027                pkgSetting = null;
9028            }
9029            final PackageSetting oldPkgSetting =
9030                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9031            final PackageSetting disabledPkgSetting =
9032                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9033
9034            String[] usesStaticLibraries = null;
9035            if (pkg.usesStaticLibraries != null) {
9036                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9037                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9038            }
9039
9040            if (pkgSetting == null) {
9041                final String parentPackageName = (pkg.parentPackage != null)
9042                        ? pkg.parentPackage.packageName : null;
9043
9044                // REMOVE SharedUserSetting from method; update in a separate call
9045                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9046                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9047                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9048                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9049                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9050                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9051                        UserManagerService.getInstance(), usesStaticLibraries,
9052                        pkg.usesStaticLibrariesVersions);
9053                // SIDE EFFECTS; updates system state; move elsewhere
9054                if (origPackage != null) {
9055                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9056                }
9057                mSettings.addUserToSettingLPw(pkgSetting);
9058            } else {
9059                // REMOVE SharedUserSetting from method; update in a separate call.
9060                //
9061                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9062                // secondaryCpuAbi are not known at this point so we always update them
9063                // to null here, only to reset them at a later point.
9064                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9065                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9066                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9067                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9068                        UserManagerService.getInstance(), usesStaticLibraries,
9069                        pkg.usesStaticLibrariesVersions);
9070            }
9071            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9072            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9073
9074            // SIDE EFFECTS; modifies system state; move elsewhere
9075            if (pkgSetting.origPackage != null) {
9076                // If we are first transitioning from an original package,
9077                // fix up the new package's name now.  We need to do this after
9078                // looking up the package under its new name, so getPackageLP
9079                // can take care of fiddling things correctly.
9080                pkg.setPackageName(origPackage.name);
9081
9082                // File a report about this.
9083                String msg = "New package " + pkgSetting.realName
9084                        + " renamed to replace old package " + pkgSetting.name;
9085                reportSettingsProblem(Log.WARN, msg);
9086
9087                // Make a note of it.
9088                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9089                    mTransferedPackages.add(origPackage.name);
9090                }
9091
9092                // No longer need to retain this.
9093                pkgSetting.origPackage = null;
9094            }
9095
9096            // SIDE EFFECTS; modifies system state; move elsewhere
9097            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9098                // Make a note of it.
9099                mTransferedPackages.add(pkg.packageName);
9100            }
9101
9102            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9103                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9104            }
9105
9106            if ((scanFlags & SCAN_BOOTING) == 0
9107                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9108                // Check all shared libraries and map to their actual file path.
9109                // We only do this here for apps not on a system dir, because those
9110                // are the only ones that can fail an install due to this.  We
9111                // will take care of the system apps by updating all of their
9112                // library paths after the scan is done. Also during the initial
9113                // scan don't update any libs as we do this wholesale after all
9114                // apps are scanned to avoid dependency based scanning.
9115                updateSharedLibrariesLPr(pkg, null);
9116            }
9117
9118            if (mFoundPolicyFile) {
9119                SELinuxMMAC.assignSeinfoValue(pkg);
9120            }
9121
9122            pkg.applicationInfo.uid = pkgSetting.appId;
9123            pkg.mExtras = pkgSetting;
9124
9125
9126            // Static shared libs have same package with different versions where
9127            // we internally use a synthetic package name to allow multiple versions
9128            // of the same package, therefore we need to compare signatures against
9129            // the package setting for the latest library version.
9130            PackageSetting signatureCheckPs = pkgSetting;
9131            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9132                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9133                if (libraryEntry != null) {
9134                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9135                }
9136            }
9137
9138            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9139                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9140                    // We just determined the app is signed correctly, so bring
9141                    // over the latest parsed certs.
9142                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9143                } else {
9144                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9145                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9146                                "Package " + pkg.packageName + " upgrade keys do not match the "
9147                                + "previously installed version");
9148                    } else {
9149                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9150                        String msg = "System package " + pkg.packageName
9151                                + " signature changed; retaining data.";
9152                        reportSettingsProblem(Log.WARN, msg);
9153                    }
9154                }
9155            } else {
9156                try {
9157                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9158                    verifySignaturesLP(signatureCheckPs, pkg);
9159                    // We just determined the app is signed correctly, so bring
9160                    // over the latest parsed certs.
9161                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9162                } catch (PackageManagerException e) {
9163                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9164                        throw e;
9165                    }
9166                    // The signature has changed, but this package is in the system
9167                    // image...  let's recover!
9168                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9169                    // However...  if this package is part of a shared user, but it
9170                    // doesn't match the signature of the shared user, let's fail.
9171                    // What this means is that you can't change the signatures
9172                    // associated with an overall shared user, which doesn't seem all
9173                    // that unreasonable.
9174                    if (signatureCheckPs.sharedUser != null) {
9175                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9176                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9177                            throw new PackageManagerException(
9178                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9179                                    "Signature mismatch for shared user: "
9180                                            + pkgSetting.sharedUser);
9181                        }
9182                    }
9183                    // File a report about this.
9184                    String msg = "System package " + pkg.packageName
9185                            + " signature changed; retaining data.";
9186                    reportSettingsProblem(Log.WARN, msg);
9187                }
9188            }
9189
9190            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9191                // This package wants to adopt ownership of permissions from
9192                // another package.
9193                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9194                    final String origName = pkg.mAdoptPermissions.get(i);
9195                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9196                    if (orig != null) {
9197                        if (verifyPackageUpdateLPr(orig, pkg)) {
9198                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9199                                    + pkg.packageName);
9200                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9201                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9202                        }
9203                    }
9204                }
9205            }
9206        }
9207
9208        pkg.applicationInfo.processName = fixProcessName(
9209                pkg.applicationInfo.packageName,
9210                pkg.applicationInfo.processName);
9211
9212        if (pkg != mPlatformPackage) {
9213            // Get all of our default paths setup
9214            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9215        }
9216
9217        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9218
9219        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9220            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9221                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9222                derivePackageAbi(
9223                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9224                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9225
9226                // Some system apps still use directory structure for native libraries
9227                // in which case we might end up not detecting abi solely based on apk
9228                // structure. Try to detect abi based on directory structure.
9229                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9230                        pkg.applicationInfo.primaryCpuAbi == null) {
9231                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9232                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9233                }
9234            } else {
9235                // This is not a first boot or an upgrade, don't bother deriving the
9236                // ABI during the scan. Instead, trust the value that was stored in the
9237                // package setting.
9238                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9239                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9240
9241                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9242
9243                if (DEBUG_ABI_SELECTION) {
9244                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9245                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9246                        pkg.applicationInfo.secondaryCpuAbi);
9247                }
9248            }
9249        } else {
9250            if ((scanFlags & SCAN_MOVE) != 0) {
9251                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9252                // but we already have this packages package info in the PackageSetting. We just
9253                // use that and derive the native library path based on the new codepath.
9254                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9255                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9256            }
9257
9258            // Set native library paths again. For moves, the path will be updated based on the
9259            // ABIs we've determined above. For non-moves, the path will be updated based on the
9260            // ABIs we determined during compilation, but the path will depend on the final
9261            // package path (after the rename away from the stage path).
9262            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9263        }
9264
9265        // This is a special case for the "system" package, where the ABI is
9266        // dictated by the zygote configuration (and init.rc). We should keep track
9267        // of this ABI so that we can deal with "normal" applications that run under
9268        // the same UID correctly.
9269        if (mPlatformPackage == pkg) {
9270            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9271                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9272        }
9273
9274        // If there's a mismatch between the abi-override in the package setting
9275        // and the abiOverride specified for the install. Warn about this because we
9276        // would've already compiled the app without taking the package setting into
9277        // account.
9278        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9279            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9280                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9281                        " for package " + pkg.packageName);
9282            }
9283        }
9284
9285        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9286        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9287        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9288
9289        // Copy the derived override back to the parsed package, so that we can
9290        // update the package settings accordingly.
9291        pkg.cpuAbiOverride = cpuAbiOverride;
9292
9293        if (DEBUG_ABI_SELECTION) {
9294            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9295                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9296                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9297        }
9298
9299        // Push the derived path down into PackageSettings so we know what to
9300        // clean up at uninstall time.
9301        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9302
9303        if (DEBUG_ABI_SELECTION) {
9304            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9305                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9306                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9307        }
9308
9309        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9310        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9311            // We don't do this here during boot because we can do it all
9312            // at once after scanning all existing packages.
9313            //
9314            // We also do this *before* we perform dexopt on this package, so that
9315            // we can avoid redundant dexopts, and also to make sure we've got the
9316            // code and package path correct.
9317            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9318        }
9319
9320        if (mFactoryTest && pkg.requestedPermissions.contains(
9321                android.Manifest.permission.FACTORY_TEST)) {
9322            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9323        }
9324
9325        if (isSystemApp(pkg)) {
9326            pkgSetting.isOrphaned = true;
9327        }
9328
9329        // Take care of first install / last update times.
9330        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9331        if (currentTime != 0) {
9332            if (pkgSetting.firstInstallTime == 0) {
9333                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9334            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9335                pkgSetting.lastUpdateTime = currentTime;
9336            }
9337        } else if (pkgSetting.firstInstallTime == 0) {
9338            // We need *something*.  Take time time stamp of the file.
9339            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9340        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9341            if (scanFileTime != pkgSetting.timeStamp) {
9342                // A package on the system image has changed; consider this
9343                // to be an update.
9344                pkgSetting.lastUpdateTime = scanFileTime;
9345            }
9346        }
9347        pkgSetting.setTimeStamp(scanFileTime);
9348
9349        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9350            if (nonMutatedPs != null) {
9351                synchronized (mPackages) {
9352                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9353                }
9354            }
9355        } else {
9356            // Modify state for the given package setting
9357            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9358                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9359            if (isEphemeral(pkg)) {
9360                final int userId = user == null ? 0 : user.getIdentifier();
9361                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9362            }
9363        }
9364        return pkg;
9365    }
9366
9367    /**
9368     * Applies policy to the parsed package based upon the given policy flags.
9369     * Ensures the package is in a good state.
9370     * <p>
9371     * Implementation detail: This method must NOT have any side effect. It would
9372     * ideally be static, but, it requires locks to read system state.
9373     */
9374    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9375        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9376            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9377            if (pkg.applicationInfo.isDirectBootAware()) {
9378                // we're direct boot aware; set for all components
9379                for (PackageParser.Service s : pkg.services) {
9380                    s.info.encryptionAware = s.info.directBootAware = true;
9381                }
9382                for (PackageParser.Provider p : pkg.providers) {
9383                    p.info.encryptionAware = p.info.directBootAware = true;
9384                }
9385                for (PackageParser.Activity a : pkg.activities) {
9386                    a.info.encryptionAware = a.info.directBootAware = true;
9387                }
9388                for (PackageParser.Activity r : pkg.receivers) {
9389                    r.info.encryptionAware = r.info.directBootAware = true;
9390                }
9391            }
9392        } else {
9393            // Only allow system apps to be flagged as core apps.
9394            pkg.coreApp = false;
9395            // clear flags not applicable to regular apps
9396            pkg.applicationInfo.privateFlags &=
9397                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9398            pkg.applicationInfo.privateFlags &=
9399                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9400        }
9401        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9402
9403        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9404            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9405        }
9406
9407        if (!isSystemApp(pkg)) {
9408            // Only system apps can use these features.
9409            pkg.mOriginalPackages = null;
9410            pkg.mRealPackage = null;
9411            pkg.mAdoptPermissions = null;
9412        }
9413    }
9414
9415    /**
9416     * Asserts the parsed package is valid according to the given policy. If the
9417     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9418     * <p>
9419     * Implementation detail: This method must NOT have any side effects. It would
9420     * ideally be static, but, it requires locks to read system state.
9421     *
9422     * @throws PackageManagerException If the package fails any of the validation checks
9423     */
9424    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9425            throws PackageManagerException {
9426        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9427            assertCodePolicy(pkg);
9428        }
9429
9430        if (pkg.applicationInfo.getCodePath() == null ||
9431                pkg.applicationInfo.getResourcePath() == null) {
9432            // Bail out. The resource and code paths haven't been set.
9433            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9434                    "Code and resource paths haven't been set correctly");
9435        }
9436
9437        // Make sure we're not adding any bogus keyset info
9438        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9439        ksms.assertScannedPackageValid(pkg);
9440
9441        synchronized (mPackages) {
9442            // The special "android" package can only be defined once
9443            if (pkg.packageName.equals("android")) {
9444                if (mAndroidApplication != null) {
9445                    Slog.w(TAG, "*************************************************");
9446                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9447                    Slog.w(TAG, " codePath=" + pkg.codePath);
9448                    Slog.w(TAG, "*************************************************");
9449                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9450                            "Core android package being redefined.  Skipping.");
9451                }
9452            }
9453
9454            // A package name must be unique; don't allow duplicates
9455            if (mPackages.containsKey(pkg.packageName)) {
9456                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9457                        "Application package " + pkg.packageName
9458                        + " already installed.  Skipping duplicate.");
9459            }
9460
9461            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9462                // Static libs have a synthetic package name containing the version
9463                // but we still want the base name to be unique.
9464                if (mPackages.containsKey(pkg.manifestPackageName)) {
9465                    throw new PackageManagerException(
9466                            "Duplicate static shared lib provider package");
9467                }
9468
9469                // Static shared libraries should have at least O target SDK
9470                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9471                    throw new PackageManagerException(
9472                            "Packages declaring static-shared libs must target O SDK or higher");
9473                }
9474
9475                // Package declaring static a shared lib cannot be ephemeral
9476                if (pkg.applicationInfo.isInstantApp()) {
9477                    throw new PackageManagerException(
9478                            "Packages declaring static-shared libs cannot be ephemeral");
9479                }
9480
9481                // Package declaring static a shared lib cannot be renamed since the package
9482                // name is synthetic and apps can't code around package manager internals.
9483                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9484                    throw new PackageManagerException(
9485                            "Packages declaring static-shared libs cannot be renamed");
9486                }
9487
9488                // Package declaring static a shared lib cannot declare child packages
9489                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9490                    throw new PackageManagerException(
9491                            "Packages declaring static-shared libs cannot have child packages");
9492                }
9493
9494                // Package declaring static a shared lib cannot declare dynamic libs
9495                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9496                    throw new PackageManagerException(
9497                            "Packages declaring static-shared libs cannot declare dynamic libs");
9498                }
9499
9500                // Package declaring static a shared lib cannot declare shared users
9501                if (pkg.mSharedUserId != null) {
9502                    throw new PackageManagerException(
9503                            "Packages declaring static-shared libs cannot declare shared users");
9504                }
9505
9506                // Static shared libs cannot declare activities
9507                if (!pkg.activities.isEmpty()) {
9508                    throw new PackageManagerException(
9509                            "Static shared libs cannot declare activities");
9510                }
9511
9512                // Static shared libs cannot declare services
9513                if (!pkg.services.isEmpty()) {
9514                    throw new PackageManagerException(
9515                            "Static shared libs cannot declare services");
9516                }
9517
9518                // Static shared libs cannot declare providers
9519                if (!pkg.providers.isEmpty()) {
9520                    throw new PackageManagerException(
9521                            "Static shared libs cannot declare content providers");
9522                }
9523
9524                // Static shared libs cannot declare receivers
9525                if (!pkg.receivers.isEmpty()) {
9526                    throw new PackageManagerException(
9527                            "Static shared libs cannot declare broadcast receivers");
9528                }
9529
9530                // Static shared libs cannot declare permission groups
9531                if (!pkg.permissionGroups.isEmpty()) {
9532                    throw new PackageManagerException(
9533                            "Static shared libs cannot declare permission groups");
9534                }
9535
9536                // Static shared libs cannot declare permissions
9537                if (!pkg.permissions.isEmpty()) {
9538                    throw new PackageManagerException(
9539                            "Static shared libs cannot declare permissions");
9540                }
9541
9542                // Static shared libs cannot declare protected broadcasts
9543                if (pkg.protectedBroadcasts != null) {
9544                    throw new PackageManagerException(
9545                            "Static shared libs cannot declare protected broadcasts");
9546                }
9547
9548                // Static shared libs cannot be overlay targets
9549                if (pkg.mOverlayTarget != null) {
9550                    throw new PackageManagerException(
9551                            "Static shared libs cannot be overlay targets");
9552                }
9553
9554                // The version codes must be ordered as lib versions
9555                int minVersionCode = Integer.MIN_VALUE;
9556                int maxVersionCode = Integer.MAX_VALUE;
9557
9558                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9559                        pkg.staticSharedLibName);
9560                if (versionedLib != null) {
9561                    final int versionCount = versionedLib.size();
9562                    for (int i = 0; i < versionCount; i++) {
9563                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9564                        // TODO: We will change version code to long, so in the new API it is long
9565                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9566                                .getVersionCode();
9567                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9568                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9569                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9570                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9571                        } else {
9572                            minVersionCode = maxVersionCode = libVersionCode;
9573                            break;
9574                        }
9575                    }
9576                }
9577                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9578                    throw new PackageManagerException("Static shared"
9579                            + " lib version codes must be ordered as lib versions");
9580                }
9581            }
9582
9583            // Only privileged apps and updated privileged apps can add child packages.
9584            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9585                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9586                    throw new PackageManagerException("Only privileged apps can add child "
9587                            + "packages. Ignoring package " + pkg.packageName);
9588                }
9589                final int childCount = pkg.childPackages.size();
9590                for (int i = 0; i < childCount; i++) {
9591                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9592                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9593                            childPkg.packageName)) {
9594                        throw new PackageManagerException("Can't override child of "
9595                                + "another disabled app. Ignoring package " + pkg.packageName);
9596                    }
9597                }
9598            }
9599
9600            // If we're only installing presumed-existing packages, require that the
9601            // scanned APK is both already known and at the path previously established
9602            // for it.  Previously unknown packages we pick up normally, but if we have an
9603            // a priori expectation about this package's install presence, enforce it.
9604            // With a singular exception for new system packages. When an OTA contains
9605            // a new system package, we allow the codepath to change from a system location
9606            // to the user-installed location. If we don't allow this change, any newer,
9607            // user-installed version of the application will be ignored.
9608            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9609                if (mExpectingBetter.containsKey(pkg.packageName)) {
9610                    logCriticalInfo(Log.WARN,
9611                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9612                } else {
9613                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9614                    if (known != null) {
9615                        if (DEBUG_PACKAGE_SCANNING) {
9616                            Log.d(TAG, "Examining " + pkg.codePath
9617                                    + " and requiring known paths " + known.codePathString
9618                                    + " & " + known.resourcePathString);
9619                        }
9620                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9621                                || !pkg.applicationInfo.getResourcePath().equals(
9622                                        known.resourcePathString)) {
9623                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9624                                    "Application package " + pkg.packageName
9625                                    + " found at " + pkg.applicationInfo.getCodePath()
9626                                    + " but expected at " + known.codePathString
9627                                    + "; ignoring.");
9628                        }
9629                    }
9630                }
9631            }
9632
9633            // Verify that this new package doesn't have any content providers
9634            // that conflict with existing packages.  Only do this if the
9635            // package isn't already installed, since we don't want to break
9636            // things that are installed.
9637            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9638                final int N = pkg.providers.size();
9639                int i;
9640                for (i=0; i<N; i++) {
9641                    PackageParser.Provider p = pkg.providers.get(i);
9642                    if (p.info.authority != null) {
9643                        String names[] = p.info.authority.split(";");
9644                        for (int j = 0; j < names.length; j++) {
9645                            if (mProvidersByAuthority.containsKey(names[j])) {
9646                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9647                                final String otherPackageName =
9648                                        ((other != null && other.getComponentName() != null) ?
9649                                                other.getComponentName().getPackageName() : "?");
9650                                throw new PackageManagerException(
9651                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9652                                        "Can't install because provider name " + names[j]
9653                                                + " (in package " + pkg.applicationInfo.packageName
9654                                                + ") is already used by " + otherPackageName);
9655                            }
9656                        }
9657                    }
9658                }
9659            }
9660        }
9661    }
9662
9663    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9664            int type, String declaringPackageName, int declaringVersionCode) {
9665        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9666        if (versionedLib == null) {
9667            versionedLib = new SparseArray<>();
9668            mSharedLibraries.put(name, versionedLib);
9669            if (type == SharedLibraryInfo.TYPE_STATIC) {
9670                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9671            }
9672        } else if (versionedLib.indexOfKey(version) >= 0) {
9673            return false;
9674        }
9675        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9676                version, type, declaringPackageName, declaringVersionCode);
9677        versionedLib.put(version, libEntry);
9678        return true;
9679    }
9680
9681    private boolean removeSharedLibraryLPw(String name, int version) {
9682        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9683        if (versionedLib == null) {
9684            return false;
9685        }
9686        final int libIdx = versionedLib.indexOfKey(version);
9687        if (libIdx < 0) {
9688            return false;
9689        }
9690        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9691        versionedLib.remove(version);
9692        if (versionedLib.size() <= 0) {
9693            mSharedLibraries.remove(name);
9694            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9695                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9696                        .getPackageName());
9697            }
9698        }
9699        return true;
9700    }
9701
9702    /**
9703     * Adds a scanned package to the system. When this method is finished, the package will
9704     * be available for query, resolution, etc...
9705     */
9706    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9707            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9708        final String pkgName = pkg.packageName;
9709        if (mCustomResolverComponentName != null &&
9710                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9711            setUpCustomResolverActivity(pkg);
9712        }
9713
9714        if (pkg.packageName.equals("android")) {
9715            synchronized (mPackages) {
9716                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9717                    // Set up information for our fall-back user intent resolution activity.
9718                    mPlatformPackage = pkg;
9719                    pkg.mVersionCode = mSdkVersion;
9720                    mAndroidApplication = pkg.applicationInfo;
9721
9722                    if (!mResolverReplaced) {
9723                        mResolveActivity.applicationInfo = mAndroidApplication;
9724                        mResolveActivity.name = ResolverActivity.class.getName();
9725                        mResolveActivity.packageName = mAndroidApplication.packageName;
9726                        mResolveActivity.processName = "system:ui";
9727                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9728                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9729                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9730                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9731                        mResolveActivity.exported = true;
9732                        mResolveActivity.enabled = true;
9733                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9734                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9735                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9736                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9737                                | ActivityInfo.CONFIG_ORIENTATION
9738                                | ActivityInfo.CONFIG_KEYBOARD
9739                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9740                        mResolveInfo.activityInfo = mResolveActivity;
9741                        mResolveInfo.priority = 0;
9742                        mResolveInfo.preferredOrder = 0;
9743                        mResolveInfo.match = 0;
9744                        mResolveComponentName = new ComponentName(
9745                                mAndroidApplication.packageName, mResolveActivity.name);
9746                    }
9747                }
9748            }
9749        }
9750
9751        ArrayList<PackageParser.Package> clientLibPkgs = null;
9752        // writer
9753        synchronized (mPackages) {
9754            boolean hasStaticSharedLibs = false;
9755
9756            // Any app can add new static shared libraries
9757            if (pkg.staticSharedLibName != null) {
9758                // Static shared libs don't allow renaming as they have synthetic package
9759                // names to allow install of multiple versions, so use name from manifest.
9760                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9761                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9762                        pkg.manifestPackageName, pkg.mVersionCode)) {
9763                    hasStaticSharedLibs = true;
9764                } else {
9765                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9766                                + pkg.staticSharedLibName + " already exists; skipping");
9767                }
9768                // Static shared libs cannot be updated once installed since they
9769                // use synthetic package name which includes the version code, so
9770                // not need to update other packages's shared lib dependencies.
9771            }
9772
9773            if (!hasStaticSharedLibs
9774                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9775                // Only system apps can add new dynamic shared libraries.
9776                if (pkg.libraryNames != null) {
9777                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9778                        String name = pkg.libraryNames.get(i);
9779                        boolean allowed = false;
9780                        if (pkg.isUpdatedSystemApp()) {
9781                            // New library entries can only be added through the
9782                            // system image.  This is important to get rid of a lot
9783                            // of nasty edge cases: for example if we allowed a non-
9784                            // system update of the app to add a library, then uninstalling
9785                            // the update would make the library go away, and assumptions
9786                            // we made such as through app install filtering would now
9787                            // have allowed apps on the device which aren't compatible
9788                            // with it.  Better to just have the restriction here, be
9789                            // conservative, and create many fewer cases that can negatively
9790                            // impact the user experience.
9791                            final PackageSetting sysPs = mSettings
9792                                    .getDisabledSystemPkgLPr(pkg.packageName);
9793                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9794                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9795                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9796                                        allowed = true;
9797                                        break;
9798                                    }
9799                                }
9800                            }
9801                        } else {
9802                            allowed = true;
9803                        }
9804                        if (allowed) {
9805                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9806                                    SharedLibraryInfo.VERSION_UNDEFINED,
9807                                    SharedLibraryInfo.TYPE_DYNAMIC,
9808                                    pkg.packageName, pkg.mVersionCode)) {
9809                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9810                                        + name + " already exists; skipping");
9811                            }
9812                        } else {
9813                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9814                                    + name + " that is not declared on system image; skipping");
9815                        }
9816                    }
9817
9818                    if ((scanFlags & SCAN_BOOTING) == 0) {
9819                        // If we are not booting, we need to update any applications
9820                        // that are clients of our shared library.  If we are booting,
9821                        // this will all be done once the scan is complete.
9822                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9823                    }
9824                }
9825            }
9826        }
9827
9828        if ((scanFlags & SCAN_BOOTING) != 0) {
9829            // No apps can run during boot scan, so they don't need to be frozen
9830        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9831            // Caller asked to not kill app, so it's probably not frozen
9832        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9833            // Caller asked us to ignore frozen check for some reason; they
9834            // probably didn't know the package name
9835        } else {
9836            // We're doing major surgery on this package, so it better be frozen
9837            // right now to keep it from launching
9838            checkPackageFrozen(pkgName);
9839        }
9840
9841        // Also need to kill any apps that are dependent on the library.
9842        if (clientLibPkgs != null) {
9843            for (int i=0; i<clientLibPkgs.size(); i++) {
9844                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9845                killApplication(clientPkg.applicationInfo.packageName,
9846                        clientPkg.applicationInfo.uid, "update lib");
9847            }
9848        }
9849
9850        // writer
9851        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9852
9853        boolean createIdmapFailed = false;
9854        synchronized (mPackages) {
9855            // We don't expect installation to fail beyond this point
9856
9857            if (pkgSetting.pkg != null) {
9858                // Note that |user| might be null during the initial boot scan. If a codePath
9859                // for an app has changed during a boot scan, it's due to an app update that's
9860                // part of the system partition and marker changes must be applied to all users.
9861                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9862                final int[] userIds = resolveUserIds(userId);
9863                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9864            }
9865
9866            // Add the new setting to mSettings
9867            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9868            // Add the new setting to mPackages
9869            mPackages.put(pkg.applicationInfo.packageName, pkg);
9870            // Make sure we don't accidentally delete its data.
9871            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9872            while (iter.hasNext()) {
9873                PackageCleanItem item = iter.next();
9874                if (pkgName.equals(item.packageName)) {
9875                    iter.remove();
9876                }
9877            }
9878
9879            // Add the package's KeySets to the global KeySetManagerService
9880            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9881            ksms.addScannedPackageLPw(pkg);
9882
9883            int N = pkg.providers.size();
9884            StringBuilder r = null;
9885            int i;
9886            for (i=0; i<N; i++) {
9887                PackageParser.Provider p = pkg.providers.get(i);
9888                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9889                        p.info.processName);
9890                mProviders.addProvider(p);
9891                p.syncable = p.info.isSyncable;
9892                if (p.info.authority != null) {
9893                    String names[] = p.info.authority.split(";");
9894                    p.info.authority = null;
9895                    for (int j = 0; j < names.length; j++) {
9896                        if (j == 1 && p.syncable) {
9897                            // We only want the first authority for a provider to possibly be
9898                            // syncable, so if we already added this provider using a different
9899                            // authority clear the syncable flag. We copy the provider before
9900                            // changing it because the mProviders object contains a reference
9901                            // to a provider that we don't want to change.
9902                            // Only do this for the second authority since the resulting provider
9903                            // object can be the same for all future authorities for this provider.
9904                            p = new PackageParser.Provider(p);
9905                            p.syncable = false;
9906                        }
9907                        if (!mProvidersByAuthority.containsKey(names[j])) {
9908                            mProvidersByAuthority.put(names[j], p);
9909                            if (p.info.authority == null) {
9910                                p.info.authority = names[j];
9911                            } else {
9912                                p.info.authority = p.info.authority + ";" + names[j];
9913                            }
9914                            if (DEBUG_PACKAGE_SCANNING) {
9915                                if (chatty)
9916                                    Log.d(TAG, "Registered content provider: " + names[j]
9917                                            + ", className = " + p.info.name + ", isSyncable = "
9918                                            + p.info.isSyncable);
9919                            }
9920                        } else {
9921                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9922                            Slog.w(TAG, "Skipping provider name " + names[j] +
9923                                    " (in package " + pkg.applicationInfo.packageName +
9924                                    "): name already used by "
9925                                    + ((other != null && other.getComponentName() != null)
9926                                            ? other.getComponentName().getPackageName() : "?"));
9927                        }
9928                    }
9929                }
9930                if (chatty) {
9931                    if (r == null) {
9932                        r = new StringBuilder(256);
9933                    } else {
9934                        r.append(' ');
9935                    }
9936                    r.append(p.info.name);
9937                }
9938            }
9939            if (r != null) {
9940                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9941            }
9942
9943            N = pkg.services.size();
9944            r = null;
9945            for (i=0; i<N; i++) {
9946                PackageParser.Service s = pkg.services.get(i);
9947                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9948                        s.info.processName);
9949                mServices.addService(s);
9950                if (chatty) {
9951                    if (r == null) {
9952                        r = new StringBuilder(256);
9953                    } else {
9954                        r.append(' ');
9955                    }
9956                    r.append(s.info.name);
9957                }
9958            }
9959            if (r != null) {
9960                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9961            }
9962
9963            N = pkg.receivers.size();
9964            r = null;
9965            for (i=0; i<N; i++) {
9966                PackageParser.Activity a = pkg.receivers.get(i);
9967                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9968                        a.info.processName);
9969                mReceivers.addActivity(a, "receiver");
9970                if (chatty) {
9971                    if (r == null) {
9972                        r = new StringBuilder(256);
9973                    } else {
9974                        r.append(' ');
9975                    }
9976                    r.append(a.info.name);
9977                }
9978            }
9979            if (r != null) {
9980                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9981            }
9982
9983            N = pkg.activities.size();
9984            r = null;
9985            for (i=0; i<N; i++) {
9986                PackageParser.Activity a = pkg.activities.get(i);
9987                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9988                        a.info.processName);
9989                mActivities.addActivity(a, "activity");
9990                if (chatty) {
9991                    if (r == null) {
9992                        r = new StringBuilder(256);
9993                    } else {
9994                        r.append(' ');
9995                    }
9996                    r.append(a.info.name);
9997                }
9998            }
9999            if (r != null) {
10000                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10001            }
10002
10003            N = pkg.permissionGroups.size();
10004            r = null;
10005            for (i=0; i<N; i++) {
10006                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10007                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10008                final String curPackageName = cur == null ? null : cur.info.packageName;
10009                // Dont allow ephemeral apps to define new permission groups.
10010                if (pkg.applicationInfo.isInstantApp()) {
10011                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10012                            + pg.info.packageName
10013                            + " ignored: ephemeral apps cannot define new permission groups.");
10014                    continue;
10015                }
10016                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10017                if (cur == null || isPackageUpdate) {
10018                    mPermissionGroups.put(pg.info.name, pg);
10019                    if (chatty) {
10020                        if (r == null) {
10021                            r = new StringBuilder(256);
10022                        } else {
10023                            r.append(' ');
10024                        }
10025                        if (isPackageUpdate) {
10026                            r.append("UPD:");
10027                        }
10028                        r.append(pg.info.name);
10029                    }
10030                } else {
10031                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10032                            + pg.info.packageName + " ignored: original from "
10033                            + cur.info.packageName);
10034                    if (chatty) {
10035                        if (r == null) {
10036                            r = new StringBuilder(256);
10037                        } else {
10038                            r.append(' ');
10039                        }
10040                        r.append("DUP:");
10041                        r.append(pg.info.name);
10042                    }
10043                }
10044            }
10045            if (r != null) {
10046                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10047            }
10048
10049            N = pkg.permissions.size();
10050            r = null;
10051            for (i=0; i<N; i++) {
10052                PackageParser.Permission p = pkg.permissions.get(i);
10053
10054                // Dont allow ephemeral apps to define new permissions.
10055                if (pkg.applicationInfo.isInstantApp()) {
10056                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10057                            + p.info.packageName
10058                            + " ignored: ephemeral apps cannot define new permissions.");
10059                    continue;
10060                }
10061
10062                // Assume by default that we did not install this permission into the system.
10063                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10064
10065                // Now that permission groups have a special meaning, we ignore permission
10066                // groups for legacy apps to prevent unexpected behavior. In particular,
10067                // permissions for one app being granted to someone just becase they happen
10068                // to be in a group defined by another app (before this had no implications).
10069                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10070                    p.group = mPermissionGroups.get(p.info.group);
10071                    // Warn for a permission in an unknown group.
10072                    if (p.info.group != null && p.group == null) {
10073                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10074                                + p.info.packageName + " in an unknown group " + p.info.group);
10075                    }
10076                }
10077
10078                ArrayMap<String, BasePermission> permissionMap =
10079                        p.tree ? mSettings.mPermissionTrees
10080                                : mSettings.mPermissions;
10081                BasePermission bp = permissionMap.get(p.info.name);
10082
10083                // Allow system apps to redefine non-system permissions
10084                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10085                    final boolean currentOwnerIsSystem = (bp.perm != null
10086                            && isSystemApp(bp.perm.owner));
10087                    if (isSystemApp(p.owner)) {
10088                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10089                            // It's a built-in permission and no owner, take ownership now
10090                            bp.packageSetting = pkgSetting;
10091                            bp.perm = p;
10092                            bp.uid = pkg.applicationInfo.uid;
10093                            bp.sourcePackage = p.info.packageName;
10094                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10095                        } else if (!currentOwnerIsSystem) {
10096                            String msg = "New decl " + p.owner + " of permission  "
10097                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10098                            reportSettingsProblem(Log.WARN, msg);
10099                            bp = null;
10100                        }
10101                    }
10102                }
10103
10104                if (bp == null) {
10105                    bp = new BasePermission(p.info.name, p.info.packageName,
10106                            BasePermission.TYPE_NORMAL);
10107                    permissionMap.put(p.info.name, bp);
10108                }
10109
10110                if (bp.perm == null) {
10111                    if (bp.sourcePackage == null
10112                            || bp.sourcePackage.equals(p.info.packageName)) {
10113                        BasePermission tree = findPermissionTreeLP(p.info.name);
10114                        if (tree == null
10115                                || tree.sourcePackage.equals(p.info.packageName)) {
10116                            bp.packageSetting = pkgSetting;
10117                            bp.perm = p;
10118                            bp.uid = pkg.applicationInfo.uid;
10119                            bp.sourcePackage = p.info.packageName;
10120                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10121                            if (chatty) {
10122                                if (r == null) {
10123                                    r = new StringBuilder(256);
10124                                } else {
10125                                    r.append(' ');
10126                                }
10127                                r.append(p.info.name);
10128                            }
10129                        } else {
10130                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10131                                    + p.info.packageName + " ignored: base tree "
10132                                    + tree.name + " is from package "
10133                                    + tree.sourcePackage);
10134                        }
10135                    } else {
10136                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10137                                + p.info.packageName + " ignored: original from "
10138                                + bp.sourcePackage);
10139                    }
10140                } else if (chatty) {
10141                    if (r == null) {
10142                        r = new StringBuilder(256);
10143                    } else {
10144                        r.append(' ');
10145                    }
10146                    r.append("DUP:");
10147                    r.append(p.info.name);
10148                }
10149                if (bp.perm == p) {
10150                    bp.protectionLevel = p.info.protectionLevel;
10151                }
10152            }
10153
10154            if (r != null) {
10155                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10156            }
10157
10158            N = pkg.instrumentation.size();
10159            r = null;
10160            for (i=0; i<N; i++) {
10161                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10162                a.info.packageName = pkg.applicationInfo.packageName;
10163                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10164                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10165                a.info.splitNames = pkg.splitNames;
10166                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10167                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10168                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10169                a.info.dataDir = pkg.applicationInfo.dataDir;
10170                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10171                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10172                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10173                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10174                mInstrumentation.put(a.getComponentName(), a);
10175                if (chatty) {
10176                    if (r == null) {
10177                        r = new StringBuilder(256);
10178                    } else {
10179                        r.append(' ');
10180                    }
10181                    r.append(a.info.name);
10182                }
10183            }
10184            if (r != null) {
10185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10186            }
10187
10188            if (pkg.protectedBroadcasts != null) {
10189                N = pkg.protectedBroadcasts.size();
10190                for (i=0; i<N; i++) {
10191                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10192                }
10193            }
10194
10195            // Create idmap files for pairs of (packages, overlay packages).
10196            // Note: "android", ie framework-res.apk, is handled by native layers.
10197            if (pkg.mOverlayTarget != null) {
10198                // This is an overlay package.
10199                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10200                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10201                        mOverlays.put(pkg.mOverlayTarget,
10202                                new ArrayMap<String, PackageParser.Package>());
10203                    }
10204                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10205                    map.put(pkg.packageName, pkg);
10206                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10207                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10208                        createIdmapFailed = true;
10209                    }
10210                }
10211            } else if (mOverlays.containsKey(pkg.packageName) &&
10212                    !pkg.packageName.equals("android")) {
10213                // This is a regular package, with one or more known overlay packages.
10214                createIdmapsForPackageLI(pkg);
10215            }
10216        }
10217
10218        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10219
10220        if (createIdmapFailed) {
10221            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10222                    "scanPackageLI failed to createIdmap");
10223        }
10224    }
10225
10226    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10227            PackageParser.Package update, int[] userIds) {
10228        if (existing.applicationInfo == null || update.applicationInfo == null) {
10229            // This isn't due to an app installation.
10230            return;
10231        }
10232
10233        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10234        final File newCodePath = new File(update.applicationInfo.getCodePath());
10235
10236        // The codePath hasn't changed, so there's nothing for us to do.
10237        if (Objects.equals(oldCodePath, newCodePath)) {
10238            return;
10239        }
10240
10241        File canonicalNewCodePath;
10242        try {
10243            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10244        } catch (IOException e) {
10245            Slog.w(TAG, "Failed to get canonical path.", e);
10246            return;
10247        }
10248
10249        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10250        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10251        // that the last component of the path (i.e, the name) doesn't need canonicalization
10252        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10253        // but may change in the future. Hopefully this function won't exist at that point.
10254        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10255                oldCodePath.getName());
10256
10257        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10258        // with "@".
10259        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10260        if (!oldMarkerPrefix.endsWith("@")) {
10261            oldMarkerPrefix += "@";
10262        }
10263        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10264        if (!newMarkerPrefix.endsWith("@")) {
10265            newMarkerPrefix += "@";
10266        }
10267
10268        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10269        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10270        for (String updatedPath : updatedPaths) {
10271            String updatedPathName = new File(updatedPath).getName();
10272            markerSuffixes.add(updatedPathName.replace('/', '@'));
10273        }
10274
10275        for (int userId : userIds) {
10276            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10277
10278            for (String markerSuffix : markerSuffixes) {
10279                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10280                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10281                if (oldForeignUseMark.exists()) {
10282                    try {
10283                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10284                                newForeignUseMark.getAbsolutePath());
10285                    } catch (ErrnoException e) {
10286                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10287                        oldForeignUseMark.delete();
10288                    }
10289                }
10290            }
10291        }
10292    }
10293
10294    /**
10295     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10296     * is derived purely on the basis of the contents of {@code scanFile} and
10297     * {@code cpuAbiOverride}.
10298     *
10299     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10300     */
10301    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10302                                 String cpuAbiOverride, boolean extractLibs,
10303                                 File appLib32InstallDir)
10304            throws PackageManagerException {
10305        // Give ourselves some initial paths; we'll come back for another
10306        // pass once we've determined ABI below.
10307        setNativeLibraryPaths(pkg, appLib32InstallDir);
10308
10309        // We would never need to extract libs for forward-locked and external packages,
10310        // since the container service will do it for us. We shouldn't attempt to
10311        // extract libs from system app when it was not updated.
10312        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10313                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10314            extractLibs = false;
10315        }
10316
10317        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10318        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10319
10320        NativeLibraryHelper.Handle handle = null;
10321        try {
10322            handle = NativeLibraryHelper.Handle.create(pkg);
10323            // TODO(multiArch): This can be null for apps that didn't go through the
10324            // usual installation process. We can calculate it again, like we
10325            // do during install time.
10326            //
10327            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10328            // unnecessary.
10329            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10330
10331            // Null out the abis so that they can be recalculated.
10332            pkg.applicationInfo.primaryCpuAbi = null;
10333            pkg.applicationInfo.secondaryCpuAbi = null;
10334            if (isMultiArch(pkg.applicationInfo)) {
10335                // Warn if we've set an abiOverride for multi-lib packages..
10336                // By definition, we need to copy both 32 and 64 bit libraries for
10337                // such packages.
10338                if (pkg.cpuAbiOverride != null
10339                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10340                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10341                }
10342
10343                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10344                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10345                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10346                    if (extractLibs) {
10347                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10348                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10349                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10350                                useIsaSpecificSubdirs);
10351                    } else {
10352                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10353                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10354                    }
10355                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10356                }
10357
10358                maybeThrowExceptionForMultiArchCopy(
10359                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10360
10361                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10362                    if (extractLibs) {
10363                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10364                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10365                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10366                                useIsaSpecificSubdirs);
10367                    } else {
10368                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10369                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10370                    }
10371                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10372                }
10373
10374                maybeThrowExceptionForMultiArchCopy(
10375                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10376
10377                if (abi64 >= 0) {
10378                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10379                }
10380
10381                if (abi32 >= 0) {
10382                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10383                    if (abi64 >= 0) {
10384                        if (pkg.use32bitAbi) {
10385                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10386                            pkg.applicationInfo.primaryCpuAbi = abi;
10387                        } else {
10388                            pkg.applicationInfo.secondaryCpuAbi = abi;
10389                        }
10390                    } else {
10391                        pkg.applicationInfo.primaryCpuAbi = abi;
10392                    }
10393                }
10394
10395            } else {
10396                String[] abiList = (cpuAbiOverride != null) ?
10397                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10398
10399                // Enable gross and lame hacks for apps that are built with old
10400                // SDK tools. We must scan their APKs for renderscript bitcode and
10401                // not launch them if it's present. Don't bother checking on devices
10402                // that don't have 64 bit support.
10403                boolean needsRenderScriptOverride = false;
10404                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10405                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10406                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10407                    needsRenderScriptOverride = true;
10408                }
10409
10410                final int copyRet;
10411                if (extractLibs) {
10412                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10413                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10414                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10415                } else {
10416                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10417                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10418                }
10419                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10420
10421                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10422                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10423                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10424                }
10425
10426                if (copyRet >= 0) {
10427                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10428                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10429                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10430                } else if (needsRenderScriptOverride) {
10431                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10432                }
10433            }
10434        } catch (IOException ioe) {
10435            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10436        } finally {
10437            IoUtils.closeQuietly(handle);
10438        }
10439
10440        // Now that we've calculated the ABIs and determined if it's an internal app,
10441        // we will go ahead and populate the nativeLibraryPath.
10442        setNativeLibraryPaths(pkg, appLib32InstallDir);
10443    }
10444
10445    /**
10446     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10447     * i.e, so that all packages can be run inside a single process if required.
10448     *
10449     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10450     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10451     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10452     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10453     * updating a package that belongs to a shared user.
10454     *
10455     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10456     * adds unnecessary complexity.
10457     */
10458    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10459            PackageParser.Package scannedPackage) {
10460        String requiredInstructionSet = null;
10461        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10462            requiredInstructionSet = VMRuntime.getInstructionSet(
10463                     scannedPackage.applicationInfo.primaryCpuAbi);
10464        }
10465
10466        PackageSetting requirer = null;
10467        for (PackageSetting ps : packagesForUser) {
10468            // If packagesForUser contains scannedPackage, we skip it. This will happen
10469            // when scannedPackage is an update of an existing package. Without this check,
10470            // we will never be able to change the ABI of any package belonging to a shared
10471            // user, even if it's compatible with other packages.
10472            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10473                if (ps.primaryCpuAbiString == null) {
10474                    continue;
10475                }
10476
10477                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10478                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10479                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10480                    // this but there's not much we can do.
10481                    String errorMessage = "Instruction set mismatch, "
10482                            + ((requirer == null) ? "[caller]" : requirer)
10483                            + " requires " + requiredInstructionSet + " whereas " + ps
10484                            + " requires " + instructionSet;
10485                    Slog.w(TAG, errorMessage);
10486                }
10487
10488                if (requiredInstructionSet == null) {
10489                    requiredInstructionSet = instructionSet;
10490                    requirer = ps;
10491                }
10492            }
10493        }
10494
10495        if (requiredInstructionSet != null) {
10496            String adjustedAbi;
10497            if (requirer != null) {
10498                // requirer != null implies that either scannedPackage was null or that scannedPackage
10499                // did not require an ABI, in which case we have to adjust scannedPackage to match
10500                // the ABI of the set (which is the same as requirer's ABI)
10501                adjustedAbi = requirer.primaryCpuAbiString;
10502                if (scannedPackage != null) {
10503                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10504                }
10505            } else {
10506                // requirer == null implies that we're updating all ABIs in the set to
10507                // match scannedPackage.
10508                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10509            }
10510
10511            for (PackageSetting ps : packagesForUser) {
10512                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10513                    if (ps.primaryCpuAbiString != null) {
10514                        continue;
10515                    }
10516
10517                    ps.primaryCpuAbiString = adjustedAbi;
10518                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10519                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10520                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10521                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10522                                + " (requirer="
10523                                + (requirer == null ? "null" : requirer.pkg.packageName)
10524                                + ", scannedPackage="
10525                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10526                                + ")");
10527                        try {
10528                            mInstaller.rmdex(ps.codePathString,
10529                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10530                        } catch (InstallerException ignored) {
10531                        }
10532                    }
10533                }
10534            }
10535        }
10536    }
10537
10538    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10539        synchronized (mPackages) {
10540            mResolverReplaced = true;
10541            // Set up information for custom user intent resolution activity.
10542            mResolveActivity.applicationInfo = pkg.applicationInfo;
10543            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10544            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10545            mResolveActivity.processName = pkg.applicationInfo.packageName;
10546            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10547            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10548                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10549            mResolveActivity.theme = 0;
10550            mResolveActivity.exported = true;
10551            mResolveActivity.enabled = true;
10552            mResolveInfo.activityInfo = mResolveActivity;
10553            mResolveInfo.priority = 0;
10554            mResolveInfo.preferredOrder = 0;
10555            mResolveInfo.match = 0;
10556            mResolveComponentName = mCustomResolverComponentName;
10557            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10558                    mResolveComponentName);
10559        }
10560    }
10561
10562    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10563        if (installerComponent == null) {
10564            if (DEBUG_EPHEMERAL) {
10565                Slog.d(TAG, "Clear ephemeral installer activity");
10566            }
10567            mEphemeralInstallerActivity.applicationInfo = null;
10568            return;
10569        }
10570
10571        if (DEBUG_EPHEMERAL) {
10572            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10573        }
10574        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10575        // Set up information for ephemeral installer activity
10576        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10577        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10578        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10579        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10580        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10581        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10582                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10583        mEphemeralInstallerActivity.theme = 0;
10584        mEphemeralInstallerActivity.exported = true;
10585        mEphemeralInstallerActivity.enabled = true;
10586        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10587        mEphemeralInstallerInfo.priority = 0;
10588        mEphemeralInstallerInfo.preferredOrder = 1;
10589        mEphemeralInstallerInfo.isDefault = true;
10590        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10591                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10592    }
10593
10594    private static String calculateBundledApkRoot(final String codePathString) {
10595        final File codePath = new File(codePathString);
10596        final File codeRoot;
10597        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10598            codeRoot = Environment.getRootDirectory();
10599        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10600            codeRoot = Environment.getOemDirectory();
10601        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10602            codeRoot = Environment.getVendorDirectory();
10603        } else {
10604            // Unrecognized code path; take its top real segment as the apk root:
10605            // e.g. /something/app/blah.apk => /something
10606            try {
10607                File f = codePath.getCanonicalFile();
10608                File parent = f.getParentFile();    // non-null because codePath is a file
10609                File tmp;
10610                while ((tmp = parent.getParentFile()) != null) {
10611                    f = parent;
10612                    parent = tmp;
10613                }
10614                codeRoot = f;
10615                Slog.w(TAG, "Unrecognized code path "
10616                        + codePath + " - using " + codeRoot);
10617            } catch (IOException e) {
10618                // Can't canonicalize the code path -- shenanigans?
10619                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10620                return Environment.getRootDirectory().getPath();
10621            }
10622        }
10623        return codeRoot.getPath();
10624    }
10625
10626    /**
10627     * Derive and set the location of native libraries for the given package,
10628     * which varies depending on where and how the package was installed.
10629     */
10630    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10631        final ApplicationInfo info = pkg.applicationInfo;
10632        final String codePath = pkg.codePath;
10633        final File codeFile = new File(codePath);
10634        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10635        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10636
10637        info.nativeLibraryRootDir = null;
10638        info.nativeLibraryRootRequiresIsa = false;
10639        info.nativeLibraryDir = null;
10640        info.secondaryNativeLibraryDir = null;
10641
10642        if (isApkFile(codeFile)) {
10643            // Monolithic install
10644            if (bundledApp) {
10645                // If "/system/lib64/apkname" exists, assume that is the per-package
10646                // native library directory to use; otherwise use "/system/lib/apkname".
10647                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10648                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10649                        getPrimaryInstructionSet(info));
10650
10651                // This is a bundled system app so choose the path based on the ABI.
10652                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10653                // is just the default path.
10654                final String apkName = deriveCodePathName(codePath);
10655                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10656                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10657                        apkName).getAbsolutePath();
10658
10659                if (info.secondaryCpuAbi != null) {
10660                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10661                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10662                            secondaryLibDir, apkName).getAbsolutePath();
10663                }
10664            } else if (asecApp) {
10665                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10666                        .getAbsolutePath();
10667            } else {
10668                final String apkName = deriveCodePathName(codePath);
10669                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10670                        .getAbsolutePath();
10671            }
10672
10673            info.nativeLibraryRootRequiresIsa = false;
10674            info.nativeLibraryDir = info.nativeLibraryRootDir;
10675        } else {
10676            // Cluster install
10677            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10678            info.nativeLibraryRootRequiresIsa = true;
10679
10680            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10681                    getPrimaryInstructionSet(info)).getAbsolutePath();
10682
10683            if (info.secondaryCpuAbi != null) {
10684                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10685                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10686            }
10687        }
10688    }
10689
10690    /**
10691     * Calculate the abis and roots for a bundled app. These can uniquely
10692     * be determined from the contents of the system partition, i.e whether
10693     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10694     * of this information, and instead assume that the system was built
10695     * sensibly.
10696     */
10697    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10698                                           PackageSetting pkgSetting) {
10699        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10700
10701        // If "/system/lib64/apkname" exists, assume that is the per-package
10702        // native library directory to use; otherwise use "/system/lib/apkname".
10703        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10704        setBundledAppAbi(pkg, apkRoot, apkName);
10705        // pkgSetting might be null during rescan following uninstall of updates
10706        // to a bundled app, so accommodate that possibility.  The settings in
10707        // that case will be established later from the parsed package.
10708        //
10709        // If the settings aren't null, sync them up with what we've just derived.
10710        // note that apkRoot isn't stored in the package settings.
10711        if (pkgSetting != null) {
10712            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10713            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10714        }
10715    }
10716
10717    /**
10718     * Deduces the ABI of a bundled app and sets the relevant fields on the
10719     * parsed pkg object.
10720     *
10721     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10722     *        under which system libraries are installed.
10723     * @param apkName the name of the installed package.
10724     */
10725    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10726        final File codeFile = new File(pkg.codePath);
10727
10728        final boolean has64BitLibs;
10729        final boolean has32BitLibs;
10730        if (isApkFile(codeFile)) {
10731            // Monolithic install
10732            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10733            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10734        } else {
10735            // Cluster install
10736            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10737            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10738                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10739                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10740                has64BitLibs = (new File(rootDir, isa)).exists();
10741            } else {
10742                has64BitLibs = false;
10743            }
10744            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10745                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10746                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10747                has32BitLibs = (new File(rootDir, isa)).exists();
10748            } else {
10749                has32BitLibs = false;
10750            }
10751        }
10752
10753        if (has64BitLibs && !has32BitLibs) {
10754            // The package has 64 bit libs, but not 32 bit libs. Its primary
10755            // ABI should be 64 bit. We can safely assume here that the bundled
10756            // native libraries correspond to the most preferred ABI in the list.
10757
10758            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10759            pkg.applicationInfo.secondaryCpuAbi = null;
10760        } else if (has32BitLibs && !has64BitLibs) {
10761            // The package has 32 bit libs but not 64 bit libs. Its primary
10762            // ABI should be 32 bit.
10763
10764            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10765            pkg.applicationInfo.secondaryCpuAbi = null;
10766        } else if (has32BitLibs && has64BitLibs) {
10767            // The application has both 64 and 32 bit bundled libraries. We check
10768            // here that the app declares multiArch support, and warn if it doesn't.
10769            //
10770            // We will be lenient here and record both ABIs. The primary will be the
10771            // ABI that's higher on the list, i.e, a device that's configured to prefer
10772            // 64 bit apps will see a 64 bit primary ABI,
10773
10774            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10775                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10776            }
10777
10778            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10779                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10780                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10781            } else {
10782                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10783                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10784            }
10785        } else {
10786            pkg.applicationInfo.primaryCpuAbi = null;
10787            pkg.applicationInfo.secondaryCpuAbi = null;
10788        }
10789    }
10790
10791    private void killApplication(String pkgName, int appId, String reason) {
10792        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10793    }
10794
10795    private void killApplication(String pkgName, int appId, int userId, String reason) {
10796        // Request the ActivityManager to kill the process(only for existing packages)
10797        // so that we do not end up in a confused state while the user is still using the older
10798        // version of the application while the new one gets installed.
10799        final long token = Binder.clearCallingIdentity();
10800        try {
10801            IActivityManager am = ActivityManager.getService();
10802            if (am != null) {
10803                try {
10804                    am.killApplication(pkgName, appId, userId, reason);
10805                } catch (RemoteException e) {
10806                }
10807            }
10808        } finally {
10809            Binder.restoreCallingIdentity(token);
10810        }
10811    }
10812
10813    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10814        // Remove the parent package setting
10815        PackageSetting ps = (PackageSetting) pkg.mExtras;
10816        if (ps != null) {
10817            removePackageLI(ps, chatty);
10818        }
10819        // Remove the child package setting
10820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10821        for (int i = 0; i < childCount; i++) {
10822            PackageParser.Package childPkg = pkg.childPackages.get(i);
10823            ps = (PackageSetting) childPkg.mExtras;
10824            if (ps != null) {
10825                removePackageLI(ps, chatty);
10826            }
10827        }
10828    }
10829
10830    void removePackageLI(PackageSetting ps, boolean chatty) {
10831        if (DEBUG_INSTALL) {
10832            if (chatty)
10833                Log.d(TAG, "Removing package " + ps.name);
10834        }
10835
10836        // writer
10837        synchronized (mPackages) {
10838            mPackages.remove(ps.name);
10839            final PackageParser.Package pkg = ps.pkg;
10840            if (pkg != null) {
10841                cleanPackageDataStructuresLILPw(pkg, chatty);
10842            }
10843        }
10844    }
10845
10846    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10847        if (DEBUG_INSTALL) {
10848            if (chatty)
10849                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10850        }
10851
10852        // writer
10853        synchronized (mPackages) {
10854            // Remove the parent package
10855            mPackages.remove(pkg.applicationInfo.packageName);
10856            cleanPackageDataStructuresLILPw(pkg, chatty);
10857
10858            // Remove the child packages
10859            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10860            for (int i = 0; i < childCount; i++) {
10861                PackageParser.Package childPkg = pkg.childPackages.get(i);
10862                mPackages.remove(childPkg.applicationInfo.packageName);
10863                cleanPackageDataStructuresLILPw(childPkg, chatty);
10864            }
10865        }
10866    }
10867
10868    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10869        int N = pkg.providers.size();
10870        StringBuilder r = null;
10871        int i;
10872        for (i=0; i<N; i++) {
10873            PackageParser.Provider p = pkg.providers.get(i);
10874            mProviders.removeProvider(p);
10875            if (p.info.authority == null) {
10876
10877                /* There was another ContentProvider with this authority when
10878                 * this app was installed so this authority is null,
10879                 * Ignore it as we don't have to unregister the provider.
10880                 */
10881                continue;
10882            }
10883            String names[] = p.info.authority.split(";");
10884            for (int j = 0; j < names.length; j++) {
10885                if (mProvidersByAuthority.get(names[j]) == p) {
10886                    mProvidersByAuthority.remove(names[j]);
10887                    if (DEBUG_REMOVE) {
10888                        if (chatty)
10889                            Log.d(TAG, "Unregistered content provider: " + names[j]
10890                                    + ", className = " + p.info.name + ", isSyncable = "
10891                                    + p.info.isSyncable);
10892                    }
10893                }
10894            }
10895            if (DEBUG_REMOVE && chatty) {
10896                if (r == null) {
10897                    r = new StringBuilder(256);
10898                } else {
10899                    r.append(' ');
10900                }
10901                r.append(p.info.name);
10902            }
10903        }
10904        if (r != null) {
10905            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10906        }
10907
10908        N = pkg.services.size();
10909        r = null;
10910        for (i=0; i<N; i++) {
10911            PackageParser.Service s = pkg.services.get(i);
10912            mServices.removeService(s);
10913            if (chatty) {
10914                if (r == null) {
10915                    r = new StringBuilder(256);
10916                } else {
10917                    r.append(' ');
10918                }
10919                r.append(s.info.name);
10920            }
10921        }
10922        if (r != null) {
10923            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10924        }
10925
10926        N = pkg.receivers.size();
10927        r = null;
10928        for (i=0; i<N; i++) {
10929            PackageParser.Activity a = pkg.receivers.get(i);
10930            mReceivers.removeActivity(a, "receiver");
10931            if (DEBUG_REMOVE && chatty) {
10932                if (r == null) {
10933                    r = new StringBuilder(256);
10934                } else {
10935                    r.append(' ');
10936                }
10937                r.append(a.info.name);
10938            }
10939        }
10940        if (r != null) {
10941            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10942        }
10943
10944        N = pkg.activities.size();
10945        r = null;
10946        for (i=0; i<N; i++) {
10947            PackageParser.Activity a = pkg.activities.get(i);
10948            mActivities.removeActivity(a, "activity");
10949            if (DEBUG_REMOVE && chatty) {
10950                if (r == null) {
10951                    r = new StringBuilder(256);
10952                } else {
10953                    r.append(' ');
10954                }
10955                r.append(a.info.name);
10956            }
10957        }
10958        if (r != null) {
10959            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10960        }
10961
10962        N = pkg.permissions.size();
10963        r = null;
10964        for (i=0; i<N; i++) {
10965            PackageParser.Permission p = pkg.permissions.get(i);
10966            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10967            if (bp == null) {
10968                bp = mSettings.mPermissionTrees.get(p.info.name);
10969            }
10970            if (bp != null && bp.perm == p) {
10971                bp.perm = null;
10972                if (DEBUG_REMOVE && chatty) {
10973                    if (r == null) {
10974                        r = new StringBuilder(256);
10975                    } else {
10976                        r.append(' ');
10977                    }
10978                    r.append(p.info.name);
10979                }
10980            }
10981            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10982                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10983                if (appOpPkgs != null) {
10984                    appOpPkgs.remove(pkg.packageName);
10985                }
10986            }
10987        }
10988        if (r != null) {
10989            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10990        }
10991
10992        N = pkg.requestedPermissions.size();
10993        r = null;
10994        for (i=0; i<N; i++) {
10995            String perm = pkg.requestedPermissions.get(i);
10996            BasePermission bp = mSettings.mPermissions.get(perm);
10997            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10998                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10999                if (appOpPkgs != null) {
11000                    appOpPkgs.remove(pkg.packageName);
11001                    if (appOpPkgs.isEmpty()) {
11002                        mAppOpPermissionPackages.remove(perm);
11003                    }
11004                }
11005            }
11006        }
11007        if (r != null) {
11008            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11009        }
11010
11011        N = pkg.instrumentation.size();
11012        r = null;
11013        for (i=0; i<N; i++) {
11014            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11015            mInstrumentation.remove(a.getComponentName());
11016            if (DEBUG_REMOVE && chatty) {
11017                if (r == null) {
11018                    r = new StringBuilder(256);
11019                } else {
11020                    r.append(' ');
11021                }
11022                r.append(a.info.name);
11023            }
11024        }
11025        if (r != null) {
11026            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11027        }
11028
11029        r = null;
11030        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11031            // Only system apps can hold shared libraries.
11032            if (pkg.libraryNames != null) {
11033                for (i = 0; i < pkg.libraryNames.size(); i++) {
11034                    String name = pkg.libraryNames.get(i);
11035                    if (removeSharedLibraryLPw(name, 0)) {
11036                        if (DEBUG_REMOVE && chatty) {
11037                            if (r == null) {
11038                                r = new StringBuilder(256);
11039                            } else {
11040                                r.append(' ');
11041                            }
11042                            r.append(name);
11043                        }
11044                    }
11045                }
11046            }
11047        }
11048
11049        r = null;
11050
11051        // Any package can hold static shared libraries.
11052        if (pkg.staticSharedLibName != null) {
11053            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11054                if (DEBUG_REMOVE && chatty) {
11055                    if (r == null) {
11056                        r = new StringBuilder(256);
11057                    } else {
11058                        r.append(' ');
11059                    }
11060                    r.append(pkg.staticSharedLibName);
11061                }
11062            }
11063        }
11064
11065        if (r != null) {
11066            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11067        }
11068    }
11069
11070    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11071        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11072            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11073                return true;
11074            }
11075        }
11076        return false;
11077    }
11078
11079    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11080    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11081    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11082
11083    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11084        // Update the parent permissions
11085        updatePermissionsLPw(pkg.packageName, pkg, flags);
11086        // Update the child permissions
11087        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11088        for (int i = 0; i < childCount; i++) {
11089            PackageParser.Package childPkg = pkg.childPackages.get(i);
11090            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11091        }
11092    }
11093
11094    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11095            int flags) {
11096        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11097        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11098    }
11099
11100    private void updatePermissionsLPw(String changingPkg,
11101            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11102        // Make sure there are no dangling permission trees.
11103        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11104        while (it.hasNext()) {
11105            final BasePermission bp = it.next();
11106            if (bp.packageSetting == null) {
11107                // We may not yet have parsed the package, so just see if
11108                // we still know about its settings.
11109                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11110            }
11111            if (bp.packageSetting == null) {
11112                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11113                        + " from package " + bp.sourcePackage);
11114                it.remove();
11115            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11116                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11117                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11118                            + " from package " + bp.sourcePackage);
11119                    flags |= UPDATE_PERMISSIONS_ALL;
11120                    it.remove();
11121                }
11122            }
11123        }
11124
11125        // Make sure all dynamic permissions have been assigned to a package,
11126        // and make sure there are no dangling permissions.
11127        it = mSettings.mPermissions.values().iterator();
11128        while (it.hasNext()) {
11129            final BasePermission bp = it.next();
11130            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11131                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11132                        + bp.name + " pkg=" + bp.sourcePackage
11133                        + " info=" + bp.pendingInfo);
11134                if (bp.packageSetting == null && bp.pendingInfo != null) {
11135                    final BasePermission tree = findPermissionTreeLP(bp.name);
11136                    if (tree != null && tree.perm != null) {
11137                        bp.packageSetting = tree.packageSetting;
11138                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11139                                new PermissionInfo(bp.pendingInfo));
11140                        bp.perm.info.packageName = tree.perm.info.packageName;
11141                        bp.perm.info.name = bp.name;
11142                        bp.uid = tree.uid;
11143                    }
11144                }
11145            }
11146            if (bp.packageSetting == null) {
11147                // We may not yet have parsed the package, so just see if
11148                // we still know about its settings.
11149                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11150            }
11151            if (bp.packageSetting == null) {
11152                Slog.w(TAG, "Removing dangling permission: " + bp.name
11153                        + " from package " + bp.sourcePackage);
11154                it.remove();
11155            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11156                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11157                    Slog.i(TAG, "Removing old permission: " + bp.name
11158                            + " from package " + bp.sourcePackage);
11159                    flags |= UPDATE_PERMISSIONS_ALL;
11160                    it.remove();
11161                }
11162            }
11163        }
11164
11165        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11166        // Now update the permissions for all packages, in particular
11167        // replace the granted permissions of the system packages.
11168        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11169            for (PackageParser.Package pkg : mPackages.values()) {
11170                if (pkg != pkgInfo) {
11171                    // Only replace for packages on requested volume
11172                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11173                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11174                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11175                    grantPermissionsLPw(pkg, replace, changingPkg);
11176                }
11177            }
11178        }
11179
11180        if (pkgInfo != null) {
11181            // Only replace for packages on requested volume
11182            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11183            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11184                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11185            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11186        }
11187        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11188    }
11189
11190    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11191            String packageOfInterest) {
11192        // IMPORTANT: There are two types of permissions: install and runtime.
11193        // Install time permissions are granted when the app is installed to
11194        // all device users and users added in the future. Runtime permissions
11195        // are granted at runtime explicitly to specific users. Normal and signature
11196        // protected permissions are install time permissions. Dangerous permissions
11197        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11198        // otherwise they are runtime permissions. This function does not manage
11199        // runtime permissions except for the case an app targeting Lollipop MR1
11200        // being upgraded to target a newer SDK, in which case dangerous permissions
11201        // are transformed from install time to runtime ones.
11202
11203        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11204        if (ps == null) {
11205            return;
11206        }
11207
11208        PermissionsState permissionsState = ps.getPermissionsState();
11209        PermissionsState origPermissions = permissionsState;
11210
11211        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11212
11213        boolean runtimePermissionsRevoked = false;
11214        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11215
11216        boolean changedInstallPermission = false;
11217
11218        if (replace) {
11219            ps.installPermissionsFixed = false;
11220            if (!ps.isSharedUser()) {
11221                origPermissions = new PermissionsState(permissionsState);
11222                permissionsState.reset();
11223            } else {
11224                // We need to know only about runtime permission changes since the
11225                // calling code always writes the install permissions state but
11226                // the runtime ones are written only if changed. The only cases of
11227                // changed runtime permissions here are promotion of an install to
11228                // runtime and revocation of a runtime from a shared user.
11229                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11230                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11231                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11232                    runtimePermissionsRevoked = true;
11233                }
11234            }
11235        }
11236
11237        permissionsState.setGlobalGids(mGlobalGids);
11238
11239        final int N = pkg.requestedPermissions.size();
11240        for (int i=0; i<N; i++) {
11241            final String name = pkg.requestedPermissions.get(i);
11242            final BasePermission bp = mSettings.mPermissions.get(name);
11243
11244            if (DEBUG_INSTALL) {
11245                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11246            }
11247
11248            if (bp == null || bp.packageSetting == null) {
11249                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11250                    Slog.w(TAG, "Unknown permission " + name
11251                            + " in package " + pkg.packageName);
11252                }
11253                continue;
11254            }
11255
11256
11257            // Limit ephemeral apps to ephemeral allowed permissions.
11258            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11259                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11260                        + pkg.packageName);
11261                continue;
11262            }
11263
11264            final String perm = bp.name;
11265            boolean allowedSig = false;
11266            int grant = GRANT_DENIED;
11267
11268            // Keep track of app op permissions.
11269            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11270                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11271                if (pkgs == null) {
11272                    pkgs = new ArraySet<>();
11273                    mAppOpPermissionPackages.put(bp.name, pkgs);
11274                }
11275                pkgs.add(pkg.packageName);
11276            }
11277
11278            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11279            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11280                    >= Build.VERSION_CODES.M;
11281            switch (level) {
11282                case PermissionInfo.PROTECTION_NORMAL: {
11283                    // For all apps normal permissions are install time ones.
11284                    grant = GRANT_INSTALL;
11285                } break;
11286
11287                case PermissionInfo.PROTECTION_DANGEROUS: {
11288                    // If a permission review is required for legacy apps we represent
11289                    // their permissions as always granted runtime ones since we need
11290                    // to keep the review required permission flag per user while an
11291                    // install permission's state is shared across all users.
11292                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11293                        // For legacy apps dangerous permissions are install time ones.
11294                        grant = GRANT_INSTALL;
11295                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11296                        // For legacy apps that became modern, install becomes runtime.
11297                        grant = GRANT_UPGRADE;
11298                    } else if (mPromoteSystemApps
11299                            && isSystemApp(ps)
11300                            && mExistingSystemPackages.contains(ps.name)) {
11301                        // For legacy system apps, install becomes runtime.
11302                        // We cannot check hasInstallPermission() for system apps since those
11303                        // permissions were granted implicitly and not persisted pre-M.
11304                        grant = GRANT_UPGRADE;
11305                    } else {
11306                        // For modern apps keep runtime permissions unchanged.
11307                        grant = GRANT_RUNTIME;
11308                    }
11309                } break;
11310
11311                case PermissionInfo.PROTECTION_SIGNATURE: {
11312                    // For all apps signature permissions are install time ones.
11313                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11314                    if (allowedSig) {
11315                        grant = GRANT_INSTALL;
11316                    }
11317                } break;
11318            }
11319
11320            if (DEBUG_INSTALL) {
11321                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11322            }
11323
11324            if (grant != GRANT_DENIED) {
11325                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11326                    // If this is an existing, non-system package, then
11327                    // we can't add any new permissions to it.
11328                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11329                        // Except...  if this is a permission that was added
11330                        // to the platform (note: need to only do this when
11331                        // updating the platform).
11332                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11333                            grant = GRANT_DENIED;
11334                        }
11335                    }
11336                }
11337
11338                switch (grant) {
11339                    case GRANT_INSTALL: {
11340                        // Revoke this as runtime permission to handle the case of
11341                        // a runtime permission being downgraded to an install one.
11342                        // Also in permission review mode we keep dangerous permissions
11343                        // for legacy apps
11344                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11345                            if (origPermissions.getRuntimePermissionState(
11346                                    bp.name, userId) != null) {
11347                                // Revoke the runtime permission and clear the flags.
11348                                origPermissions.revokeRuntimePermission(bp, userId);
11349                                origPermissions.updatePermissionFlags(bp, userId,
11350                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11351                                // If we revoked a permission permission, we have to write.
11352                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11353                                        changedRuntimePermissionUserIds, userId);
11354                            }
11355                        }
11356                        // Grant an install permission.
11357                        if (permissionsState.grantInstallPermission(bp) !=
11358                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11359                            changedInstallPermission = true;
11360                        }
11361                    } break;
11362
11363                    case GRANT_RUNTIME: {
11364                        // Grant previously granted runtime permissions.
11365                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11366                            PermissionState permissionState = origPermissions
11367                                    .getRuntimePermissionState(bp.name, userId);
11368                            int flags = permissionState != null
11369                                    ? permissionState.getFlags() : 0;
11370                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11371                                // Don't propagate the permission in a permission review mode if
11372                                // the former was revoked, i.e. marked to not propagate on upgrade.
11373                                // Note that in a permission review mode install permissions are
11374                                // represented as constantly granted runtime ones since we need to
11375                                // keep a per user state associated with the permission. Also the
11376                                // revoke on upgrade flag is no longer applicable and is reset.
11377                                final boolean revokeOnUpgrade = (flags & PackageManager
11378                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11379                                if (revokeOnUpgrade) {
11380                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11381                                    // Since we changed the flags, we have to write.
11382                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11383                                            changedRuntimePermissionUserIds, userId);
11384                                }
11385                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11386                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11387                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11388                                        // If we cannot put the permission as it was,
11389                                        // we have to write.
11390                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11391                                                changedRuntimePermissionUserIds, userId);
11392                                    }
11393                                }
11394
11395                                // If the app supports runtime permissions no need for a review.
11396                                if (mPermissionReviewRequired
11397                                        && appSupportsRuntimePermissions
11398                                        && (flags & PackageManager
11399                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11400                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11401                                    // Since we changed the flags, we have to write.
11402                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11403                                            changedRuntimePermissionUserIds, userId);
11404                                }
11405                            } else if (mPermissionReviewRequired
11406                                    && !appSupportsRuntimePermissions) {
11407                                // For legacy apps that need a permission review, every new
11408                                // runtime permission is granted but it is pending a review.
11409                                // We also need to review only platform defined runtime
11410                                // permissions as these are the only ones the platform knows
11411                                // how to disable the API to simulate revocation as legacy
11412                                // apps don't expect to run with revoked permissions.
11413                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11414                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11415                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11416                                        // We changed the flags, hence have to write.
11417                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11418                                                changedRuntimePermissionUserIds, userId);
11419                                    }
11420                                }
11421                                if (permissionsState.grantRuntimePermission(bp, userId)
11422                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11423                                    // We changed the permission, hence have to write.
11424                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11425                                            changedRuntimePermissionUserIds, userId);
11426                                }
11427                            }
11428                            // Propagate the permission flags.
11429                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11430                        }
11431                    } break;
11432
11433                    case GRANT_UPGRADE: {
11434                        // Grant runtime permissions for a previously held install permission.
11435                        PermissionState permissionState = origPermissions
11436                                .getInstallPermissionState(bp.name);
11437                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11438
11439                        if (origPermissions.revokeInstallPermission(bp)
11440                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11441                            // We will be transferring the permission flags, so clear them.
11442                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11443                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11444                            changedInstallPermission = true;
11445                        }
11446
11447                        // If the permission is not to be promoted to runtime we ignore it and
11448                        // also its other flags as they are not applicable to install permissions.
11449                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11450                            for (int userId : currentUserIds) {
11451                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11452                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11453                                    // Transfer the permission flags.
11454                                    permissionsState.updatePermissionFlags(bp, userId,
11455                                            flags, flags);
11456                                    // If we granted the permission, we have to write.
11457                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11458                                            changedRuntimePermissionUserIds, userId);
11459                                }
11460                            }
11461                        }
11462                    } break;
11463
11464                    default: {
11465                        if (packageOfInterest == null
11466                                || packageOfInterest.equals(pkg.packageName)) {
11467                            Slog.w(TAG, "Not granting permission " + perm
11468                                    + " to package " + pkg.packageName
11469                                    + " because it was previously installed without");
11470                        }
11471                    } break;
11472                }
11473            } else {
11474                if (permissionsState.revokeInstallPermission(bp) !=
11475                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11476                    // Also drop the permission flags.
11477                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11478                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11479                    changedInstallPermission = true;
11480                    Slog.i(TAG, "Un-granting permission " + perm
11481                            + " from package " + pkg.packageName
11482                            + " (protectionLevel=" + bp.protectionLevel
11483                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11484                            + ")");
11485                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11486                    // Don't print warning for app op permissions, since it is fine for them
11487                    // not to be granted, there is a UI for the user to decide.
11488                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11489                        Slog.w(TAG, "Not granting permission " + perm
11490                                + " to package " + pkg.packageName
11491                                + " (protectionLevel=" + bp.protectionLevel
11492                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11493                                + ")");
11494                    }
11495                }
11496            }
11497        }
11498
11499        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11500                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11501            // This is the first that we have heard about this package, so the
11502            // permissions we have now selected are fixed until explicitly
11503            // changed.
11504            ps.installPermissionsFixed = true;
11505        }
11506
11507        // Persist the runtime permissions state for users with changes. If permissions
11508        // were revoked because no app in the shared user declares them we have to
11509        // write synchronously to avoid losing runtime permissions state.
11510        for (int userId : changedRuntimePermissionUserIds) {
11511            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11512        }
11513    }
11514
11515    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11516        boolean allowed = false;
11517        final int NP = PackageParser.NEW_PERMISSIONS.length;
11518        for (int ip=0; ip<NP; ip++) {
11519            final PackageParser.NewPermissionInfo npi
11520                    = PackageParser.NEW_PERMISSIONS[ip];
11521            if (npi.name.equals(perm)
11522                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11523                allowed = true;
11524                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11525                        + pkg.packageName);
11526                break;
11527            }
11528        }
11529        return allowed;
11530    }
11531
11532    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11533            BasePermission bp, PermissionsState origPermissions) {
11534        boolean privilegedPermission = (bp.protectionLevel
11535                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11536        boolean privappPermissionsDisable =
11537                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11538        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11539        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11540        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11541                && !platformPackage && platformPermission) {
11542            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11543                    .getPrivAppPermissions(pkg.packageName);
11544            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11545            if (!whitelisted) {
11546                Slog.w(TAG, "Privileged permission " + perm + " for package "
11547                        + pkg.packageName + " - not in privapp-permissions whitelist");
11548                if (!mSystemReady) {
11549                    if (mPrivappPermissionsViolations == null) {
11550                        mPrivappPermissionsViolations = new ArraySet<>();
11551                    }
11552                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11553                }
11554                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11555                    return false;
11556                }
11557            }
11558        }
11559        boolean allowed = (compareSignatures(
11560                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11561                        == PackageManager.SIGNATURE_MATCH)
11562                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11563                        == PackageManager.SIGNATURE_MATCH);
11564        if (!allowed && privilegedPermission) {
11565            if (isSystemApp(pkg)) {
11566                // For updated system applications, a system permission
11567                // is granted only if it had been defined by the original application.
11568                if (pkg.isUpdatedSystemApp()) {
11569                    final PackageSetting sysPs = mSettings
11570                            .getDisabledSystemPkgLPr(pkg.packageName);
11571                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11572                        // If the original was granted this permission, we take
11573                        // that grant decision as read and propagate it to the
11574                        // update.
11575                        if (sysPs.isPrivileged()) {
11576                            allowed = true;
11577                        }
11578                    } else {
11579                        // The system apk may have been updated with an older
11580                        // version of the one on the data partition, but which
11581                        // granted a new system permission that it didn't have
11582                        // before.  In this case we do want to allow the app to
11583                        // now get the new permission if the ancestral apk is
11584                        // privileged to get it.
11585                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11586                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11587                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11588                                    allowed = true;
11589                                    break;
11590                                }
11591                            }
11592                        }
11593                        // Also if a privileged parent package on the system image or any of
11594                        // its children requested a privileged permission, the updated child
11595                        // packages can also get the permission.
11596                        if (pkg.parentPackage != null) {
11597                            final PackageSetting disabledSysParentPs = mSettings
11598                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11599                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11600                                    && disabledSysParentPs.isPrivileged()) {
11601                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11602                                    allowed = true;
11603                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11604                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11605                                    for (int i = 0; i < count; i++) {
11606                                        PackageParser.Package disabledSysChildPkg =
11607                                                disabledSysParentPs.pkg.childPackages.get(i);
11608                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11609                                                perm)) {
11610                                            allowed = true;
11611                                            break;
11612                                        }
11613                                    }
11614                                }
11615                            }
11616                        }
11617                    }
11618                } else {
11619                    allowed = isPrivilegedApp(pkg);
11620                }
11621            }
11622        }
11623        if (!allowed) {
11624            if (!allowed && (bp.protectionLevel
11625                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11626                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11627                // If this was a previously normal/dangerous permission that got moved
11628                // to a system permission as part of the runtime permission redesign, then
11629                // we still want to blindly grant it to old apps.
11630                allowed = true;
11631            }
11632            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11633                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11634                // If this permission is to be granted to the system installer and
11635                // this app is an installer, then it gets the permission.
11636                allowed = true;
11637            }
11638            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11639                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11640                // If this permission is to be granted to the system verifier and
11641                // this app is a verifier, then it gets the permission.
11642                allowed = true;
11643            }
11644            if (!allowed && (bp.protectionLevel
11645                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11646                    && isSystemApp(pkg)) {
11647                // Any pre-installed system app is allowed to get this permission.
11648                allowed = true;
11649            }
11650            if (!allowed && (bp.protectionLevel
11651                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11652                // For development permissions, a development permission
11653                // is granted only if it was already granted.
11654                allowed = origPermissions.hasInstallPermission(perm);
11655            }
11656            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11657                    && pkg.packageName.equals(mSetupWizardPackage)) {
11658                // If this permission is to be granted to the system setup wizard and
11659                // this app is a setup wizard, then it gets the permission.
11660                allowed = true;
11661            }
11662        }
11663        return allowed;
11664    }
11665
11666    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11667        final int permCount = pkg.requestedPermissions.size();
11668        for (int j = 0; j < permCount; j++) {
11669            String requestedPermission = pkg.requestedPermissions.get(j);
11670            if (permission.equals(requestedPermission)) {
11671                return true;
11672            }
11673        }
11674        return false;
11675    }
11676
11677    final class ActivityIntentResolver
11678            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11679        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11680                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11681            if (!sUserManager.exists(userId)) return null;
11682            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11683                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11684                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11685            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11686                    isEphemeral, userId);
11687        }
11688
11689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11690                int userId) {
11691            if (!sUserManager.exists(userId)) return null;
11692            mFlags = flags;
11693            return super.queryIntent(intent, resolvedType,
11694                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11695                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11696                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11697        }
11698
11699        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11700                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11701            if (!sUserManager.exists(userId)) return null;
11702            if (packageActivities == null) {
11703                return null;
11704            }
11705            mFlags = flags;
11706            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11707            final boolean vislbleToEphemeral =
11708                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11709            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11710            final int N = packageActivities.size();
11711            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11712                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11713
11714            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11715            for (int i = 0; i < N; ++i) {
11716                intentFilters = packageActivities.get(i).intents;
11717                if (intentFilters != null && intentFilters.size() > 0) {
11718                    PackageParser.ActivityIntentInfo[] array =
11719                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11720                    intentFilters.toArray(array);
11721                    listCut.add(array);
11722                }
11723            }
11724            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11725                    vislbleToEphemeral, isEphemeral, listCut, userId);
11726        }
11727
11728        /**
11729         * Finds a privileged activity that matches the specified activity names.
11730         */
11731        private PackageParser.Activity findMatchingActivity(
11732                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11733            for (PackageParser.Activity sysActivity : activityList) {
11734                if (sysActivity.info.name.equals(activityInfo.name)) {
11735                    return sysActivity;
11736                }
11737                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11738                    return sysActivity;
11739                }
11740                if (sysActivity.info.targetActivity != null) {
11741                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11742                        return sysActivity;
11743                    }
11744                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11745                        return sysActivity;
11746                    }
11747                }
11748            }
11749            return null;
11750        }
11751
11752        public class IterGenerator<E> {
11753            public Iterator<E> generate(ActivityIntentInfo info) {
11754                return null;
11755            }
11756        }
11757
11758        public class ActionIterGenerator extends IterGenerator<String> {
11759            @Override
11760            public Iterator<String> generate(ActivityIntentInfo info) {
11761                return info.actionsIterator();
11762            }
11763        }
11764
11765        public class CategoriesIterGenerator extends IterGenerator<String> {
11766            @Override
11767            public Iterator<String> generate(ActivityIntentInfo info) {
11768                return info.categoriesIterator();
11769            }
11770        }
11771
11772        public class SchemesIterGenerator extends IterGenerator<String> {
11773            @Override
11774            public Iterator<String> generate(ActivityIntentInfo info) {
11775                return info.schemesIterator();
11776            }
11777        }
11778
11779        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11780            @Override
11781            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11782                return info.authoritiesIterator();
11783            }
11784        }
11785
11786        /**
11787         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11788         * MODIFIED. Do not pass in a list that should not be changed.
11789         */
11790        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11791                IterGenerator<T> generator, Iterator<T> searchIterator) {
11792            // loop through the set of actions; every one must be found in the intent filter
11793            while (searchIterator.hasNext()) {
11794                // we must have at least one filter in the list to consider a match
11795                if (intentList.size() == 0) {
11796                    break;
11797                }
11798
11799                final T searchAction = searchIterator.next();
11800
11801                // loop through the set of intent filters
11802                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11803                while (intentIter.hasNext()) {
11804                    final ActivityIntentInfo intentInfo = intentIter.next();
11805                    boolean selectionFound = false;
11806
11807                    // loop through the intent filter's selection criteria; at least one
11808                    // of them must match the searched criteria
11809                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11810                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11811                        final T intentSelection = intentSelectionIter.next();
11812                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11813                            selectionFound = true;
11814                            break;
11815                        }
11816                    }
11817
11818                    // the selection criteria wasn't found in this filter's set; this filter
11819                    // is not a potential match
11820                    if (!selectionFound) {
11821                        intentIter.remove();
11822                    }
11823                }
11824            }
11825        }
11826
11827        private boolean isProtectedAction(ActivityIntentInfo filter) {
11828            final Iterator<String> actionsIter = filter.actionsIterator();
11829            while (actionsIter != null && actionsIter.hasNext()) {
11830                final String filterAction = actionsIter.next();
11831                if (PROTECTED_ACTIONS.contains(filterAction)) {
11832                    return true;
11833                }
11834            }
11835            return false;
11836        }
11837
11838        /**
11839         * Adjusts the priority of the given intent filter according to policy.
11840         * <p>
11841         * <ul>
11842         * <li>The priority for non privileged applications is capped to '0'</li>
11843         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11844         * <li>The priority for unbundled updates to privileged applications is capped to the
11845         *      priority defined on the system partition</li>
11846         * </ul>
11847         * <p>
11848         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11849         * allowed to obtain any priority on any action.
11850         */
11851        private void adjustPriority(
11852                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11853            // nothing to do; priority is fine as-is
11854            if (intent.getPriority() <= 0) {
11855                return;
11856            }
11857
11858            final ActivityInfo activityInfo = intent.activity.info;
11859            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11860
11861            final boolean privilegedApp =
11862                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11863            if (!privilegedApp) {
11864                // non-privileged applications can never define a priority >0
11865                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11866                        + " package: " + applicationInfo.packageName
11867                        + " activity: " + intent.activity.className
11868                        + " origPrio: " + intent.getPriority());
11869                intent.setPriority(0);
11870                return;
11871            }
11872
11873            if (systemActivities == null) {
11874                // the system package is not disabled; we're parsing the system partition
11875                if (isProtectedAction(intent)) {
11876                    if (mDeferProtectedFilters) {
11877                        // We can't deal with these just yet. No component should ever obtain a
11878                        // >0 priority for a protected actions, with ONE exception -- the setup
11879                        // wizard. The setup wizard, however, cannot be known until we're able to
11880                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11881                        // until all intent filters have been processed. Chicken, meet egg.
11882                        // Let the filter temporarily have a high priority and rectify the
11883                        // priorities after all system packages have been scanned.
11884                        mProtectedFilters.add(intent);
11885                        if (DEBUG_FILTERS) {
11886                            Slog.i(TAG, "Protected action; save for later;"
11887                                    + " package: " + applicationInfo.packageName
11888                                    + " activity: " + intent.activity.className
11889                                    + " origPrio: " + intent.getPriority());
11890                        }
11891                        return;
11892                    } else {
11893                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11894                            Slog.i(TAG, "No setup wizard;"
11895                                + " All protected intents capped to priority 0");
11896                        }
11897                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11898                            if (DEBUG_FILTERS) {
11899                                Slog.i(TAG, "Found setup wizard;"
11900                                    + " allow priority " + intent.getPriority() + ";"
11901                                    + " package: " + intent.activity.info.packageName
11902                                    + " activity: " + intent.activity.className
11903                                    + " priority: " + intent.getPriority());
11904                            }
11905                            // setup wizard gets whatever it wants
11906                            return;
11907                        }
11908                        Slog.w(TAG, "Protected action; cap priority to 0;"
11909                                + " package: " + intent.activity.info.packageName
11910                                + " activity: " + intent.activity.className
11911                                + " origPrio: " + intent.getPriority());
11912                        intent.setPriority(0);
11913                        return;
11914                    }
11915                }
11916                // privileged apps on the system image get whatever priority they request
11917                return;
11918            }
11919
11920            // privileged app unbundled update ... try to find the same activity
11921            final PackageParser.Activity foundActivity =
11922                    findMatchingActivity(systemActivities, activityInfo);
11923            if (foundActivity == null) {
11924                // this is a new activity; it cannot obtain >0 priority
11925                if (DEBUG_FILTERS) {
11926                    Slog.i(TAG, "New activity; cap priority to 0;"
11927                            + " package: " + applicationInfo.packageName
11928                            + " activity: " + intent.activity.className
11929                            + " origPrio: " + intent.getPriority());
11930                }
11931                intent.setPriority(0);
11932                return;
11933            }
11934
11935            // found activity, now check for filter equivalence
11936
11937            // a shallow copy is enough; we modify the list, not its contents
11938            final List<ActivityIntentInfo> intentListCopy =
11939                    new ArrayList<>(foundActivity.intents);
11940            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11941
11942            // find matching action subsets
11943            final Iterator<String> actionsIterator = intent.actionsIterator();
11944            if (actionsIterator != null) {
11945                getIntentListSubset(
11946                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11947                if (intentListCopy.size() == 0) {
11948                    // no more intents to match; we're not equivalent
11949                    if (DEBUG_FILTERS) {
11950                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11951                                + " package: " + applicationInfo.packageName
11952                                + " activity: " + intent.activity.className
11953                                + " origPrio: " + intent.getPriority());
11954                    }
11955                    intent.setPriority(0);
11956                    return;
11957                }
11958            }
11959
11960            // find matching category subsets
11961            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11962            if (categoriesIterator != null) {
11963                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11964                        categoriesIterator);
11965                if (intentListCopy.size() == 0) {
11966                    // no more intents to match; we're not equivalent
11967                    if (DEBUG_FILTERS) {
11968                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11969                                + " package: " + applicationInfo.packageName
11970                                + " activity: " + intent.activity.className
11971                                + " origPrio: " + intent.getPriority());
11972                    }
11973                    intent.setPriority(0);
11974                    return;
11975                }
11976            }
11977
11978            // find matching schemes subsets
11979            final Iterator<String> schemesIterator = intent.schemesIterator();
11980            if (schemesIterator != null) {
11981                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11982                        schemesIterator);
11983                if (intentListCopy.size() == 0) {
11984                    // no more intents to match; we're not equivalent
11985                    if (DEBUG_FILTERS) {
11986                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11987                                + " package: " + applicationInfo.packageName
11988                                + " activity: " + intent.activity.className
11989                                + " origPrio: " + intent.getPriority());
11990                    }
11991                    intent.setPriority(0);
11992                    return;
11993                }
11994            }
11995
11996            // find matching authorities subsets
11997            final Iterator<IntentFilter.AuthorityEntry>
11998                    authoritiesIterator = intent.authoritiesIterator();
11999            if (authoritiesIterator != null) {
12000                getIntentListSubset(intentListCopy,
12001                        new AuthoritiesIterGenerator(),
12002                        authoritiesIterator);
12003                if (intentListCopy.size() == 0) {
12004                    // no more intents to match; we're not equivalent
12005                    if (DEBUG_FILTERS) {
12006                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12007                                + " package: " + applicationInfo.packageName
12008                                + " activity: " + intent.activity.className
12009                                + " origPrio: " + intent.getPriority());
12010                    }
12011                    intent.setPriority(0);
12012                    return;
12013                }
12014            }
12015
12016            // we found matching filter(s); app gets the max priority of all intents
12017            int cappedPriority = 0;
12018            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12019                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12020            }
12021            if (intent.getPriority() > cappedPriority) {
12022                if (DEBUG_FILTERS) {
12023                    Slog.i(TAG, "Found matching filter(s);"
12024                            + " cap priority to " + cappedPriority + ";"
12025                            + " package: " + applicationInfo.packageName
12026                            + " activity: " + intent.activity.className
12027                            + " origPrio: " + intent.getPriority());
12028                }
12029                intent.setPriority(cappedPriority);
12030                return;
12031            }
12032            // all this for nothing; the requested priority was <= what was on the system
12033        }
12034
12035        public final void addActivity(PackageParser.Activity a, String type) {
12036            mActivities.put(a.getComponentName(), a);
12037            if (DEBUG_SHOW_INFO)
12038                Log.v(
12039                TAG, "  " + type + " " +
12040                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12041            if (DEBUG_SHOW_INFO)
12042                Log.v(TAG, "    Class=" + a.info.name);
12043            final int NI = a.intents.size();
12044            for (int j=0; j<NI; j++) {
12045                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12046                if ("activity".equals(type)) {
12047                    final PackageSetting ps =
12048                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12049                    final List<PackageParser.Activity> systemActivities =
12050                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12051                    adjustPriority(systemActivities, intent);
12052                }
12053                if (DEBUG_SHOW_INFO) {
12054                    Log.v(TAG, "    IntentFilter:");
12055                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12056                }
12057                if (!intent.debugCheck()) {
12058                    Log.w(TAG, "==> For Activity " + a.info.name);
12059                }
12060                addFilter(intent);
12061            }
12062        }
12063
12064        public final void removeActivity(PackageParser.Activity a, String type) {
12065            mActivities.remove(a.getComponentName());
12066            if (DEBUG_SHOW_INFO) {
12067                Log.v(TAG, "  " + type + " "
12068                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12069                                : a.info.name) + ":");
12070                Log.v(TAG, "    Class=" + a.info.name);
12071            }
12072            final int NI = a.intents.size();
12073            for (int j=0; j<NI; j++) {
12074                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12075                if (DEBUG_SHOW_INFO) {
12076                    Log.v(TAG, "    IntentFilter:");
12077                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12078                }
12079                removeFilter(intent);
12080            }
12081        }
12082
12083        @Override
12084        protected boolean allowFilterResult(
12085                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12086            ActivityInfo filterAi = filter.activity.info;
12087            for (int i=dest.size()-1; i>=0; i--) {
12088                ActivityInfo destAi = dest.get(i).activityInfo;
12089                if (destAi.name == filterAi.name
12090                        && destAi.packageName == filterAi.packageName) {
12091                    return false;
12092                }
12093            }
12094            return true;
12095        }
12096
12097        @Override
12098        protected ActivityIntentInfo[] newArray(int size) {
12099            return new ActivityIntentInfo[size];
12100        }
12101
12102        @Override
12103        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12104            if (!sUserManager.exists(userId)) return true;
12105            PackageParser.Package p = filter.activity.owner;
12106            if (p != null) {
12107                PackageSetting ps = (PackageSetting)p.mExtras;
12108                if (ps != null) {
12109                    // System apps are never considered stopped for purposes of
12110                    // filtering, because there may be no way for the user to
12111                    // actually re-launch them.
12112                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12113                            && ps.getStopped(userId);
12114                }
12115            }
12116            return false;
12117        }
12118
12119        @Override
12120        protected boolean isPackageForFilter(String packageName,
12121                PackageParser.ActivityIntentInfo info) {
12122            return packageName.equals(info.activity.owner.packageName);
12123        }
12124
12125        @Override
12126        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12127                int match, int userId) {
12128            if (!sUserManager.exists(userId)) return null;
12129            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12130                return null;
12131            }
12132            final PackageParser.Activity activity = info.activity;
12133            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12134            if (ps == null) {
12135                return null;
12136            }
12137            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12138                    ps.readUserState(userId), userId);
12139            if (ai == null) {
12140                return null;
12141            }
12142            final ResolveInfo res = new ResolveInfo();
12143            res.activityInfo = ai;
12144            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12145                res.filter = info;
12146            }
12147            if (info != null) {
12148                res.handleAllWebDataURI = info.handleAllWebDataURI();
12149            }
12150            res.priority = info.getPriority();
12151            res.preferredOrder = activity.owner.mPreferredOrder;
12152            //System.out.println("Result: " + res.activityInfo.className +
12153            //                   " = " + res.priority);
12154            res.match = match;
12155            res.isDefault = info.hasDefault;
12156            res.labelRes = info.labelRes;
12157            res.nonLocalizedLabel = info.nonLocalizedLabel;
12158            if (userNeedsBadging(userId)) {
12159                res.noResourceId = true;
12160            } else {
12161                res.icon = info.icon;
12162            }
12163            res.iconResourceId = info.icon;
12164            res.system = res.activityInfo.applicationInfo.isSystemApp();
12165            return res;
12166        }
12167
12168        @Override
12169        protected void sortResults(List<ResolveInfo> results) {
12170            Collections.sort(results, mResolvePrioritySorter);
12171        }
12172
12173        @Override
12174        protected void dumpFilter(PrintWriter out, String prefix,
12175                PackageParser.ActivityIntentInfo filter) {
12176            out.print(prefix); out.print(
12177                    Integer.toHexString(System.identityHashCode(filter.activity)));
12178                    out.print(' ');
12179                    filter.activity.printComponentShortName(out);
12180                    out.print(" filter ");
12181                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12182        }
12183
12184        @Override
12185        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12186            return filter.activity;
12187        }
12188
12189        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12190            PackageParser.Activity activity = (PackageParser.Activity)label;
12191            out.print(prefix); out.print(
12192                    Integer.toHexString(System.identityHashCode(activity)));
12193                    out.print(' ');
12194                    activity.printComponentShortName(out);
12195            if (count > 1) {
12196                out.print(" ("); out.print(count); out.print(" filters)");
12197            }
12198            out.println();
12199        }
12200
12201        // Keys are String (activity class name), values are Activity.
12202        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12203                = new ArrayMap<ComponentName, PackageParser.Activity>();
12204        private int mFlags;
12205    }
12206
12207    private final class ServiceIntentResolver
12208            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12209        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12210                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12211            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12212            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12213                    isEphemeral, userId);
12214        }
12215
12216        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12217                int userId) {
12218            if (!sUserManager.exists(userId)) return null;
12219            mFlags = flags;
12220            return super.queryIntent(intent, resolvedType,
12221                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12222                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12223                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12224        }
12225
12226        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12227                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12228            if (!sUserManager.exists(userId)) return null;
12229            if (packageServices == null) {
12230                return null;
12231            }
12232            mFlags = flags;
12233            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12234            final boolean vislbleToEphemeral =
12235                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12236            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12237            final int N = packageServices.size();
12238            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12239                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12240
12241            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12242            for (int i = 0; i < N; ++i) {
12243                intentFilters = packageServices.get(i).intents;
12244                if (intentFilters != null && intentFilters.size() > 0) {
12245                    PackageParser.ServiceIntentInfo[] array =
12246                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12247                    intentFilters.toArray(array);
12248                    listCut.add(array);
12249                }
12250            }
12251            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12252                    vislbleToEphemeral, isEphemeral, listCut, userId);
12253        }
12254
12255        public final void addService(PackageParser.Service s) {
12256            mServices.put(s.getComponentName(), s);
12257            if (DEBUG_SHOW_INFO) {
12258                Log.v(TAG, "  "
12259                        + (s.info.nonLocalizedLabel != null
12260                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12261                Log.v(TAG, "    Class=" + s.info.name);
12262            }
12263            final int NI = s.intents.size();
12264            int j;
12265            for (j=0; j<NI; j++) {
12266                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12267                if (DEBUG_SHOW_INFO) {
12268                    Log.v(TAG, "    IntentFilter:");
12269                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12270                }
12271                if (!intent.debugCheck()) {
12272                    Log.w(TAG, "==> For Service " + s.info.name);
12273                }
12274                addFilter(intent);
12275            }
12276        }
12277
12278        public final void removeService(PackageParser.Service s) {
12279            mServices.remove(s.getComponentName());
12280            if (DEBUG_SHOW_INFO) {
12281                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12282                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12283                Log.v(TAG, "    Class=" + s.info.name);
12284            }
12285            final int NI = s.intents.size();
12286            int j;
12287            for (j=0; j<NI; j++) {
12288                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12289                if (DEBUG_SHOW_INFO) {
12290                    Log.v(TAG, "    IntentFilter:");
12291                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12292                }
12293                removeFilter(intent);
12294            }
12295        }
12296
12297        @Override
12298        protected boolean allowFilterResult(
12299                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12300            ServiceInfo filterSi = filter.service.info;
12301            for (int i=dest.size()-1; i>=0; i--) {
12302                ServiceInfo destAi = dest.get(i).serviceInfo;
12303                if (destAi.name == filterSi.name
12304                        && destAi.packageName == filterSi.packageName) {
12305                    return false;
12306                }
12307            }
12308            return true;
12309        }
12310
12311        @Override
12312        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12313            return new PackageParser.ServiceIntentInfo[size];
12314        }
12315
12316        @Override
12317        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12318            if (!sUserManager.exists(userId)) return true;
12319            PackageParser.Package p = filter.service.owner;
12320            if (p != null) {
12321                PackageSetting ps = (PackageSetting)p.mExtras;
12322                if (ps != null) {
12323                    // System apps are never considered stopped for purposes of
12324                    // filtering, because there may be no way for the user to
12325                    // actually re-launch them.
12326                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12327                            && ps.getStopped(userId);
12328                }
12329            }
12330            return false;
12331        }
12332
12333        @Override
12334        protected boolean isPackageForFilter(String packageName,
12335                PackageParser.ServiceIntentInfo info) {
12336            return packageName.equals(info.service.owner.packageName);
12337        }
12338
12339        @Override
12340        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12341                int match, int userId) {
12342            if (!sUserManager.exists(userId)) return null;
12343            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12344            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12345                return null;
12346            }
12347            final PackageParser.Service service = info.service;
12348            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12349            if (ps == null) {
12350                return null;
12351            }
12352            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12353                    ps.readUserState(userId), userId);
12354            if (si == null) {
12355                return null;
12356            }
12357            final ResolveInfo res = new ResolveInfo();
12358            res.serviceInfo = si;
12359            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12360                res.filter = filter;
12361            }
12362            res.priority = info.getPriority();
12363            res.preferredOrder = service.owner.mPreferredOrder;
12364            res.match = match;
12365            res.isDefault = info.hasDefault;
12366            res.labelRes = info.labelRes;
12367            res.nonLocalizedLabel = info.nonLocalizedLabel;
12368            res.icon = info.icon;
12369            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12370            return res;
12371        }
12372
12373        @Override
12374        protected void sortResults(List<ResolveInfo> results) {
12375            Collections.sort(results, mResolvePrioritySorter);
12376        }
12377
12378        @Override
12379        protected void dumpFilter(PrintWriter out, String prefix,
12380                PackageParser.ServiceIntentInfo filter) {
12381            out.print(prefix); out.print(
12382                    Integer.toHexString(System.identityHashCode(filter.service)));
12383                    out.print(' ');
12384                    filter.service.printComponentShortName(out);
12385                    out.print(" filter ");
12386                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12387        }
12388
12389        @Override
12390        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12391            return filter.service;
12392        }
12393
12394        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12395            PackageParser.Service service = (PackageParser.Service)label;
12396            out.print(prefix); out.print(
12397                    Integer.toHexString(System.identityHashCode(service)));
12398                    out.print(' ');
12399                    service.printComponentShortName(out);
12400            if (count > 1) {
12401                out.print(" ("); out.print(count); out.print(" filters)");
12402            }
12403            out.println();
12404        }
12405
12406//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12407//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12408//            final List<ResolveInfo> retList = Lists.newArrayList();
12409//            while (i.hasNext()) {
12410//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12411//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12412//                    retList.add(resolveInfo);
12413//                }
12414//            }
12415//            return retList;
12416//        }
12417
12418        // Keys are String (activity class name), values are Activity.
12419        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12420                = new ArrayMap<ComponentName, PackageParser.Service>();
12421        private int mFlags;
12422    }
12423
12424    private final class ProviderIntentResolver
12425            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12426        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12427                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12428            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12429            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12430                    isEphemeral, userId);
12431        }
12432
12433        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12434                int userId) {
12435            if (!sUserManager.exists(userId))
12436                return null;
12437            mFlags = flags;
12438            return super.queryIntent(intent, resolvedType,
12439                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12440                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12441                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12442        }
12443
12444        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12445                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12446            if (!sUserManager.exists(userId))
12447                return null;
12448            if (packageProviders == null) {
12449                return null;
12450            }
12451            mFlags = flags;
12452            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12453            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12454            final boolean vislbleToEphemeral =
12455                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12456            final int N = packageProviders.size();
12457            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12458                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12459
12460            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12461            for (int i = 0; i < N; ++i) {
12462                intentFilters = packageProviders.get(i).intents;
12463                if (intentFilters != null && intentFilters.size() > 0) {
12464                    PackageParser.ProviderIntentInfo[] array =
12465                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12466                    intentFilters.toArray(array);
12467                    listCut.add(array);
12468                }
12469            }
12470            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12471                    vislbleToEphemeral, isEphemeral, listCut, userId);
12472        }
12473
12474        public final void addProvider(PackageParser.Provider p) {
12475            if (mProviders.containsKey(p.getComponentName())) {
12476                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12477                return;
12478            }
12479
12480            mProviders.put(p.getComponentName(), p);
12481            if (DEBUG_SHOW_INFO) {
12482                Log.v(TAG, "  "
12483                        + (p.info.nonLocalizedLabel != null
12484                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12485                Log.v(TAG, "    Class=" + p.info.name);
12486            }
12487            final int NI = p.intents.size();
12488            int j;
12489            for (j = 0; j < NI; j++) {
12490                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12491                if (DEBUG_SHOW_INFO) {
12492                    Log.v(TAG, "    IntentFilter:");
12493                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12494                }
12495                if (!intent.debugCheck()) {
12496                    Log.w(TAG, "==> For Provider " + p.info.name);
12497                }
12498                addFilter(intent);
12499            }
12500        }
12501
12502        public final void removeProvider(PackageParser.Provider p) {
12503            mProviders.remove(p.getComponentName());
12504            if (DEBUG_SHOW_INFO) {
12505                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12506                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12507                Log.v(TAG, "    Class=" + p.info.name);
12508            }
12509            final int NI = p.intents.size();
12510            int j;
12511            for (j = 0; j < NI; j++) {
12512                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12513                if (DEBUG_SHOW_INFO) {
12514                    Log.v(TAG, "    IntentFilter:");
12515                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12516                }
12517                removeFilter(intent);
12518            }
12519        }
12520
12521        @Override
12522        protected boolean allowFilterResult(
12523                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12524            ProviderInfo filterPi = filter.provider.info;
12525            for (int i = dest.size() - 1; i >= 0; i--) {
12526                ProviderInfo destPi = dest.get(i).providerInfo;
12527                if (destPi.name == filterPi.name
12528                        && destPi.packageName == filterPi.packageName) {
12529                    return false;
12530                }
12531            }
12532            return true;
12533        }
12534
12535        @Override
12536        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12537            return new PackageParser.ProviderIntentInfo[size];
12538        }
12539
12540        @Override
12541        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12542            if (!sUserManager.exists(userId))
12543                return true;
12544            PackageParser.Package p = filter.provider.owner;
12545            if (p != null) {
12546                PackageSetting ps = (PackageSetting) p.mExtras;
12547                if (ps != null) {
12548                    // System apps are never considered stopped for purposes of
12549                    // filtering, because there may be no way for the user to
12550                    // actually re-launch them.
12551                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12552                            && ps.getStopped(userId);
12553                }
12554            }
12555            return false;
12556        }
12557
12558        @Override
12559        protected boolean isPackageForFilter(String packageName,
12560                PackageParser.ProviderIntentInfo info) {
12561            return packageName.equals(info.provider.owner.packageName);
12562        }
12563
12564        @Override
12565        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12566                int match, int userId) {
12567            if (!sUserManager.exists(userId))
12568                return null;
12569            final PackageParser.ProviderIntentInfo info = filter;
12570            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12571                return null;
12572            }
12573            final PackageParser.Provider provider = info.provider;
12574            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12575            if (ps == null) {
12576                return null;
12577            }
12578            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12579                    ps.readUserState(userId), userId);
12580            if (pi == null) {
12581                return null;
12582            }
12583            final ResolveInfo res = new ResolveInfo();
12584            res.providerInfo = pi;
12585            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12586                res.filter = filter;
12587            }
12588            res.priority = info.getPriority();
12589            res.preferredOrder = provider.owner.mPreferredOrder;
12590            res.match = match;
12591            res.isDefault = info.hasDefault;
12592            res.labelRes = info.labelRes;
12593            res.nonLocalizedLabel = info.nonLocalizedLabel;
12594            res.icon = info.icon;
12595            res.system = res.providerInfo.applicationInfo.isSystemApp();
12596            return res;
12597        }
12598
12599        @Override
12600        protected void sortResults(List<ResolveInfo> results) {
12601            Collections.sort(results, mResolvePrioritySorter);
12602        }
12603
12604        @Override
12605        protected void dumpFilter(PrintWriter out, String prefix,
12606                PackageParser.ProviderIntentInfo filter) {
12607            out.print(prefix);
12608            out.print(
12609                    Integer.toHexString(System.identityHashCode(filter.provider)));
12610            out.print(' ');
12611            filter.provider.printComponentShortName(out);
12612            out.print(" filter ");
12613            out.println(Integer.toHexString(System.identityHashCode(filter)));
12614        }
12615
12616        @Override
12617        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12618            return filter.provider;
12619        }
12620
12621        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12622            PackageParser.Provider provider = (PackageParser.Provider)label;
12623            out.print(prefix); out.print(
12624                    Integer.toHexString(System.identityHashCode(provider)));
12625                    out.print(' ');
12626                    provider.printComponentShortName(out);
12627            if (count > 1) {
12628                out.print(" ("); out.print(count); out.print(" filters)");
12629            }
12630            out.println();
12631        }
12632
12633        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12634                = new ArrayMap<ComponentName, PackageParser.Provider>();
12635        private int mFlags;
12636    }
12637
12638    static final class EphemeralIntentResolver
12639            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12640        /**
12641         * The result that has the highest defined order. Ordering applies on a
12642         * per-package basis. Mapping is from package name to Pair of order and
12643         * EphemeralResolveInfo.
12644         * <p>
12645         * NOTE: This is implemented as a field variable for convenience and efficiency.
12646         * By having a field variable, we're able to track filter ordering as soon as
12647         * a non-zero order is defined. Otherwise, multiple loops across the result set
12648         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12649         * this needs to be contained entirely within {@link #filterResults()}.
12650         */
12651        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12652
12653        @Override
12654        protected EphemeralResponse[] newArray(int size) {
12655            return new EphemeralResponse[size];
12656        }
12657
12658        @Override
12659        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12660            return true;
12661        }
12662
12663        @Override
12664        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12665                int userId) {
12666            if (!sUserManager.exists(userId)) {
12667                return null;
12668            }
12669            final String packageName = responseObj.resolveInfo.getPackageName();
12670            final Integer order = responseObj.getOrder();
12671            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12672                    mOrderResult.get(packageName);
12673            // ordering is enabled and this item's order isn't high enough
12674            if (lastOrderResult != null && lastOrderResult.first >= order) {
12675                return null;
12676            }
12677            final EphemeralResolveInfo res = responseObj.resolveInfo;
12678            if (order > 0) {
12679                // non-zero order, enable ordering
12680                mOrderResult.put(packageName, new Pair<>(order, res));
12681            }
12682            return responseObj;
12683        }
12684
12685        @Override
12686        protected void filterResults(List<EphemeralResponse> results) {
12687            // only do work if ordering is enabled [most of the time it won't be]
12688            if (mOrderResult.size() == 0) {
12689                return;
12690            }
12691            int resultSize = results.size();
12692            for (int i = 0; i < resultSize; i++) {
12693                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12694                final String packageName = info.getPackageName();
12695                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12696                if (savedInfo == null) {
12697                    // package doesn't having ordering
12698                    continue;
12699                }
12700                if (savedInfo.second == info) {
12701                    // circled back to the highest ordered item; remove from order list
12702                    mOrderResult.remove(savedInfo);
12703                    if (mOrderResult.size() == 0) {
12704                        // no more ordered items
12705                        break;
12706                    }
12707                    continue;
12708                }
12709                // item has a worse order, remove it from the result list
12710                results.remove(i);
12711                resultSize--;
12712                i--;
12713            }
12714        }
12715    }
12716
12717    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12718            new Comparator<ResolveInfo>() {
12719        public int compare(ResolveInfo r1, ResolveInfo r2) {
12720            int v1 = r1.priority;
12721            int v2 = r2.priority;
12722            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12723            if (v1 != v2) {
12724                return (v1 > v2) ? -1 : 1;
12725            }
12726            v1 = r1.preferredOrder;
12727            v2 = r2.preferredOrder;
12728            if (v1 != v2) {
12729                return (v1 > v2) ? -1 : 1;
12730            }
12731            if (r1.isDefault != r2.isDefault) {
12732                return r1.isDefault ? -1 : 1;
12733            }
12734            v1 = r1.match;
12735            v2 = r2.match;
12736            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12737            if (v1 != v2) {
12738                return (v1 > v2) ? -1 : 1;
12739            }
12740            if (r1.system != r2.system) {
12741                return r1.system ? -1 : 1;
12742            }
12743            if (r1.activityInfo != null) {
12744                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12745            }
12746            if (r1.serviceInfo != null) {
12747                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12748            }
12749            if (r1.providerInfo != null) {
12750                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12751            }
12752            return 0;
12753        }
12754    };
12755
12756    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12757            new Comparator<ProviderInfo>() {
12758        public int compare(ProviderInfo p1, ProviderInfo p2) {
12759            final int v1 = p1.initOrder;
12760            final int v2 = p2.initOrder;
12761            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12762        }
12763    };
12764
12765    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12766            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12767            final int[] userIds) {
12768        mHandler.post(new Runnable() {
12769            @Override
12770            public void run() {
12771                try {
12772                    final IActivityManager am = ActivityManager.getService();
12773                    if (am == null) return;
12774                    final int[] resolvedUserIds;
12775                    if (userIds == null) {
12776                        resolvedUserIds = am.getRunningUserIds();
12777                    } else {
12778                        resolvedUserIds = userIds;
12779                    }
12780                    for (int id : resolvedUserIds) {
12781                        final Intent intent = new Intent(action,
12782                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12783                        if (extras != null) {
12784                            intent.putExtras(extras);
12785                        }
12786                        if (targetPkg != null) {
12787                            intent.setPackage(targetPkg);
12788                        }
12789                        // Modify the UID when posting to other users
12790                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12791                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12792                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12793                            intent.putExtra(Intent.EXTRA_UID, uid);
12794                        }
12795                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12796                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12797                        if (DEBUG_BROADCASTS) {
12798                            RuntimeException here = new RuntimeException("here");
12799                            here.fillInStackTrace();
12800                            Slog.d(TAG, "Sending to user " + id + ": "
12801                                    + intent.toShortString(false, true, false, false)
12802                                    + " " + intent.getExtras(), here);
12803                        }
12804                        am.broadcastIntent(null, intent, null, finishedReceiver,
12805                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12806                                null, finishedReceiver != null, false, id);
12807                    }
12808                } catch (RemoteException ex) {
12809                }
12810            }
12811        });
12812    }
12813
12814    /**
12815     * Check if the external storage media is available. This is true if there
12816     * is a mounted external storage medium or if the external storage is
12817     * emulated.
12818     */
12819    private boolean isExternalMediaAvailable() {
12820        return mMediaMounted || Environment.isExternalStorageEmulated();
12821    }
12822
12823    @Override
12824    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12825        // writer
12826        synchronized (mPackages) {
12827            if (!isExternalMediaAvailable()) {
12828                // If the external storage is no longer mounted at this point,
12829                // the caller may not have been able to delete all of this
12830                // packages files and can not delete any more.  Bail.
12831                return null;
12832            }
12833            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12834            if (lastPackage != null) {
12835                pkgs.remove(lastPackage);
12836            }
12837            if (pkgs.size() > 0) {
12838                return pkgs.get(0);
12839            }
12840        }
12841        return null;
12842    }
12843
12844    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12845        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12846                userId, andCode ? 1 : 0, packageName);
12847        if (mSystemReady) {
12848            msg.sendToTarget();
12849        } else {
12850            if (mPostSystemReadyMessages == null) {
12851                mPostSystemReadyMessages = new ArrayList<>();
12852            }
12853            mPostSystemReadyMessages.add(msg);
12854        }
12855    }
12856
12857    void startCleaningPackages() {
12858        // reader
12859        if (!isExternalMediaAvailable()) {
12860            return;
12861        }
12862        synchronized (mPackages) {
12863            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12864                return;
12865            }
12866        }
12867        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12868        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12869        IActivityManager am = ActivityManager.getService();
12870        if (am != null) {
12871            try {
12872                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12873                        UserHandle.USER_SYSTEM);
12874            } catch (RemoteException e) {
12875            }
12876        }
12877    }
12878
12879    @Override
12880    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12881            int installFlags, String installerPackageName, int userId) {
12882        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12883
12884        final int callingUid = Binder.getCallingUid();
12885        enforceCrossUserPermission(callingUid, userId,
12886                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12887
12888        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12889            try {
12890                if (observer != null) {
12891                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12892                }
12893            } catch (RemoteException re) {
12894            }
12895            return;
12896        }
12897
12898        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12899            installFlags |= PackageManager.INSTALL_FROM_ADB;
12900
12901        } else {
12902            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12903            // about installerPackageName.
12904
12905            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12906            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12907        }
12908
12909        UserHandle user;
12910        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12911            user = UserHandle.ALL;
12912        } else {
12913            user = new UserHandle(userId);
12914        }
12915
12916        // Only system components can circumvent runtime permissions when installing.
12917        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12918                && mContext.checkCallingOrSelfPermission(Manifest.permission
12919                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12920            throw new SecurityException("You need the "
12921                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12922                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12923        }
12924
12925        final File originFile = new File(originPath);
12926        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12927
12928        final Message msg = mHandler.obtainMessage(INIT_COPY);
12929        final VerificationInfo verificationInfo = new VerificationInfo(
12930                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12931        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12932                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12933                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12934                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12935        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12936        msg.obj = params;
12937
12938        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12939                System.identityHashCode(msg.obj));
12940        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12941                System.identityHashCode(msg.obj));
12942
12943        mHandler.sendMessage(msg);
12944    }
12945
12946
12947    /**
12948     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12949     * it is acting on behalf on an enterprise or the user).
12950     *
12951     * Note that the ordering of the conditionals in this method is important. The checks we perform
12952     * are as follows, in this order:
12953     *
12954     * 1) If the install is being performed by a system app, we can trust the app to have set the
12955     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12956     *    what it is.
12957     * 2) If the install is being performed by a device or profile owner app, the install reason
12958     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12959     *    set the install reason correctly. If the app targets an older SDK version where install
12960     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12961     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12962     * 3) In all other cases, the install is being performed by a regular app that is neither part
12963     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12964     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12965     *    set to enterprise policy and if so, change it to unknown instead.
12966     */
12967    private int fixUpInstallReason(String installerPackageName, int installerUid,
12968            int installReason) {
12969        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12970                == PERMISSION_GRANTED) {
12971            // If the install is being performed by a system app, we trust that app to have set the
12972            // install reason correctly.
12973            return installReason;
12974        }
12975
12976        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12977            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12978        if (dpm != null) {
12979            ComponentName owner = null;
12980            try {
12981                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12982                if (owner == null) {
12983                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12984                }
12985            } catch (RemoteException e) {
12986            }
12987            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12988                // If the install is being performed by a device or profile owner, the install
12989                // reason should be enterprise policy.
12990                return PackageManager.INSTALL_REASON_POLICY;
12991            }
12992        }
12993
12994        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12995            // If the install is being performed by a regular app (i.e. neither system app nor
12996            // device or profile owner), we have no reason to believe that the app is acting on
12997            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12998            // change it to unknown instead.
12999            return PackageManager.INSTALL_REASON_UNKNOWN;
13000        }
13001
13002        // If the install is being performed by a regular app and the install reason was set to any
13003        // value but enterprise policy, leave the install reason unchanged.
13004        return installReason;
13005    }
13006
13007    void installStage(String packageName, File stagedDir, String stagedCid,
13008            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13009            String installerPackageName, int installerUid, UserHandle user,
13010            Certificate[][] certificates) {
13011        if (DEBUG_EPHEMERAL) {
13012            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13013                Slog.d(TAG, "Ephemeral install of " + packageName);
13014            }
13015        }
13016        final VerificationInfo verificationInfo = new VerificationInfo(
13017                sessionParams.originatingUri, sessionParams.referrerUri,
13018                sessionParams.originatingUid, installerUid);
13019
13020        final OriginInfo origin;
13021        if (stagedDir != null) {
13022            origin = OriginInfo.fromStagedFile(stagedDir);
13023        } else {
13024            origin = OriginInfo.fromStagedContainer(stagedCid);
13025        }
13026
13027        final Message msg = mHandler.obtainMessage(INIT_COPY);
13028        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13029                sessionParams.installReason);
13030        final InstallParams params = new InstallParams(origin, null, observer,
13031                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13032                verificationInfo, user, sessionParams.abiOverride,
13033                sessionParams.grantedRuntimePermissions, certificates, installReason);
13034        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13035        msg.obj = params;
13036
13037        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13038                System.identityHashCode(msg.obj));
13039        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13040                System.identityHashCode(msg.obj));
13041
13042        mHandler.sendMessage(msg);
13043    }
13044
13045    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13046            int userId) {
13047        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13048        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13049    }
13050
13051    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13052            int appId, int... userIds) {
13053        if (ArrayUtils.isEmpty(userIds)) {
13054            return;
13055        }
13056        Bundle extras = new Bundle(1);
13057        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13058        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13059
13060        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13061                packageName, extras, 0, null, null, userIds);
13062        if (isSystem) {
13063            mHandler.post(() -> {
13064                        for (int userId : userIds) {
13065                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13066                        }
13067                    }
13068            );
13069        }
13070    }
13071
13072    /**
13073     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13074     * automatically without needing an explicit launch.
13075     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13076     */
13077    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13078        // If user is not running, the app didn't miss any broadcast
13079        if (!mUserManagerInternal.isUserRunning(userId)) {
13080            return;
13081        }
13082        final IActivityManager am = ActivityManager.getService();
13083        try {
13084            // Deliver LOCKED_BOOT_COMPLETED first
13085            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13086                    .setPackage(packageName);
13087            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13088            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13089                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13090
13091            // Deliver BOOT_COMPLETED only if user is unlocked
13092            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13093                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13094                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13095                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13096            }
13097        } catch (RemoteException e) {
13098            throw e.rethrowFromSystemServer();
13099        }
13100    }
13101
13102    @Override
13103    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13104            int userId) {
13105        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13106        PackageSetting pkgSetting;
13107        final int uid = Binder.getCallingUid();
13108        enforceCrossUserPermission(uid, userId,
13109                true /* requireFullPermission */, true /* checkShell */,
13110                "setApplicationHiddenSetting for user " + userId);
13111
13112        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13113            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13114            return false;
13115        }
13116
13117        long callingId = Binder.clearCallingIdentity();
13118        try {
13119            boolean sendAdded = false;
13120            boolean sendRemoved = false;
13121            // writer
13122            synchronized (mPackages) {
13123                pkgSetting = mSettings.mPackages.get(packageName);
13124                if (pkgSetting == null) {
13125                    return false;
13126                }
13127                // Do not allow "android" is being disabled
13128                if ("android".equals(packageName)) {
13129                    Slog.w(TAG, "Cannot hide package: android");
13130                    return false;
13131                }
13132                // Cannot hide static shared libs as they are considered
13133                // a part of the using app (emulating static linking). Also
13134                // static libs are installed always on internal storage.
13135                PackageParser.Package pkg = mPackages.get(packageName);
13136                if (pkg != null && pkg.staticSharedLibName != null) {
13137                    Slog.w(TAG, "Cannot hide package: " + packageName
13138                            + " providing static shared library: "
13139                            + pkg.staticSharedLibName);
13140                    return false;
13141                }
13142                // Only allow protected packages to hide themselves.
13143                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13144                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13145                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13146                    return false;
13147                }
13148
13149                if (pkgSetting.getHidden(userId) != hidden) {
13150                    pkgSetting.setHidden(hidden, userId);
13151                    mSettings.writePackageRestrictionsLPr(userId);
13152                    if (hidden) {
13153                        sendRemoved = true;
13154                    } else {
13155                        sendAdded = true;
13156                    }
13157                }
13158            }
13159            if (sendAdded) {
13160                sendPackageAddedForUser(packageName, pkgSetting, userId);
13161                return true;
13162            }
13163            if (sendRemoved) {
13164                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13165                        "hiding pkg");
13166                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13167                return true;
13168            }
13169        } finally {
13170            Binder.restoreCallingIdentity(callingId);
13171        }
13172        return false;
13173    }
13174
13175    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13176            int userId) {
13177        final PackageRemovedInfo info = new PackageRemovedInfo();
13178        info.removedPackage = packageName;
13179        info.removedUsers = new int[] {userId};
13180        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13181        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13182    }
13183
13184    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13185        if (pkgList.length > 0) {
13186            Bundle extras = new Bundle(1);
13187            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13188
13189            sendPackageBroadcast(
13190                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13191                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13192                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13193                    new int[] {userId});
13194        }
13195    }
13196
13197    /**
13198     * Returns true if application is not found or there was an error. Otherwise it returns
13199     * the hidden state of the package for the given user.
13200     */
13201    @Override
13202    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13203        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13204        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13205                true /* requireFullPermission */, false /* checkShell */,
13206                "getApplicationHidden for user " + userId);
13207        PackageSetting pkgSetting;
13208        long callingId = Binder.clearCallingIdentity();
13209        try {
13210            // writer
13211            synchronized (mPackages) {
13212                pkgSetting = mSettings.mPackages.get(packageName);
13213                if (pkgSetting == null) {
13214                    return true;
13215                }
13216                return pkgSetting.getHidden(userId);
13217            }
13218        } finally {
13219            Binder.restoreCallingIdentity(callingId);
13220        }
13221    }
13222
13223    /**
13224     * @hide
13225     */
13226    @Override
13227    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13229                null);
13230        PackageSetting pkgSetting;
13231        final int uid = Binder.getCallingUid();
13232        enforceCrossUserPermission(uid, userId,
13233                true /* requireFullPermission */, true /* checkShell */,
13234                "installExistingPackage for user " + userId);
13235        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13236            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13237        }
13238
13239        long callingId = Binder.clearCallingIdentity();
13240        try {
13241            boolean installed = false;
13242
13243            // writer
13244            synchronized (mPackages) {
13245                pkgSetting = mSettings.mPackages.get(packageName);
13246                if (pkgSetting == null) {
13247                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13248                }
13249                if (!pkgSetting.getInstalled(userId)) {
13250                    pkgSetting.setInstalled(true, userId);
13251                    pkgSetting.setHidden(false, userId);
13252                    pkgSetting.setInstallReason(installReason, userId);
13253                    mSettings.writePackageRestrictionsLPr(userId);
13254                    installed = true;
13255                }
13256            }
13257
13258            if (installed) {
13259                if (pkgSetting.pkg != null) {
13260                    synchronized (mInstallLock) {
13261                        // We don't need to freeze for a brand new install
13262                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13263                    }
13264                }
13265                sendPackageAddedForUser(packageName, pkgSetting, userId);
13266            }
13267        } finally {
13268            Binder.restoreCallingIdentity(callingId);
13269        }
13270
13271        return PackageManager.INSTALL_SUCCEEDED;
13272    }
13273
13274    boolean isUserRestricted(int userId, String restrictionKey) {
13275        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13276        if (restrictions.getBoolean(restrictionKey, false)) {
13277            Log.w(TAG, "User is restricted: " + restrictionKey);
13278            return true;
13279        }
13280        return false;
13281    }
13282
13283    @Override
13284    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13285            int userId) {
13286        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13288                true /* requireFullPermission */, true /* checkShell */,
13289                "setPackagesSuspended for user " + userId);
13290
13291        if (ArrayUtils.isEmpty(packageNames)) {
13292            return packageNames;
13293        }
13294
13295        // List of package names for whom the suspended state has changed.
13296        List<String> changedPackages = new ArrayList<>(packageNames.length);
13297        // List of package names for whom the suspended state is not set as requested in this
13298        // method.
13299        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13300        long callingId = Binder.clearCallingIdentity();
13301        try {
13302            for (int i = 0; i < packageNames.length; i++) {
13303                String packageName = packageNames[i];
13304                boolean changed = false;
13305                final int appId;
13306                synchronized (mPackages) {
13307                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13308                    if (pkgSetting == null) {
13309                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13310                                + "\". Skipping suspending/un-suspending.");
13311                        unactionedPackages.add(packageName);
13312                        continue;
13313                    }
13314                    appId = pkgSetting.appId;
13315                    if (pkgSetting.getSuspended(userId) != suspended) {
13316                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13317                            unactionedPackages.add(packageName);
13318                            continue;
13319                        }
13320                        pkgSetting.setSuspended(suspended, userId);
13321                        mSettings.writePackageRestrictionsLPr(userId);
13322                        changed = true;
13323                        changedPackages.add(packageName);
13324                    }
13325                }
13326
13327                if (changed && suspended) {
13328                    killApplication(packageName, UserHandle.getUid(userId, appId),
13329                            "suspending package");
13330                }
13331            }
13332        } finally {
13333            Binder.restoreCallingIdentity(callingId);
13334        }
13335
13336        if (!changedPackages.isEmpty()) {
13337            sendPackagesSuspendedForUser(changedPackages.toArray(
13338                    new String[changedPackages.size()]), userId, suspended);
13339        }
13340
13341        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13342    }
13343
13344    @Override
13345    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13347                true /* requireFullPermission */, false /* checkShell */,
13348                "isPackageSuspendedForUser for user " + userId);
13349        synchronized (mPackages) {
13350            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13351            if (pkgSetting == null) {
13352                throw new IllegalArgumentException("Unknown target package: " + packageName);
13353            }
13354            return pkgSetting.getSuspended(userId);
13355        }
13356    }
13357
13358    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13359        if (isPackageDeviceAdmin(packageName, userId)) {
13360            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13361                    + "\": has an active device admin");
13362            return false;
13363        }
13364
13365        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13366        if (packageName.equals(activeLauncherPackageName)) {
13367            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13368                    + "\": contains the active launcher");
13369            return false;
13370        }
13371
13372        if (packageName.equals(mRequiredInstallerPackage)) {
13373            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13374                    + "\": required for package installation");
13375            return false;
13376        }
13377
13378        if (packageName.equals(mRequiredUninstallerPackage)) {
13379            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13380                    + "\": required for package uninstallation");
13381            return false;
13382        }
13383
13384        if (packageName.equals(mRequiredVerifierPackage)) {
13385            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13386                    + "\": required for package verification");
13387            return false;
13388        }
13389
13390        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13391            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13392                    + "\": is the default dialer");
13393            return false;
13394        }
13395
13396        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13397            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13398                    + "\": protected package");
13399            return false;
13400        }
13401
13402        // Cannot suspend static shared libs as they are considered
13403        // a part of the using app (emulating static linking). Also
13404        // static libs are installed always on internal storage.
13405        PackageParser.Package pkg = mPackages.get(packageName);
13406        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13407            Slog.w(TAG, "Cannot suspend package: " + packageName
13408                    + " providing static shared library: "
13409                    + pkg.staticSharedLibName);
13410            return false;
13411        }
13412
13413        return true;
13414    }
13415
13416    private String getActiveLauncherPackageName(int userId) {
13417        Intent intent = new Intent(Intent.ACTION_MAIN);
13418        intent.addCategory(Intent.CATEGORY_HOME);
13419        ResolveInfo resolveInfo = resolveIntent(
13420                intent,
13421                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13422                PackageManager.MATCH_DEFAULT_ONLY,
13423                userId);
13424
13425        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13426    }
13427
13428    private String getDefaultDialerPackageName(int userId) {
13429        synchronized (mPackages) {
13430            return mSettings.getDefaultDialerPackageNameLPw(userId);
13431        }
13432    }
13433
13434    @Override
13435    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13436        mContext.enforceCallingOrSelfPermission(
13437                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13438                "Only package verification agents can verify applications");
13439
13440        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13441        final PackageVerificationResponse response = new PackageVerificationResponse(
13442                verificationCode, Binder.getCallingUid());
13443        msg.arg1 = id;
13444        msg.obj = response;
13445        mHandler.sendMessage(msg);
13446    }
13447
13448    @Override
13449    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13450            long millisecondsToDelay) {
13451        mContext.enforceCallingOrSelfPermission(
13452                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13453                "Only package verification agents can extend verification timeouts");
13454
13455        final PackageVerificationState state = mPendingVerification.get(id);
13456        final PackageVerificationResponse response = new PackageVerificationResponse(
13457                verificationCodeAtTimeout, Binder.getCallingUid());
13458
13459        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13460            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13461        }
13462        if (millisecondsToDelay < 0) {
13463            millisecondsToDelay = 0;
13464        }
13465        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13466                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13467            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13468        }
13469
13470        if ((state != null) && !state.timeoutExtended()) {
13471            state.extendTimeout();
13472
13473            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13474            msg.arg1 = id;
13475            msg.obj = response;
13476            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13477        }
13478    }
13479
13480    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13481            int verificationCode, UserHandle user) {
13482        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13483        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13484        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13485        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13486        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13487
13488        mContext.sendBroadcastAsUser(intent, user,
13489                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13490    }
13491
13492    private ComponentName matchComponentForVerifier(String packageName,
13493            List<ResolveInfo> receivers) {
13494        ActivityInfo targetReceiver = null;
13495
13496        final int NR = receivers.size();
13497        for (int i = 0; i < NR; i++) {
13498            final ResolveInfo info = receivers.get(i);
13499            if (info.activityInfo == null) {
13500                continue;
13501            }
13502
13503            if (packageName.equals(info.activityInfo.packageName)) {
13504                targetReceiver = info.activityInfo;
13505                break;
13506            }
13507        }
13508
13509        if (targetReceiver == null) {
13510            return null;
13511        }
13512
13513        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13514    }
13515
13516    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13517            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13518        if (pkgInfo.verifiers.length == 0) {
13519            return null;
13520        }
13521
13522        final int N = pkgInfo.verifiers.length;
13523        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13524        for (int i = 0; i < N; i++) {
13525            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13526
13527            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13528                    receivers);
13529            if (comp == null) {
13530                continue;
13531            }
13532
13533            final int verifierUid = getUidForVerifier(verifierInfo);
13534            if (verifierUid == -1) {
13535                continue;
13536            }
13537
13538            if (DEBUG_VERIFY) {
13539                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13540                        + " with the correct signature");
13541            }
13542            sufficientVerifiers.add(comp);
13543            verificationState.addSufficientVerifier(verifierUid);
13544        }
13545
13546        return sufficientVerifiers;
13547    }
13548
13549    private int getUidForVerifier(VerifierInfo verifierInfo) {
13550        synchronized (mPackages) {
13551            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13552            if (pkg == null) {
13553                return -1;
13554            } else if (pkg.mSignatures.length != 1) {
13555                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13556                        + " has more than one signature; ignoring");
13557                return -1;
13558            }
13559
13560            /*
13561             * If the public key of the package's signature does not match
13562             * our expected public key, then this is a different package and
13563             * we should skip.
13564             */
13565
13566            final byte[] expectedPublicKey;
13567            try {
13568                final Signature verifierSig = pkg.mSignatures[0];
13569                final PublicKey publicKey = verifierSig.getPublicKey();
13570                expectedPublicKey = publicKey.getEncoded();
13571            } catch (CertificateException e) {
13572                return -1;
13573            }
13574
13575            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13576
13577            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13578                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13579                        + " does not have the expected public key; ignoring");
13580                return -1;
13581            }
13582
13583            return pkg.applicationInfo.uid;
13584        }
13585    }
13586
13587    @Override
13588    public void finishPackageInstall(int token, boolean didLaunch) {
13589        enforceSystemOrRoot("Only the system is allowed to finish installs");
13590
13591        if (DEBUG_INSTALL) {
13592            Slog.v(TAG, "BM finishing package install for " + token);
13593        }
13594        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13595
13596        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13597        mHandler.sendMessage(msg);
13598    }
13599
13600    /**
13601     * Get the verification agent timeout.
13602     *
13603     * @return verification timeout in milliseconds
13604     */
13605    private long getVerificationTimeout() {
13606        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13607                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13608                DEFAULT_VERIFICATION_TIMEOUT);
13609    }
13610
13611    /**
13612     * Get the default verification agent response code.
13613     *
13614     * @return default verification response code
13615     */
13616    private int getDefaultVerificationResponse() {
13617        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13618                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13619                DEFAULT_VERIFICATION_RESPONSE);
13620    }
13621
13622    /**
13623     * Check whether or not package verification has been enabled.
13624     *
13625     * @return true if verification should be performed
13626     */
13627    private boolean isVerificationEnabled(int userId, int installFlags) {
13628        if (!DEFAULT_VERIFY_ENABLE) {
13629            return false;
13630        }
13631        // Ephemeral apps don't get the full verification treatment
13632        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13633            if (DEBUG_EPHEMERAL) {
13634                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13635            }
13636            return false;
13637        }
13638
13639        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13640
13641        // Check if installing from ADB
13642        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13643            // Do not run verification in a test harness environment
13644            if (ActivityManager.isRunningInTestHarness()) {
13645                return false;
13646            }
13647            if (ensureVerifyAppsEnabled) {
13648                return true;
13649            }
13650            // Check if the developer does not want package verification for ADB installs
13651            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13652                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13653                return false;
13654            }
13655        }
13656
13657        if (ensureVerifyAppsEnabled) {
13658            return true;
13659        }
13660
13661        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13662                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13663    }
13664
13665    @Override
13666    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13667            throws RemoteException {
13668        mContext.enforceCallingOrSelfPermission(
13669                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13670                "Only intentfilter verification agents can verify applications");
13671
13672        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13673        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13674                Binder.getCallingUid(), verificationCode, failedDomains);
13675        msg.arg1 = id;
13676        msg.obj = response;
13677        mHandler.sendMessage(msg);
13678    }
13679
13680    @Override
13681    public int getIntentVerificationStatus(String packageName, int userId) {
13682        synchronized (mPackages) {
13683            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13684        }
13685    }
13686
13687    @Override
13688    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13689        mContext.enforceCallingOrSelfPermission(
13690                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13691
13692        boolean result = false;
13693        synchronized (mPackages) {
13694            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13695        }
13696        if (result) {
13697            scheduleWritePackageRestrictionsLocked(userId);
13698        }
13699        return result;
13700    }
13701
13702    @Override
13703    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13704            String packageName) {
13705        synchronized (mPackages) {
13706            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13707        }
13708    }
13709
13710    @Override
13711    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13712        if (TextUtils.isEmpty(packageName)) {
13713            return ParceledListSlice.emptyList();
13714        }
13715        synchronized (mPackages) {
13716            PackageParser.Package pkg = mPackages.get(packageName);
13717            if (pkg == null || pkg.activities == null) {
13718                return ParceledListSlice.emptyList();
13719            }
13720            final int count = pkg.activities.size();
13721            ArrayList<IntentFilter> result = new ArrayList<>();
13722            for (int n=0; n<count; n++) {
13723                PackageParser.Activity activity = pkg.activities.get(n);
13724                if (activity.intents != null && activity.intents.size() > 0) {
13725                    result.addAll(activity.intents);
13726                }
13727            }
13728            return new ParceledListSlice<>(result);
13729        }
13730    }
13731
13732    @Override
13733    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13734        mContext.enforceCallingOrSelfPermission(
13735                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13736
13737        synchronized (mPackages) {
13738            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13739            if (packageName != null) {
13740                result |= updateIntentVerificationStatus(packageName,
13741                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13742                        userId);
13743                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13744                        packageName, userId);
13745            }
13746            return result;
13747        }
13748    }
13749
13750    @Override
13751    public String getDefaultBrowserPackageName(int userId) {
13752        synchronized (mPackages) {
13753            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13754        }
13755    }
13756
13757    /**
13758     * Get the "allow unknown sources" setting.
13759     *
13760     * @return the current "allow unknown sources" setting
13761     */
13762    private int getUnknownSourcesSettings() {
13763        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13764                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13765                -1);
13766    }
13767
13768    @Override
13769    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13770        final int uid = Binder.getCallingUid();
13771        // writer
13772        synchronized (mPackages) {
13773            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13774            if (targetPackageSetting == null) {
13775                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13776            }
13777
13778            PackageSetting installerPackageSetting;
13779            if (installerPackageName != null) {
13780                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13781                if (installerPackageSetting == null) {
13782                    throw new IllegalArgumentException("Unknown installer package: "
13783                            + installerPackageName);
13784                }
13785            } else {
13786                installerPackageSetting = null;
13787            }
13788
13789            Signature[] callerSignature;
13790            Object obj = mSettings.getUserIdLPr(uid);
13791            if (obj != null) {
13792                if (obj instanceof SharedUserSetting) {
13793                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13794                } else if (obj instanceof PackageSetting) {
13795                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13796                } else {
13797                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13798                }
13799            } else {
13800                throw new SecurityException("Unknown calling UID: " + uid);
13801            }
13802
13803            // Verify: can't set installerPackageName to a package that is
13804            // not signed with the same cert as the caller.
13805            if (installerPackageSetting != null) {
13806                if (compareSignatures(callerSignature,
13807                        installerPackageSetting.signatures.mSignatures)
13808                        != PackageManager.SIGNATURE_MATCH) {
13809                    throw new SecurityException(
13810                            "Caller does not have same cert as new installer package "
13811                            + installerPackageName);
13812                }
13813            }
13814
13815            // Verify: if target already has an installer package, it must
13816            // be signed with the same cert as the caller.
13817            if (targetPackageSetting.installerPackageName != null) {
13818                PackageSetting setting = mSettings.mPackages.get(
13819                        targetPackageSetting.installerPackageName);
13820                // If the currently set package isn't valid, then it's always
13821                // okay to change it.
13822                if (setting != null) {
13823                    if (compareSignatures(callerSignature,
13824                            setting.signatures.mSignatures)
13825                            != PackageManager.SIGNATURE_MATCH) {
13826                        throw new SecurityException(
13827                                "Caller does not have same cert as old installer package "
13828                                + targetPackageSetting.installerPackageName);
13829                    }
13830                }
13831            }
13832
13833            // Okay!
13834            targetPackageSetting.installerPackageName = installerPackageName;
13835            if (installerPackageName != null) {
13836                mSettings.mInstallerPackages.add(installerPackageName);
13837            }
13838            scheduleWriteSettingsLocked();
13839        }
13840    }
13841
13842    @Override
13843    public void setApplicationCategoryHint(String packageName, int categoryHint,
13844            String callerPackageName) {
13845        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13846                callerPackageName);
13847        synchronized (mPackages) {
13848            PackageSetting ps = mSettings.mPackages.get(packageName);
13849            if (ps == null) {
13850                throw new IllegalArgumentException("Unknown target package " + packageName);
13851            }
13852
13853            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13854                throw new IllegalArgumentException("Calling package " + callerPackageName
13855                        + " is not installer for " + packageName);
13856            }
13857
13858            if (ps.categoryHint != categoryHint) {
13859                ps.categoryHint = categoryHint;
13860                scheduleWriteSettingsLocked();
13861            }
13862        }
13863    }
13864
13865    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13866        // Queue up an async operation since the package installation may take a little while.
13867        mHandler.post(new Runnable() {
13868            public void run() {
13869                mHandler.removeCallbacks(this);
13870                 // Result object to be returned
13871                PackageInstalledInfo res = new PackageInstalledInfo();
13872                res.setReturnCode(currentStatus);
13873                res.uid = -1;
13874                res.pkg = null;
13875                res.removedInfo = null;
13876                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13877                    args.doPreInstall(res.returnCode);
13878                    synchronized (mInstallLock) {
13879                        installPackageTracedLI(args, res);
13880                    }
13881                    args.doPostInstall(res.returnCode, res.uid);
13882                }
13883
13884                // A restore should be performed at this point if (a) the install
13885                // succeeded, (b) the operation is not an update, and (c) the new
13886                // package has not opted out of backup participation.
13887                final boolean update = res.removedInfo != null
13888                        && res.removedInfo.removedPackage != null;
13889                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13890                boolean doRestore = !update
13891                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13892
13893                // Set up the post-install work request bookkeeping.  This will be used
13894                // and cleaned up by the post-install event handling regardless of whether
13895                // there's a restore pass performed.  Token values are >= 1.
13896                int token;
13897                if (mNextInstallToken < 0) mNextInstallToken = 1;
13898                token = mNextInstallToken++;
13899
13900                PostInstallData data = new PostInstallData(args, res);
13901                mRunningInstalls.put(token, data);
13902                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13903
13904                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13905                    // Pass responsibility to the Backup Manager.  It will perform a
13906                    // restore if appropriate, then pass responsibility back to the
13907                    // Package Manager to run the post-install observer callbacks
13908                    // and broadcasts.
13909                    IBackupManager bm = IBackupManager.Stub.asInterface(
13910                            ServiceManager.getService(Context.BACKUP_SERVICE));
13911                    if (bm != null) {
13912                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13913                                + " to BM for possible restore");
13914                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13915                        try {
13916                            // TODO: http://b/22388012
13917                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13918                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13919                            } else {
13920                                doRestore = false;
13921                            }
13922                        } catch (RemoteException e) {
13923                            // can't happen; the backup manager is local
13924                        } catch (Exception e) {
13925                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13926                            doRestore = false;
13927                        }
13928                    } else {
13929                        Slog.e(TAG, "Backup Manager not found!");
13930                        doRestore = false;
13931                    }
13932                }
13933
13934                if (!doRestore) {
13935                    // No restore possible, or the Backup Manager was mysteriously not
13936                    // available -- just fire the post-install work request directly.
13937                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13938
13939                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13940
13941                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13942                    mHandler.sendMessage(msg);
13943                }
13944            }
13945        });
13946    }
13947
13948    /**
13949     * Callback from PackageSettings whenever an app is first transitioned out of the
13950     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13951     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13952     * here whether the app is the target of an ongoing install, and only send the
13953     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13954     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13955     * handling.
13956     */
13957    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13958        // Serialize this with the rest of the install-process message chain.  In the
13959        // restore-at-install case, this Runnable will necessarily run before the
13960        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13961        // are coherent.  In the non-restore case, the app has already completed install
13962        // and been launched through some other means, so it is not in a problematic
13963        // state for observers to see the FIRST_LAUNCH signal.
13964        mHandler.post(new Runnable() {
13965            @Override
13966            public void run() {
13967                for (int i = 0; i < mRunningInstalls.size(); i++) {
13968                    final PostInstallData data = mRunningInstalls.valueAt(i);
13969                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13970                        continue;
13971                    }
13972                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13973                        // right package; but is it for the right user?
13974                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13975                            if (userId == data.res.newUsers[uIndex]) {
13976                                if (DEBUG_BACKUP) {
13977                                    Slog.i(TAG, "Package " + pkgName
13978                                            + " being restored so deferring FIRST_LAUNCH");
13979                                }
13980                                return;
13981                            }
13982                        }
13983                    }
13984                }
13985                // didn't find it, so not being restored
13986                if (DEBUG_BACKUP) {
13987                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13988                }
13989                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13990            }
13991        });
13992    }
13993
13994    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13995        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13996                installerPkg, null, userIds);
13997    }
13998
13999    private abstract class HandlerParams {
14000        private static final int MAX_RETRIES = 4;
14001
14002        /**
14003         * Number of times startCopy() has been attempted and had a non-fatal
14004         * error.
14005         */
14006        private int mRetries = 0;
14007
14008        /** User handle for the user requesting the information or installation. */
14009        private final UserHandle mUser;
14010        String traceMethod;
14011        int traceCookie;
14012
14013        HandlerParams(UserHandle user) {
14014            mUser = user;
14015        }
14016
14017        UserHandle getUser() {
14018            return mUser;
14019        }
14020
14021        HandlerParams setTraceMethod(String traceMethod) {
14022            this.traceMethod = traceMethod;
14023            return this;
14024        }
14025
14026        HandlerParams setTraceCookie(int traceCookie) {
14027            this.traceCookie = traceCookie;
14028            return this;
14029        }
14030
14031        final boolean startCopy() {
14032            boolean res;
14033            try {
14034                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14035
14036                if (++mRetries > MAX_RETRIES) {
14037                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14038                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14039                    handleServiceError();
14040                    return false;
14041                } else {
14042                    handleStartCopy();
14043                    res = true;
14044                }
14045            } catch (RemoteException e) {
14046                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14047                mHandler.sendEmptyMessage(MCS_RECONNECT);
14048                res = false;
14049            }
14050            handleReturnCode();
14051            return res;
14052        }
14053
14054        final void serviceError() {
14055            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14056            handleServiceError();
14057            handleReturnCode();
14058        }
14059
14060        abstract void handleStartCopy() throws RemoteException;
14061        abstract void handleServiceError();
14062        abstract void handleReturnCode();
14063    }
14064
14065    class MeasureParams extends HandlerParams {
14066        private final PackageStats mStats;
14067        private boolean mSuccess;
14068
14069        private final IPackageStatsObserver mObserver;
14070
14071        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14072            super(new UserHandle(stats.userHandle));
14073            mObserver = observer;
14074            mStats = stats;
14075        }
14076
14077        @Override
14078        public String toString() {
14079            return "MeasureParams{"
14080                + Integer.toHexString(System.identityHashCode(this))
14081                + " " + mStats.packageName + "}";
14082        }
14083
14084        @Override
14085        void handleStartCopy() throws RemoteException {
14086            synchronized (mInstallLock) {
14087                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14088            }
14089
14090            if (mSuccess) {
14091                boolean mounted = false;
14092                try {
14093                    final String status = Environment.getExternalStorageState();
14094                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14095                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14096                } catch (Exception e) {
14097                }
14098
14099                if (mounted) {
14100                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14101
14102                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14103                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14104
14105                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14106                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14107
14108                    // Always subtract cache size, since it's a subdirectory
14109                    mStats.externalDataSize -= mStats.externalCacheSize;
14110
14111                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14112                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14113
14114                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14115                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14116                }
14117            }
14118        }
14119
14120        @Override
14121        void handleReturnCode() {
14122            if (mObserver != null) {
14123                try {
14124                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14125                } catch (RemoteException e) {
14126                    Slog.i(TAG, "Observer no longer exists.");
14127                }
14128            }
14129        }
14130
14131        @Override
14132        void handleServiceError() {
14133            Slog.e(TAG, "Could not measure application " + mStats.packageName
14134                            + " external storage");
14135        }
14136    }
14137
14138    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14139            throws RemoteException {
14140        long result = 0;
14141        for (File path : paths) {
14142            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14143        }
14144        return result;
14145    }
14146
14147    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14148        for (File path : paths) {
14149            try {
14150                mcs.clearDirectory(path.getAbsolutePath());
14151            } catch (RemoteException e) {
14152            }
14153        }
14154    }
14155
14156    static class OriginInfo {
14157        /**
14158         * Location where install is coming from, before it has been
14159         * copied/renamed into place. This could be a single monolithic APK
14160         * file, or a cluster directory. This location may be untrusted.
14161         */
14162        final File file;
14163        final String cid;
14164
14165        /**
14166         * Flag indicating that {@link #file} or {@link #cid} has already been
14167         * staged, meaning downstream users don't need to defensively copy the
14168         * contents.
14169         */
14170        final boolean staged;
14171
14172        /**
14173         * Flag indicating that {@link #file} or {@link #cid} is an already
14174         * installed app that is being moved.
14175         */
14176        final boolean existing;
14177
14178        final String resolvedPath;
14179        final File resolvedFile;
14180
14181        static OriginInfo fromNothing() {
14182            return new OriginInfo(null, null, false, false);
14183        }
14184
14185        static OriginInfo fromUntrustedFile(File file) {
14186            return new OriginInfo(file, null, false, false);
14187        }
14188
14189        static OriginInfo fromExistingFile(File file) {
14190            return new OriginInfo(file, null, false, true);
14191        }
14192
14193        static OriginInfo fromStagedFile(File file) {
14194            return new OriginInfo(file, null, true, false);
14195        }
14196
14197        static OriginInfo fromStagedContainer(String cid) {
14198            return new OriginInfo(null, cid, true, false);
14199        }
14200
14201        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14202            this.file = file;
14203            this.cid = cid;
14204            this.staged = staged;
14205            this.existing = existing;
14206
14207            if (cid != null) {
14208                resolvedPath = PackageHelper.getSdDir(cid);
14209                resolvedFile = new File(resolvedPath);
14210            } else if (file != null) {
14211                resolvedPath = file.getAbsolutePath();
14212                resolvedFile = file;
14213            } else {
14214                resolvedPath = null;
14215                resolvedFile = null;
14216            }
14217        }
14218    }
14219
14220    static class MoveInfo {
14221        final int moveId;
14222        final String fromUuid;
14223        final String toUuid;
14224        final String packageName;
14225        final String dataAppName;
14226        final int appId;
14227        final String seinfo;
14228        final int targetSdkVersion;
14229
14230        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14231                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14232            this.moveId = moveId;
14233            this.fromUuid = fromUuid;
14234            this.toUuid = toUuid;
14235            this.packageName = packageName;
14236            this.dataAppName = dataAppName;
14237            this.appId = appId;
14238            this.seinfo = seinfo;
14239            this.targetSdkVersion = targetSdkVersion;
14240        }
14241    }
14242
14243    static class VerificationInfo {
14244        /** A constant used to indicate that a uid value is not present. */
14245        public static final int NO_UID = -1;
14246
14247        /** URI referencing where the package was downloaded from. */
14248        final Uri originatingUri;
14249
14250        /** HTTP referrer URI associated with the originatingURI. */
14251        final Uri referrer;
14252
14253        /** UID of the application that the install request originated from. */
14254        final int originatingUid;
14255
14256        /** UID of application requesting the install */
14257        final int installerUid;
14258
14259        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14260            this.originatingUri = originatingUri;
14261            this.referrer = referrer;
14262            this.originatingUid = originatingUid;
14263            this.installerUid = installerUid;
14264        }
14265    }
14266
14267    class InstallParams extends HandlerParams {
14268        final OriginInfo origin;
14269        final MoveInfo move;
14270        final IPackageInstallObserver2 observer;
14271        int installFlags;
14272        final String installerPackageName;
14273        final String volumeUuid;
14274        private InstallArgs mArgs;
14275        private int mRet;
14276        final String packageAbiOverride;
14277        final String[] grantedRuntimePermissions;
14278        final VerificationInfo verificationInfo;
14279        final Certificate[][] certificates;
14280        final int installReason;
14281
14282        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14283                int installFlags, String installerPackageName, String volumeUuid,
14284                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14285                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14286            super(user);
14287            this.origin = origin;
14288            this.move = move;
14289            this.observer = observer;
14290            this.installFlags = installFlags;
14291            this.installerPackageName = installerPackageName;
14292            this.volumeUuid = volumeUuid;
14293            this.verificationInfo = verificationInfo;
14294            this.packageAbiOverride = packageAbiOverride;
14295            this.grantedRuntimePermissions = grantedPermissions;
14296            this.certificates = certificates;
14297            this.installReason = installReason;
14298        }
14299
14300        @Override
14301        public String toString() {
14302            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14303                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14304        }
14305
14306        private int installLocationPolicy(PackageInfoLite pkgLite) {
14307            String packageName = pkgLite.packageName;
14308            int installLocation = pkgLite.installLocation;
14309            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14310            // reader
14311            synchronized (mPackages) {
14312                // Currently installed package which the new package is attempting to replace or
14313                // null if no such package is installed.
14314                PackageParser.Package installedPkg = mPackages.get(packageName);
14315                // Package which currently owns the data which the new package will own if installed.
14316                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14317                // will be null whereas dataOwnerPkg will contain information about the package
14318                // which was uninstalled while keeping its data.
14319                PackageParser.Package dataOwnerPkg = installedPkg;
14320                if (dataOwnerPkg  == null) {
14321                    PackageSetting ps = mSettings.mPackages.get(packageName);
14322                    if (ps != null) {
14323                        dataOwnerPkg = ps.pkg;
14324                    }
14325                }
14326
14327                if (dataOwnerPkg != null) {
14328                    // If installed, the package will get access to data left on the device by its
14329                    // predecessor. As a security measure, this is permited only if this is not a
14330                    // version downgrade or if the predecessor package is marked as debuggable and
14331                    // a downgrade is explicitly requested.
14332                    //
14333                    // On debuggable platform builds, downgrades are permitted even for
14334                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14335                    // not offer security guarantees and thus it's OK to disable some security
14336                    // mechanisms to make debugging/testing easier on those builds. However, even on
14337                    // debuggable builds downgrades of packages are permitted only if requested via
14338                    // installFlags. This is because we aim to keep the behavior of debuggable
14339                    // platform builds as close as possible to the behavior of non-debuggable
14340                    // platform builds.
14341                    final boolean downgradeRequested =
14342                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14343                    final boolean packageDebuggable =
14344                                (dataOwnerPkg.applicationInfo.flags
14345                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14346                    final boolean downgradePermitted =
14347                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14348                    if (!downgradePermitted) {
14349                        try {
14350                            checkDowngrade(dataOwnerPkg, pkgLite);
14351                        } catch (PackageManagerException e) {
14352                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14353                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14354                        }
14355                    }
14356                }
14357
14358                if (installedPkg != null) {
14359                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14360                        // Check for updated system application.
14361                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14362                            if (onSd) {
14363                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14364                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14365                            }
14366                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14367                        } else {
14368                            if (onSd) {
14369                                // Install flag overrides everything.
14370                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14371                            }
14372                            // If current upgrade specifies particular preference
14373                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14374                                // Application explicitly specified internal.
14375                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14376                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14377                                // App explictly prefers external. Let policy decide
14378                            } else {
14379                                // Prefer previous location
14380                                if (isExternal(installedPkg)) {
14381                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14382                                }
14383                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14384                            }
14385                        }
14386                    } else {
14387                        // Invalid install. Return error code
14388                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14389                    }
14390                }
14391            }
14392            // All the special cases have been taken care of.
14393            // Return result based on recommended install location.
14394            if (onSd) {
14395                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14396            }
14397            return pkgLite.recommendedInstallLocation;
14398        }
14399
14400        /*
14401         * Invoke remote method to get package information and install
14402         * location values. Override install location based on default
14403         * policy if needed and then create install arguments based
14404         * on the install location.
14405         */
14406        public void handleStartCopy() throws RemoteException {
14407            int ret = PackageManager.INSTALL_SUCCEEDED;
14408
14409            // If we're already staged, we've firmly committed to an install location
14410            if (origin.staged) {
14411                if (origin.file != null) {
14412                    installFlags |= PackageManager.INSTALL_INTERNAL;
14413                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14414                } else if (origin.cid != null) {
14415                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14416                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14417                } else {
14418                    throw new IllegalStateException("Invalid stage location");
14419                }
14420            }
14421
14422            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14423            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14424            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14425            PackageInfoLite pkgLite = null;
14426
14427            if (onInt && onSd) {
14428                // Check if both bits are set.
14429                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14430                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14431            } else if (onSd && ephemeral) {
14432                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14433                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14434            } else {
14435                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14436                        packageAbiOverride);
14437
14438                if (DEBUG_EPHEMERAL && ephemeral) {
14439                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14440                }
14441
14442                /*
14443                 * If we have too little free space, try to free cache
14444                 * before giving up.
14445                 */
14446                if (!origin.staged && pkgLite.recommendedInstallLocation
14447                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14448                    // TODO: focus freeing disk space on the target device
14449                    final StorageManager storage = StorageManager.from(mContext);
14450                    final long lowThreshold = storage.getStorageLowBytes(
14451                            Environment.getDataDirectory());
14452
14453                    final long sizeBytes = mContainerService.calculateInstalledSize(
14454                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14455
14456                    try {
14457                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14458                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14459                                installFlags, packageAbiOverride);
14460                    } catch (InstallerException e) {
14461                        Slog.w(TAG, "Failed to free cache", e);
14462                    }
14463
14464                    /*
14465                     * The cache free must have deleted the file we
14466                     * downloaded to install.
14467                     *
14468                     * TODO: fix the "freeCache" call to not delete
14469                     *       the file we care about.
14470                     */
14471                    if (pkgLite.recommendedInstallLocation
14472                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14473                        pkgLite.recommendedInstallLocation
14474                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14475                    }
14476                }
14477            }
14478
14479            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14480                int loc = pkgLite.recommendedInstallLocation;
14481                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14482                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14483                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14484                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14485                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14486                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14487                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14488                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14489                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14490                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14491                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14492                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14493                } else {
14494                    // Override with defaults if needed.
14495                    loc = installLocationPolicy(pkgLite);
14496                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14497                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14498                    } else if (!onSd && !onInt) {
14499                        // Override install location with flags
14500                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14501                            // Set the flag to install on external media.
14502                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14503                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14504                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14505                            if (DEBUG_EPHEMERAL) {
14506                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14507                            }
14508                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14509                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14510                                    |PackageManager.INSTALL_INTERNAL);
14511                        } else {
14512                            // Make sure the flag for installing on external
14513                            // media is unset
14514                            installFlags |= PackageManager.INSTALL_INTERNAL;
14515                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14516                        }
14517                    }
14518                }
14519            }
14520
14521            final InstallArgs args = createInstallArgs(this);
14522            mArgs = args;
14523
14524            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14525                // TODO: http://b/22976637
14526                // Apps installed for "all" users use the device owner to verify the app
14527                UserHandle verifierUser = getUser();
14528                if (verifierUser == UserHandle.ALL) {
14529                    verifierUser = UserHandle.SYSTEM;
14530                }
14531
14532                /*
14533                 * Determine if we have any installed package verifiers. If we
14534                 * do, then we'll defer to them to verify the packages.
14535                 */
14536                final int requiredUid = mRequiredVerifierPackage == null ? -1
14537                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14538                                verifierUser.getIdentifier());
14539                if (!origin.existing && requiredUid != -1
14540                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14541                    final Intent verification = new Intent(
14542                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14543                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14544                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14545                            PACKAGE_MIME_TYPE);
14546                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14547
14548                    // Query all live verifiers based on current user state
14549                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14550                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14551
14552                    if (DEBUG_VERIFY) {
14553                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14554                                + verification.toString() + " with " + pkgLite.verifiers.length
14555                                + " optional verifiers");
14556                    }
14557
14558                    final int verificationId = mPendingVerificationToken++;
14559
14560                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14561
14562                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14563                            installerPackageName);
14564
14565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14566                            installFlags);
14567
14568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14569                            pkgLite.packageName);
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14572                            pkgLite.versionCode);
14573
14574                    if (verificationInfo != null) {
14575                        if (verificationInfo.originatingUri != null) {
14576                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14577                                    verificationInfo.originatingUri);
14578                        }
14579                        if (verificationInfo.referrer != null) {
14580                            verification.putExtra(Intent.EXTRA_REFERRER,
14581                                    verificationInfo.referrer);
14582                        }
14583                        if (verificationInfo.originatingUid >= 0) {
14584                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14585                                    verificationInfo.originatingUid);
14586                        }
14587                        if (verificationInfo.installerUid >= 0) {
14588                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14589                                    verificationInfo.installerUid);
14590                        }
14591                    }
14592
14593                    final PackageVerificationState verificationState = new PackageVerificationState(
14594                            requiredUid, args);
14595
14596                    mPendingVerification.append(verificationId, verificationState);
14597
14598                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14599                            receivers, verificationState);
14600
14601                    /*
14602                     * If any sufficient verifiers were listed in the package
14603                     * manifest, attempt to ask them.
14604                     */
14605                    if (sufficientVerifiers != null) {
14606                        final int N = sufficientVerifiers.size();
14607                        if (N == 0) {
14608                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14609                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14610                        } else {
14611                            for (int i = 0; i < N; i++) {
14612                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14613
14614                                final Intent sufficientIntent = new Intent(verification);
14615                                sufficientIntent.setComponent(verifierComponent);
14616                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14617                            }
14618                        }
14619                    }
14620
14621                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14622                            mRequiredVerifierPackage, receivers);
14623                    if (ret == PackageManager.INSTALL_SUCCEEDED
14624                            && mRequiredVerifierPackage != null) {
14625                        Trace.asyncTraceBegin(
14626                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14627                        /*
14628                         * Send the intent to the required verification agent,
14629                         * but only start the verification timeout after the
14630                         * target BroadcastReceivers have run.
14631                         */
14632                        verification.setComponent(requiredVerifierComponent);
14633                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14634                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14635                                new BroadcastReceiver() {
14636                                    @Override
14637                                    public void onReceive(Context context, Intent intent) {
14638                                        final Message msg = mHandler
14639                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14640                                        msg.arg1 = verificationId;
14641                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14642                                    }
14643                                }, null, 0, null, null);
14644
14645                        /*
14646                         * We don't want the copy to proceed until verification
14647                         * succeeds, so null out this field.
14648                         */
14649                        mArgs = null;
14650                    }
14651                } else {
14652                    /*
14653                     * No package verification is enabled, so immediately start
14654                     * the remote call to initiate copy using temporary file.
14655                     */
14656                    ret = args.copyApk(mContainerService, true);
14657                }
14658            }
14659
14660            mRet = ret;
14661        }
14662
14663        @Override
14664        void handleReturnCode() {
14665            // If mArgs is null, then MCS couldn't be reached. When it
14666            // reconnects, it will try again to install. At that point, this
14667            // will succeed.
14668            if (mArgs != null) {
14669                processPendingInstall(mArgs, mRet);
14670            }
14671        }
14672
14673        @Override
14674        void handleServiceError() {
14675            mArgs = createInstallArgs(this);
14676            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14677        }
14678
14679        public boolean isForwardLocked() {
14680            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14681        }
14682    }
14683
14684    /**
14685     * Used during creation of InstallArgs
14686     *
14687     * @param installFlags package installation flags
14688     * @return true if should be installed on external storage
14689     */
14690    private static boolean installOnExternalAsec(int installFlags) {
14691        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14692            return false;
14693        }
14694        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14695            return true;
14696        }
14697        return false;
14698    }
14699
14700    /**
14701     * Used during creation of InstallArgs
14702     *
14703     * @param installFlags package installation flags
14704     * @return true if should be installed as forward locked
14705     */
14706    private static boolean installForwardLocked(int installFlags) {
14707        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14708    }
14709
14710    private InstallArgs createInstallArgs(InstallParams params) {
14711        if (params.move != null) {
14712            return new MoveInstallArgs(params);
14713        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14714            return new AsecInstallArgs(params);
14715        } else {
14716            return new FileInstallArgs(params);
14717        }
14718    }
14719
14720    /**
14721     * Create args that describe an existing installed package. Typically used
14722     * when cleaning up old installs, or used as a move source.
14723     */
14724    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14725            String resourcePath, String[] instructionSets) {
14726        final boolean isInAsec;
14727        if (installOnExternalAsec(installFlags)) {
14728            /* Apps on SD card are always in ASEC containers. */
14729            isInAsec = true;
14730        } else if (installForwardLocked(installFlags)
14731                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14732            /*
14733             * Forward-locked apps are only in ASEC containers if they're the
14734             * new style
14735             */
14736            isInAsec = true;
14737        } else {
14738            isInAsec = false;
14739        }
14740
14741        if (isInAsec) {
14742            return new AsecInstallArgs(codePath, instructionSets,
14743                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14744        } else {
14745            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14746        }
14747    }
14748
14749    static abstract class InstallArgs {
14750        /** @see InstallParams#origin */
14751        final OriginInfo origin;
14752        /** @see InstallParams#move */
14753        final MoveInfo move;
14754
14755        final IPackageInstallObserver2 observer;
14756        // Always refers to PackageManager flags only
14757        final int installFlags;
14758        final String installerPackageName;
14759        final String volumeUuid;
14760        final UserHandle user;
14761        final String abiOverride;
14762        final String[] installGrantPermissions;
14763        /** If non-null, drop an async trace when the install completes */
14764        final String traceMethod;
14765        final int traceCookie;
14766        final Certificate[][] certificates;
14767        final int installReason;
14768
14769        // The list of instruction sets supported by this app. This is currently
14770        // only used during the rmdex() phase to clean up resources. We can get rid of this
14771        // if we move dex files under the common app path.
14772        /* nullable */ String[] instructionSets;
14773
14774        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14775                int installFlags, String installerPackageName, String volumeUuid,
14776                UserHandle user, String[] instructionSets,
14777                String abiOverride, String[] installGrantPermissions,
14778                String traceMethod, int traceCookie, Certificate[][] certificates,
14779                int installReason) {
14780            this.origin = origin;
14781            this.move = move;
14782            this.installFlags = installFlags;
14783            this.observer = observer;
14784            this.installerPackageName = installerPackageName;
14785            this.volumeUuid = volumeUuid;
14786            this.user = user;
14787            this.instructionSets = instructionSets;
14788            this.abiOverride = abiOverride;
14789            this.installGrantPermissions = installGrantPermissions;
14790            this.traceMethod = traceMethod;
14791            this.traceCookie = traceCookie;
14792            this.certificates = certificates;
14793            this.installReason = installReason;
14794        }
14795
14796        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14797        abstract int doPreInstall(int status);
14798
14799        /**
14800         * Rename package into final resting place. All paths on the given
14801         * scanned package should be updated to reflect the rename.
14802         */
14803        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14804        abstract int doPostInstall(int status, int uid);
14805
14806        /** @see PackageSettingBase#codePathString */
14807        abstract String getCodePath();
14808        /** @see PackageSettingBase#resourcePathString */
14809        abstract String getResourcePath();
14810
14811        // Need installer lock especially for dex file removal.
14812        abstract void cleanUpResourcesLI();
14813        abstract boolean doPostDeleteLI(boolean delete);
14814
14815        /**
14816         * Called before the source arguments are copied. This is used mostly
14817         * for MoveParams when it needs to read the source file to put it in the
14818         * destination.
14819         */
14820        int doPreCopy() {
14821            return PackageManager.INSTALL_SUCCEEDED;
14822        }
14823
14824        /**
14825         * Called after the source arguments are copied. This is used mostly for
14826         * MoveParams when it needs to read the source file to put it in the
14827         * destination.
14828         */
14829        int doPostCopy(int uid) {
14830            return PackageManager.INSTALL_SUCCEEDED;
14831        }
14832
14833        protected boolean isFwdLocked() {
14834            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14835        }
14836
14837        protected boolean isExternalAsec() {
14838            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14839        }
14840
14841        protected boolean isEphemeral() {
14842            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14843        }
14844
14845        UserHandle getUser() {
14846            return user;
14847        }
14848    }
14849
14850    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14851        if (!allCodePaths.isEmpty()) {
14852            if (instructionSets == null) {
14853                throw new IllegalStateException("instructionSet == null");
14854            }
14855            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14856            for (String codePath : allCodePaths) {
14857                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14858                    try {
14859                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14860                    } catch (InstallerException ignored) {
14861                    }
14862                }
14863            }
14864        }
14865    }
14866
14867    /**
14868     * Logic to handle installation of non-ASEC applications, including copying
14869     * and renaming logic.
14870     */
14871    class FileInstallArgs extends InstallArgs {
14872        private File codeFile;
14873        private File resourceFile;
14874
14875        // Example topology:
14876        // /data/app/com.example/base.apk
14877        // /data/app/com.example/split_foo.apk
14878        // /data/app/com.example/lib/arm/libfoo.so
14879        // /data/app/com.example/lib/arm64/libfoo.so
14880        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14881
14882        /** New install */
14883        FileInstallArgs(InstallParams params) {
14884            super(params.origin, params.move, params.observer, params.installFlags,
14885                    params.installerPackageName, params.volumeUuid,
14886                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14887                    params.grantedRuntimePermissions,
14888                    params.traceMethod, params.traceCookie, params.certificates,
14889                    params.installReason);
14890            if (isFwdLocked()) {
14891                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14892            }
14893        }
14894
14895        /** Existing install */
14896        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14897            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14898                    null, null, null, 0, null /*certificates*/,
14899                    PackageManager.INSTALL_REASON_UNKNOWN);
14900            this.codeFile = (codePath != null) ? new File(codePath) : null;
14901            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14902        }
14903
14904        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14905            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14906            try {
14907                return doCopyApk(imcs, temp);
14908            } finally {
14909                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14910            }
14911        }
14912
14913        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14914            if (origin.staged) {
14915                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14916                codeFile = origin.file;
14917                resourceFile = origin.file;
14918                return PackageManager.INSTALL_SUCCEEDED;
14919            }
14920
14921            try {
14922                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14923                final File tempDir =
14924                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14925                codeFile = tempDir;
14926                resourceFile = tempDir;
14927            } catch (IOException e) {
14928                Slog.w(TAG, "Failed to create copy file: " + e);
14929                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14930            }
14931
14932            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14933                @Override
14934                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14935                    if (!FileUtils.isValidExtFilename(name)) {
14936                        throw new IllegalArgumentException("Invalid filename: " + name);
14937                    }
14938                    try {
14939                        final File file = new File(codeFile, name);
14940                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14941                                O_RDWR | O_CREAT, 0644);
14942                        Os.chmod(file.getAbsolutePath(), 0644);
14943                        return new ParcelFileDescriptor(fd);
14944                    } catch (ErrnoException e) {
14945                        throw new RemoteException("Failed to open: " + e.getMessage());
14946                    }
14947                }
14948            };
14949
14950            int ret = PackageManager.INSTALL_SUCCEEDED;
14951            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14952            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14953                Slog.e(TAG, "Failed to copy package");
14954                return ret;
14955            }
14956
14957            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14958            NativeLibraryHelper.Handle handle = null;
14959            try {
14960                handle = NativeLibraryHelper.Handle.create(codeFile);
14961                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14962                        abiOverride);
14963            } catch (IOException e) {
14964                Slog.e(TAG, "Copying native libraries failed", e);
14965                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14966            } finally {
14967                IoUtils.closeQuietly(handle);
14968            }
14969
14970            return ret;
14971        }
14972
14973        int doPreInstall(int status) {
14974            if (status != PackageManager.INSTALL_SUCCEEDED) {
14975                cleanUp();
14976            }
14977            return status;
14978        }
14979
14980        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14981            if (status != PackageManager.INSTALL_SUCCEEDED) {
14982                cleanUp();
14983                return false;
14984            }
14985
14986            final File targetDir = codeFile.getParentFile();
14987            final File beforeCodeFile = codeFile;
14988            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14989
14990            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14991            try {
14992                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14993            } catch (ErrnoException e) {
14994                Slog.w(TAG, "Failed to rename", e);
14995                return false;
14996            }
14997
14998            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14999                Slog.w(TAG, "Failed to restorecon");
15000                return false;
15001            }
15002
15003            // Reflect the rename internally
15004            codeFile = afterCodeFile;
15005            resourceFile = afterCodeFile;
15006
15007            // Reflect the rename in scanned details
15008            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15009            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15010                    afterCodeFile, pkg.baseCodePath));
15011            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15012                    afterCodeFile, pkg.splitCodePaths));
15013
15014            // Reflect the rename in app info
15015            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15016            pkg.setApplicationInfoCodePath(pkg.codePath);
15017            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15018            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15019            pkg.setApplicationInfoResourcePath(pkg.codePath);
15020            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15021            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15022
15023            return true;
15024        }
15025
15026        int doPostInstall(int status, int uid) {
15027            if (status != PackageManager.INSTALL_SUCCEEDED) {
15028                cleanUp();
15029            }
15030            return status;
15031        }
15032
15033        @Override
15034        String getCodePath() {
15035            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15036        }
15037
15038        @Override
15039        String getResourcePath() {
15040            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15041        }
15042
15043        private boolean cleanUp() {
15044            if (codeFile == null || !codeFile.exists()) {
15045                return false;
15046            }
15047
15048            removeCodePathLI(codeFile);
15049
15050            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15051                resourceFile.delete();
15052            }
15053
15054            return true;
15055        }
15056
15057        void cleanUpResourcesLI() {
15058            // Try enumerating all code paths before deleting
15059            List<String> allCodePaths = Collections.EMPTY_LIST;
15060            if (codeFile != null && codeFile.exists()) {
15061                try {
15062                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15063                    allCodePaths = pkg.getAllCodePaths();
15064                } catch (PackageParserException e) {
15065                    // Ignored; we tried our best
15066                }
15067            }
15068
15069            cleanUp();
15070            removeDexFiles(allCodePaths, instructionSets);
15071        }
15072
15073        boolean doPostDeleteLI(boolean delete) {
15074            // XXX err, shouldn't we respect the delete flag?
15075            cleanUpResourcesLI();
15076            return true;
15077        }
15078    }
15079
15080    private boolean isAsecExternal(String cid) {
15081        final String asecPath = PackageHelper.getSdFilesystem(cid);
15082        return !asecPath.startsWith(mAsecInternalPath);
15083    }
15084
15085    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15086            PackageManagerException {
15087        if (copyRet < 0) {
15088            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15089                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15090                throw new PackageManagerException(copyRet, message);
15091            }
15092        }
15093    }
15094
15095    /**
15096     * Extract the StorageManagerService "container ID" from the full code path of an
15097     * .apk.
15098     */
15099    static String cidFromCodePath(String fullCodePath) {
15100        int eidx = fullCodePath.lastIndexOf("/");
15101        String subStr1 = fullCodePath.substring(0, eidx);
15102        int sidx = subStr1.lastIndexOf("/");
15103        return subStr1.substring(sidx+1, eidx);
15104    }
15105
15106    /**
15107     * Logic to handle installation of ASEC applications, including copying and
15108     * renaming logic.
15109     */
15110    class AsecInstallArgs extends InstallArgs {
15111        static final String RES_FILE_NAME = "pkg.apk";
15112        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15113
15114        String cid;
15115        String packagePath;
15116        String resourcePath;
15117
15118        /** New install */
15119        AsecInstallArgs(InstallParams params) {
15120            super(params.origin, params.move, params.observer, params.installFlags,
15121                    params.installerPackageName, params.volumeUuid,
15122                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15123                    params.grantedRuntimePermissions,
15124                    params.traceMethod, params.traceCookie, params.certificates,
15125                    params.installReason);
15126        }
15127
15128        /** Existing install */
15129        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15130                        boolean isExternal, boolean isForwardLocked) {
15131            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15132                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15133                    instructionSets, null, null, null, 0, null /*certificates*/,
15134                    PackageManager.INSTALL_REASON_UNKNOWN);
15135            // Hackily pretend we're still looking at a full code path
15136            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15137                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15138            }
15139
15140            // Extract cid from fullCodePath
15141            int eidx = fullCodePath.lastIndexOf("/");
15142            String subStr1 = fullCodePath.substring(0, eidx);
15143            int sidx = subStr1.lastIndexOf("/");
15144            cid = subStr1.substring(sidx+1, eidx);
15145            setMountPath(subStr1);
15146        }
15147
15148        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15149            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15150                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15151                    instructionSets, null, null, null, 0, null /*certificates*/,
15152                    PackageManager.INSTALL_REASON_UNKNOWN);
15153            this.cid = cid;
15154            setMountPath(PackageHelper.getSdDir(cid));
15155        }
15156
15157        void createCopyFile() {
15158            cid = mInstallerService.allocateExternalStageCidLegacy();
15159        }
15160
15161        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15162            if (origin.staged && origin.cid != null) {
15163                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15164                cid = origin.cid;
15165                setMountPath(PackageHelper.getSdDir(cid));
15166                return PackageManager.INSTALL_SUCCEEDED;
15167            }
15168
15169            if (temp) {
15170                createCopyFile();
15171            } else {
15172                /*
15173                 * Pre-emptively destroy the container since it's destroyed if
15174                 * copying fails due to it existing anyway.
15175                 */
15176                PackageHelper.destroySdDir(cid);
15177            }
15178
15179            final String newMountPath = imcs.copyPackageToContainer(
15180                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15181                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15182
15183            if (newMountPath != null) {
15184                setMountPath(newMountPath);
15185                return PackageManager.INSTALL_SUCCEEDED;
15186            } else {
15187                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15188            }
15189        }
15190
15191        @Override
15192        String getCodePath() {
15193            return packagePath;
15194        }
15195
15196        @Override
15197        String getResourcePath() {
15198            return resourcePath;
15199        }
15200
15201        int doPreInstall(int status) {
15202            if (status != PackageManager.INSTALL_SUCCEEDED) {
15203                // Destroy container
15204                PackageHelper.destroySdDir(cid);
15205            } else {
15206                boolean mounted = PackageHelper.isContainerMounted(cid);
15207                if (!mounted) {
15208                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15209                            Process.SYSTEM_UID);
15210                    if (newMountPath != null) {
15211                        setMountPath(newMountPath);
15212                    } else {
15213                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15214                    }
15215                }
15216            }
15217            return status;
15218        }
15219
15220        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15221            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15222            String newMountPath = null;
15223            if (PackageHelper.isContainerMounted(cid)) {
15224                // Unmount the container
15225                if (!PackageHelper.unMountSdDir(cid)) {
15226                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15227                    return false;
15228                }
15229            }
15230            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15231                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15232                        " which might be stale. Will try to clean up.");
15233                // Clean up the stale container and proceed to recreate.
15234                if (!PackageHelper.destroySdDir(newCacheId)) {
15235                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15236                    return false;
15237                }
15238                // Successfully cleaned up stale container. Try to rename again.
15239                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15240                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15241                            + " inspite of cleaning it up.");
15242                    return false;
15243                }
15244            }
15245            if (!PackageHelper.isContainerMounted(newCacheId)) {
15246                Slog.w(TAG, "Mounting container " + newCacheId);
15247                newMountPath = PackageHelper.mountSdDir(newCacheId,
15248                        getEncryptKey(), Process.SYSTEM_UID);
15249            } else {
15250                newMountPath = PackageHelper.getSdDir(newCacheId);
15251            }
15252            if (newMountPath == null) {
15253                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15254                return false;
15255            }
15256            Log.i(TAG, "Succesfully renamed " + cid +
15257                    " to " + newCacheId +
15258                    " at new path: " + newMountPath);
15259            cid = newCacheId;
15260
15261            final File beforeCodeFile = new File(packagePath);
15262            setMountPath(newMountPath);
15263            final File afterCodeFile = new File(packagePath);
15264
15265            // Reflect the rename in scanned details
15266            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15267            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15268                    afterCodeFile, pkg.baseCodePath));
15269            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15270                    afterCodeFile, pkg.splitCodePaths));
15271
15272            // Reflect the rename in app info
15273            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15274            pkg.setApplicationInfoCodePath(pkg.codePath);
15275            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15276            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15277            pkg.setApplicationInfoResourcePath(pkg.codePath);
15278            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15279            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15280
15281            return true;
15282        }
15283
15284        private void setMountPath(String mountPath) {
15285            final File mountFile = new File(mountPath);
15286
15287            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15288            if (monolithicFile.exists()) {
15289                packagePath = monolithicFile.getAbsolutePath();
15290                if (isFwdLocked()) {
15291                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15292                } else {
15293                    resourcePath = packagePath;
15294                }
15295            } else {
15296                packagePath = mountFile.getAbsolutePath();
15297                resourcePath = packagePath;
15298            }
15299        }
15300
15301        int doPostInstall(int status, int uid) {
15302            if (status != PackageManager.INSTALL_SUCCEEDED) {
15303                cleanUp();
15304            } else {
15305                final int groupOwner;
15306                final String protectedFile;
15307                if (isFwdLocked()) {
15308                    groupOwner = UserHandle.getSharedAppGid(uid);
15309                    protectedFile = RES_FILE_NAME;
15310                } else {
15311                    groupOwner = -1;
15312                    protectedFile = null;
15313                }
15314
15315                if (uid < Process.FIRST_APPLICATION_UID
15316                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15317                    Slog.e(TAG, "Failed to finalize " + cid);
15318                    PackageHelper.destroySdDir(cid);
15319                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15320                }
15321
15322                boolean mounted = PackageHelper.isContainerMounted(cid);
15323                if (!mounted) {
15324                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15325                }
15326            }
15327            return status;
15328        }
15329
15330        private void cleanUp() {
15331            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15332
15333            // Destroy secure container
15334            PackageHelper.destroySdDir(cid);
15335        }
15336
15337        private List<String> getAllCodePaths() {
15338            final File codeFile = new File(getCodePath());
15339            if (codeFile != null && codeFile.exists()) {
15340                try {
15341                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15342                    return pkg.getAllCodePaths();
15343                } catch (PackageParserException e) {
15344                    // Ignored; we tried our best
15345                }
15346            }
15347            return Collections.EMPTY_LIST;
15348        }
15349
15350        void cleanUpResourcesLI() {
15351            // Enumerate all code paths before deleting
15352            cleanUpResourcesLI(getAllCodePaths());
15353        }
15354
15355        private void cleanUpResourcesLI(List<String> allCodePaths) {
15356            cleanUp();
15357            removeDexFiles(allCodePaths, instructionSets);
15358        }
15359
15360        String getPackageName() {
15361            return getAsecPackageName(cid);
15362        }
15363
15364        boolean doPostDeleteLI(boolean delete) {
15365            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15366            final List<String> allCodePaths = getAllCodePaths();
15367            boolean mounted = PackageHelper.isContainerMounted(cid);
15368            if (mounted) {
15369                // Unmount first
15370                if (PackageHelper.unMountSdDir(cid)) {
15371                    mounted = false;
15372                }
15373            }
15374            if (!mounted && delete) {
15375                cleanUpResourcesLI(allCodePaths);
15376            }
15377            return !mounted;
15378        }
15379
15380        @Override
15381        int doPreCopy() {
15382            if (isFwdLocked()) {
15383                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15384                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15385                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15386                }
15387            }
15388
15389            return PackageManager.INSTALL_SUCCEEDED;
15390        }
15391
15392        @Override
15393        int doPostCopy(int uid) {
15394            if (isFwdLocked()) {
15395                if (uid < Process.FIRST_APPLICATION_UID
15396                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15397                                RES_FILE_NAME)) {
15398                    Slog.e(TAG, "Failed to finalize " + cid);
15399                    PackageHelper.destroySdDir(cid);
15400                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15401                }
15402            }
15403
15404            return PackageManager.INSTALL_SUCCEEDED;
15405        }
15406    }
15407
15408    /**
15409     * Logic to handle movement of existing installed applications.
15410     */
15411    class MoveInstallArgs extends InstallArgs {
15412        private File codeFile;
15413        private File resourceFile;
15414
15415        /** New install */
15416        MoveInstallArgs(InstallParams params) {
15417            super(params.origin, params.move, params.observer, params.installFlags,
15418                    params.installerPackageName, params.volumeUuid,
15419                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15420                    params.grantedRuntimePermissions,
15421                    params.traceMethod, params.traceCookie, params.certificates,
15422                    params.installReason);
15423        }
15424
15425        int copyApk(IMediaContainerService imcs, boolean temp) {
15426            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15427                    + move.fromUuid + " to " + move.toUuid);
15428            synchronized (mInstaller) {
15429                try {
15430                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15431                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15432                } catch (InstallerException e) {
15433                    Slog.w(TAG, "Failed to move app", e);
15434                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15435                }
15436            }
15437
15438            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15439            resourceFile = codeFile;
15440            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15441
15442            return PackageManager.INSTALL_SUCCEEDED;
15443        }
15444
15445        int doPreInstall(int status) {
15446            if (status != PackageManager.INSTALL_SUCCEEDED) {
15447                cleanUp(move.toUuid);
15448            }
15449            return status;
15450        }
15451
15452        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15453            if (status != PackageManager.INSTALL_SUCCEEDED) {
15454                cleanUp(move.toUuid);
15455                return false;
15456            }
15457
15458            // Reflect the move in app info
15459            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15460            pkg.setApplicationInfoCodePath(pkg.codePath);
15461            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15462            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15463            pkg.setApplicationInfoResourcePath(pkg.codePath);
15464            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15465            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15466
15467            return true;
15468        }
15469
15470        int doPostInstall(int status, int uid) {
15471            if (status == PackageManager.INSTALL_SUCCEEDED) {
15472                cleanUp(move.fromUuid);
15473            } else {
15474                cleanUp(move.toUuid);
15475            }
15476            return status;
15477        }
15478
15479        @Override
15480        String getCodePath() {
15481            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15482        }
15483
15484        @Override
15485        String getResourcePath() {
15486            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15487        }
15488
15489        private boolean cleanUp(String volumeUuid) {
15490            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15491                    move.dataAppName);
15492            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15493            final int[] userIds = sUserManager.getUserIds();
15494            synchronized (mInstallLock) {
15495                // Clean up both app data and code
15496                // All package moves are frozen until finished
15497                for (int userId : userIds) {
15498                    try {
15499                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15500                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15501                    } catch (InstallerException e) {
15502                        Slog.w(TAG, String.valueOf(e));
15503                    }
15504                }
15505                removeCodePathLI(codeFile);
15506            }
15507            return true;
15508        }
15509
15510        void cleanUpResourcesLI() {
15511            throw new UnsupportedOperationException();
15512        }
15513
15514        boolean doPostDeleteLI(boolean delete) {
15515            throw new UnsupportedOperationException();
15516        }
15517    }
15518
15519    static String getAsecPackageName(String packageCid) {
15520        int idx = packageCid.lastIndexOf("-");
15521        if (idx == -1) {
15522            return packageCid;
15523        }
15524        return packageCid.substring(0, idx);
15525    }
15526
15527    // Utility method used to create code paths based on package name and available index.
15528    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15529        String idxStr = "";
15530        int idx = 1;
15531        // Fall back to default value of idx=1 if prefix is not
15532        // part of oldCodePath
15533        if (oldCodePath != null) {
15534            String subStr = oldCodePath;
15535            // Drop the suffix right away
15536            if (suffix != null && subStr.endsWith(suffix)) {
15537                subStr = subStr.substring(0, subStr.length() - suffix.length());
15538            }
15539            // If oldCodePath already contains prefix find out the
15540            // ending index to either increment or decrement.
15541            int sidx = subStr.lastIndexOf(prefix);
15542            if (sidx != -1) {
15543                subStr = subStr.substring(sidx + prefix.length());
15544                if (subStr != null) {
15545                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15546                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15547                    }
15548                    try {
15549                        idx = Integer.parseInt(subStr);
15550                        if (idx <= 1) {
15551                            idx++;
15552                        } else {
15553                            idx--;
15554                        }
15555                    } catch(NumberFormatException e) {
15556                    }
15557                }
15558            }
15559        }
15560        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15561        return prefix + idxStr;
15562    }
15563
15564    private File getNextCodePath(File targetDir, String packageName) {
15565        File result;
15566        SecureRandom random = new SecureRandom();
15567        byte[] bytes = new byte[16];
15568        do {
15569            random.nextBytes(bytes);
15570            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15571            result = new File(targetDir, packageName + "-" + suffix);
15572        } while (result.exists());
15573        return result;
15574    }
15575
15576    // Utility method that returns the relative package path with respect
15577    // to the installation directory. Like say for /data/data/com.test-1.apk
15578    // string com.test-1 is returned.
15579    static String deriveCodePathName(String codePath) {
15580        if (codePath == null) {
15581            return null;
15582        }
15583        final File codeFile = new File(codePath);
15584        final String name = codeFile.getName();
15585        if (codeFile.isDirectory()) {
15586            return name;
15587        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15588            final int lastDot = name.lastIndexOf('.');
15589            return name.substring(0, lastDot);
15590        } else {
15591            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15592            return null;
15593        }
15594    }
15595
15596    static class PackageInstalledInfo {
15597        String name;
15598        int uid;
15599        // The set of users that originally had this package installed.
15600        int[] origUsers;
15601        // The set of users that now have this package installed.
15602        int[] newUsers;
15603        PackageParser.Package pkg;
15604        int returnCode;
15605        String returnMsg;
15606        PackageRemovedInfo removedInfo;
15607        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15608
15609        public void setError(int code, String msg) {
15610            setReturnCode(code);
15611            setReturnMessage(msg);
15612            Slog.w(TAG, msg);
15613        }
15614
15615        public void setError(String msg, PackageParserException e) {
15616            setReturnCode(e.error);
15617            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15618            Slog.w(TAG, msg, e);
15619        }
15620
15621        public void setError(String msg, PackageManagerException e) {
15622            returnCode = e.error;
15623            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15624            Slog.w(TAG, msg, e);
15625        }
15626
15627        public void setReturnCode(int returnCode) {
15628            this.returnCode = returnCode;
15629            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15630            for (int i = 0; i < childCount; i++) {
15631                addedChildPackages.valueAt(i).returnCode = returnCode;
15632            }
15633        }
15634
15635        private void setReturnMessage(String returnMsg) {
15636            this.returnMsg = returnMsg;
15637            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15638            for (int i = 0; i < childCount; i++) {
15639                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15640            }
15641        }
15642
15643        // In some error cases we want to convey more info back to the observer
15644        String origPackage;
15645        String origPermission;
15646    }
15647
15648    /*
15649     * Install a non-existing package.
15650     */
15651    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15652            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15653            PackageInstalledInfo res, int installReason) {
15654        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15655
15656        // Remember this for later, in case we need to rollback this install
15657        String pkgName = pkg.packageName;
15658
15659        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15660
15661        synchronized(mPackages) {
15662            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15663            if (renamedPackage != null) {
15664                // A package with the same name is already installed, though
15665                // it has been renamed to an older name.  The package we
15666                // are trying to install should be installed as an update to
15667                // the existing one, but that has not been requested, so bail.
15668                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15669                        + " without first uninstalling package running as "
15670                        + renamedPackage);
15671                return;
15672            }
15673            if (mPackages.containsKey(pkgName)) {
15674                // Don't allow installation over an existing package with the same name.
15675                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15676                        + " without first uninstalling.");
15677                return;
15678            }
15679        }
15680
15681        try {
15682            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15683                    System.currentTimeMillis(), user);
15684
15685            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15686
15687            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15688                prepareAppDataAfterInstallLIF(newPackage);
15689
15690            } else {
15691                // Remove package from internal structures, but keep around any
15692                // data that might have already existed
15693                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15694                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15695            }
15696        } catch (PackageManagerException e) {
15697            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15698        }
15699
15700        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15701    }
15702
15703    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15704        // Can't rotate keys during boot or if sharedUser.
15705        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15706                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15707            return false;
15708        }
15709        // app is using upgradeKeySets; make sure all are valid
15710        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15711        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15712        for (int i = 0; i < upgradeKeySets.length; i++) {
15713            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15714                Slog.wtf(TAG, "Package "
15715                         + (oldPs.name != null ? oldPs.name : "<null>")
15716                         + " contains upgrade-key-set reference to unknown key-set: "
15717                         + upgradeKeySets[i]
15718                         + " reverting to signatures check.");
15719                return false;
15720            }
15721        }
15722        return true;
15723    }
15724
15725    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15726        // Upgrade keysets are being used.  Determine if new package has a superset of the
15727        // required keys.
15728        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15729        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15730        for (int i = 0; i < upgradeKeySets.length; i++) {
15731            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15732            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15733                return true;
15734            }
15735        }
15736        return false;
15737    }
15738
15739    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15740        try (DigestInputStream digestStream =
15741                new DigestInputStream(new FileInputStream(file), digest)) {
15742            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15743        }
15744    }
15745
15746    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15747            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15748            int installReason) {
15749        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15750
15751        final PackageParser.Package oldPackage;
15752        final String pkgName = pkg.packageName;
15753        final int[] allUsers;
15754        final int[] installedUsers;
15755
15756        synchronized(mPackages) {
15757            oldPackage = mPackages.get(pkgName);
15758            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15759
15760            // don't allow upgrade to target a release SDK from a pre-release SDK
15761            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15762                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15763            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15764                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15765            if (oldTargetsPreRelease
15766                    && !newTargetsPreRelease
15767                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15768                Slog.w(TAG, "Can't install package targeting released sdk");
15769                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15770                return;
15771            }
15772
15773            // don't allow an upgrade from full to ephemeral
15774            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15775            if (isEphemeral && !oldIsEphemeral) {
15776                // can't downgrade from full to ephemeral
15777                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15778                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15779                return;
15780            }
15781
15782            // verify signatures are valid
15783            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15784            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15785                if (!checkUpgradeKeySetLP(ps, pkg)) {
15786                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15787                            "New package not signed by keys specified by upgrade-keysets: "
15788                                    + pkgName);
15789                    return;
15790                }
15791            } else {
15792                // default to original signature matching
15793                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15794                        != PackageManager.SIGNATURE_MATCH) {
15795                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15796                            "New package has a different signature: " + pkgName);
15797                    return;
15798                }
15799            }
15800
15801            // don't allow a system upgrade unless the upgrade hash matches
15802            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15803                byte[] digestBytes = null;
15804                try {
15805                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15806                    updateDigest(digest, new File(pkg.baseCodePath));
15807                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15808                        for (String path : pkg.splitCodePaths) {
15809                            updateDigest(digest, new File(path));
15810                        }
15811                    }
15812                    digestBytes = digest.digest();
15813                } catch (NoSuchAlgorithmException | IOException e) {
15814                    res.setError(INSTALL_FAILED_INVALID_APK,
15815                            "Could not compute hash: " + pkgName);
15816                    return;
15817                }
15818                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15819                    res.setError(INSTALL_FAILED_INVALID_APK,
15820                            "New package fails restrict-update check: " + pkgName);
15821                    return;
15822                }
15823                // retain upgrade restriction
15824                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15825            }
15826
15827            // Check for shared user id changes
15828            String invalidPackageName =
15829                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15830            if (invalidPackageName != null) {
15831                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15832                        "Package " + invalidPackageName + " tried to change user "
15833                                + oldPackage.mSharedUserId);
15834                return;
15835            }
15836
15837            // In case of rollback, remember per-user/profile install state
15838            allUsers = sUserManager.getUserIds();
15839            installedUsers = ps.queryInstalledUsers(allUsers, true);
15840        }
15841
15842        // Update what is removed
15843        res.removedInfo = new PackageRemovedInfo();
15844        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15845        res.removedInfo.removedPackage = oldPackage.packageName;
15846        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15847        res.removedInfo.isUpdate = true;
15848        res.removedInfo.origUsers = installedUsers;
15849        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15850        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15851        for (int i = 0; i < installedUsers.length; i++) {
15852            final int userId = installedUsers[i];
15853            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15854        }
15855
15856        final int childCount = (oldPackage.childPackages != null)
15857                ? oldPackage.childPackages.size() : 0;
15858        for (int i = 0; i < childCount; i++) {
15859            boolean childPackageUpdated = false;
15860            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15861            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15862            if (res.addedChildPackages != null) {
15863                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15864                if (childRes != null) {
15865                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15866                    childRes.removedInfo.removedPackage = childPkg.packageName;
15867                    childRes.removedInfo.isUpdate = true;
15868                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15869                    childPackageUpdated = true;
15870                }
15871            }
15872            if (!childPackageUpdated) {
15873                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15874                childRemovedRes.removedPackage = childPkg.packageName;
15875                childRemovedRes.isUpdate = false;
15876                childRemovedRes.dataRemoved = true;
15877                synchronized (mPackages) {
15878                    if (childPs != null) {
15879                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15880                    }
15881                }
15882                if (res.removedInfo.removedChildPackages == null) {
15883                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15884                }
15885                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15886            }
15887        }
15888
15889        boolean sysPkg = (isSystemApp(oldPackage));
15890        if (sysPkg) {
15891            // Set the system/privileged flags as needed
15892            final boolean privileged =
15893                    (oldPackage.applicationInfo.privateFlags
15894                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15895            final int systemPolicyFlags = policyFlags
15896                    | PackageParser.PARSE_IS_SYSTEM
15897                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15898
15899            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15900                    user, allUsers, installerPackageName, res, installReason);
15901        } else {
15902            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15903                    user, allUsers, installerPackageName, res, installReason);
15904        }
15905    }
15906
15907    public List<String> getPreviousCodePaths(String packageName) {
15908        final PackageSetting ps = mSettings.mPackages.get(packageName);
15909        final List<String> result = new ArrayList<String>();
15910        if (ps != null && ps.oldCodePaths != null) {
15911            result.addAll(ps.oldCodePaths);
15912        }
15913        return result;
15914    }
15915
15916    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15917            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15918            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15919            int installReason) {
15920        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15921                + deletedPackage);
15922
15923        String pkgName = deletedPackage.packageName;
15924        boolean deletedPkg = true;
15925        boolean addedPkg = false;
15926        boolean updatedSettings = false;
15927        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15928        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15929                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15930
15931        final long origUpdateTime = (pkg.mExtras != null)
15932                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15933
15934        // First delete the existing package while retaining the data directory
15935        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15936                res.removedInfo, true, pkg)) {
15937            // If the existing package wasn't successfully deleted
15938            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15939            deletedPkg = false;
15940        } else {
15941            // Successfully deleted the old package; proceed with replace.
15942
15943            // If deleted package lived in a container, give users a chance to
15944            // relinquish resources before killing.
15945            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15946                if (DEBUG_INSTALL) {
15947                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15948                }
15949                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15950                final ArrayList<String> pkgList = new ArrayList<String>(1);
15951                pkgList.add(deletedPackage.applicationInfo.packageName);
15952                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15953            }
15954
15955            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15956                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15957            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15958
15959            try {
15960                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15961                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15962                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15963                        installReason);
15964
15965                // Update the in-memory copy of the previous code paths.
15966                PackageSetting ps = mSettings.mPackages.get(pkgName);
15967                if (!killApp) {
15968                    if (ps.oldCodePaths == null) {
15969                        ps.oldCodePaths = new ArraySet<>();
15970                    }
15971                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15972                    if (deletedPackage.splitCodePaths != null) {
15973                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15974                    }
15975                } else {
15976                    ps.oldCodePaths = null;
15977                }
15978                if (ps.childPackageNames != null) {
15979                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15980                        final String childPkgName = ps.childPackageNames.get(i);
15981                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15982                        childPs.oldCodePaths = ps.oldCodePaths;
15983                    }
15984                }
15985                prepareAppDataAfterInstallLIF(newPackage);
15986                addedPkg = true;
15987            } catch (PackageManagerException e) {
15988                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15989            }
15990        }
15991
15992        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15993            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15994
15995            // Revert all internal state mutations and added folders for the failed install
15996            if (addedPkg) {
15997                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15998                        res.removedInfo, true, null);
15999            }
16000
16001            // Restore the old package
16002            if (deletedPkg) {
16003                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16004                File restoreFile = new File(deletedPackage.codePath);
16005                // Parse old package
16006                boolean oldExternal = isExternal(deletedPackage);
16007                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16008                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16009                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16010                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16011                try {
16012                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16013                            null);
16014                } catch (PackageManagerException e) {
16015                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16016                            + e.getMessage());
16017                    return;
16018                }
16019
16020                synchronized (mPackages) {
16021                    // Ensure the installer package name up to date
16022                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16023
16024                    // Update permissions for restored package
16025                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16026
16027                    mSettings.writeLPr();
16028                }
16029
16030                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16031            }
16032        } else {
16033            synchronized (mPackages) {
16034                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16035                if (ps != null) {
16036                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16037                    if (res.removedInfo.removedChildPackages != null) {
16038                        final int childCount = res.removedInfo.removedChildPackages.size();
16039                        // Iterate in reverse as we may modify the collection
16040                        for (int i = childCount - 1; i >= 0; i--) {
16041                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16042                            if (res.addedChildPackages.containsKey(childPackageName)) {
16043                                res.removedInfo.removedChildPackages.removeAt(i);
16044                            } else {
16045                                PackageRemovedInfo childInfo = res.removedInfo
16046                                        .removedChildPackages.valueAt(i);
16047                                childInfo.removedForAllUsers = mPackages.get(
16048                                        childInfo.removedPackage) == null;
16049                            }
16050                        }
16051                    }
16052                }
16053            }
16054        }
16055    }
16056
16057    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16058            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16059            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16060            int installReason) {
16061        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16062                + ", old=" + deletedPackage);
16063
16064        final boolean disabledSystem;
16065
16066        // Remove existing system package
16067        removePackageLI(deletedPackage, true);
16068
16069        synchronized (mPackages) {
16070            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16071        }
16072        if (!disabledSystem) {
16073            // We didn't need to disable the .apk as a current system package,
16074            // which means we are replacing another update that is already
16075            // installed.  We need to make sure to delete the older one's .apk.
16076            res.removedInfo.args = createInstallArgsForExisting(0,
16077                    deletedPackage.applicationInfo.getCodePath(),
16078                    deletedPackage.applicationInfo.getResourcePath(),
16079                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16080        } else {
16081            res.removedInfo.args = null;
16082        }
16083
16084        // Successfully disabled the old package. Now proceed with re-installation
16085        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16086                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16087        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16088
16089        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16090        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16091                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16092
16093        PackageParser.Package newPackage = null;
16094        try {
16095            // Add the package to the internal data structures
16096            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16097
16098            // Set the update and install times
16099            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16100            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16101                    System.currentTimeMillis());
16102
16103            // Update the package dynamic state if succeeded
16104            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16105                // Now that the install succeeded make sure we remove data
16106                // directories for any child package the update removed.
16107                final int deletedChildCount = (deletedPackage.childPackages != null)
16108                        ? deletedPackage.childPackages.size() : 0;
16109                final int newChildCount = (newPackage.childPackages != null)
16110                        ? newPackage.childPackages.size() : 0;
16111                for (int i = 0; i < deletedChildCount; i++) {
16112                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16113                    boolean childPackageDeleted = true;
16114                    for (int j = 0; j < newChildCount; j++) {
16115                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16116                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16117                            childPackageDeleted = false;
16118                            break;
16119                        }
16120                    }
16121                    if (childPackageDeleted) {
16122                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16123                                deletedChildPkg.packageName);
16124                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16125                            PackageRemovedInfo removedChildRes = res.removedInfo
16126                                    .removedChildPackages.get(deletedChildPkg.packageName);
16127                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16128                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16129                        }
16130                    }
16131                }
16132
16133                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16134                        installReason);
16135                prepareAppDataAfterInstallLIF(newPackage);
16136            }
16137        } catch (PackageManagerException e) {
16138            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16139            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16140        }
16141
16142        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16143            // Re installation failed. Restore old information
16144            // Remove new pkg information
16145            if (newPackage != null) {
16146                removeInstalledPackageLI(newPackage, true);
16147            }
16148            // Add back the old system package
16149            try {
16150                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16151            } catch (PackageManagerException e) {
16152                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16153            }
16154
16155            synchronized (mPackages) {
16156                if (disabledSystem) {
16157                    enableSystemPackageLPw(deletedPackage);
16158                }
16159
16160                // Ensure the installer package name up to date
16161                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16162
16163                // Update permissions for restored package
16164                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16165
16166                mSettings.writeLPr();
16167            }
16168
16169            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16170                    + " after failed upgrade");
16171        }
16172    }
16173
16174    /**
16175     * Checks whether the parent or any of the child packages have a change shared
16176     * user. For a package to be a valid update the shred users of the parent and
16177     * the children should match. We may later support changing child shared users.
16178     * @param oldPkg The updated package.
16179     * @param newPkg The update package.
16180     * @return The shared user that change between the versions.
16181     */
16182    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16183            PackageParser.Package newPkg) {
16184        // Check parent shared user
16185        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16186            return newPkg.packageName;
16187        }
16188        // Check child shared users
16189        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16190        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16191        for (int i = 0; i < newChildCount; i++) {
16192            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16193            // If this child was present, did it have the same shared user?
16194            for (int j = 0; j < oldChildCount; j++) {
16195                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16196                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16197                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16198                    return newChildPkg.packageName;
16199                }
16200            }
16201        }
16202        return null;
16203    }
16204
16205    private void removeNativeBinariesLI(PackageSetting ps) {
16206        // Remove the lib path for the parent package
16207        if (ps != null) {
16208            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16209            // Remove the lib path for the child packages
16210            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16211            for (int i = 0; i < childCount; i++) {
16212                PackageSetting childPs = null;
16213                synchronized (mPackages) {
16214                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16215                }
16216                if (childPs != null) {
16217                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16218                            .legacyNativeLibraryPathString);
16219                }
16220            }
16221        }
16222    }
16223
16224    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16225        // Enable the parent package
16226        mSettings.enableSystemPackageLPw(pkg.packageName);
16227        // Enable the child packages
16228        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16229        for (int i = 0; i < childCount; i++) {
16230            PackageParser.Package childPkg = pkg.childPackages.get(i);
16231            mSettings.enableSystemPackageLPw(childPkg.packageName);
16232        }
16233    }
16234
16235    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16236            PackageParser.Package newPkg) {
16237        // Disable the parent package (parent always replaced)
16238        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16239        // Disable the child packages
16240        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16241        for (int i = 0; i < childCount; i++) {
16242            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16243            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16244            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16245        }
16246        return disabled;
16247    }
16248
16249    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16250            String installerPackageName) {
16251        // Enable the parent package
16252        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16253        // Enable the child packages
16254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16255        for (int i = 0; i < childCount; i++) {
16256            PackageParser.Package childPkg = pkg.childPackages.get(i);
16257            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16258        }
16259    }
16260
16261    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16262        // Collect all used permissions in the UID
16263        ArraySet<String> usedPermissions = new ArraySet<>();
16264        final int packageCount = su.packages.size();
16265        for (int i = 0; i < packageCount; i++) {
16266            PackageSetting ps = su.packages.valueAt(i);
16267            if (ps.pkg == null) {
16268                continue;
16269            }
16270            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16271            for (int j = 0; j < requestedPermCount; j++) {
16272                String permission = ps.pkg.requestedPermissions.get(j);
16273                BasePermission bp = mSettings.mPermissions.get(permission);
16274                if (bp != null) {
16275                    usedPermissions.add(permission);
16276                }
16277            }
16278        }
16279
16280        PermissionsState permissionsState = su.getPermissionsState();
16281        // Prune install permissions
16282        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16283        final int installPermCount = installPermStates.size();
16284        for (int i = installPermCount - 1; i >= 0;  i--) {
16285            PermissionState permissionState = installPermStates.get(i);
16286            if (!usedPermissions.contains(permissionState.getName())) {
16287                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16288                if (bp != null) {
16289                    permissionsState.revokeInstallPermission(bp);
16290                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16291                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16292                }
16293            }
16294        }
16295
16296        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16297
16298        // Prune runtime permissions
16299        for (int userId : allUserIds) {
16300            List<PermissionState> runtimePermStates = permissionsState
16301                    .getRuntimePermissionStates(userId);
16302            final int runtimePermCount = runtimePermStates.size();
16303            for (int i = runtimePermCount - 1; i >= 0; i--) {
16304                PermissionState permissionState = runtimePermStates.get(i);
16305                if (!usedPermissions.contains(permissionState.getName())) {
16306                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16307                    if (bp != null) {
16308                        permissionsState.revokeRuntimePermission(bp, userId);
16309                        permissionsState.updatePermissionFlags(bp, userId,
16310                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16311                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16312                                runtimePermissionChangedUserIds, userId);
16313                    }
16314                }
16315            }
16316        }
16317
16318        return runtimePermissionChangedUserIds;
16319    }
16320
16321    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16322            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16323        // Update the parent package setting
16324        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16325                res, user, installReason);
16326        // Update the child packages setting
16327        final int childCount = (newPackage.childPackages != null)
16328                ? newPackage.childPackages.size() : 0;
16329        for (int i = 0; i < childCount; i++) {
16330            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16331            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16332            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16333                    childRes.origUsers, childRes, user, installReason);
16334        }
16335    }
16336
16337    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16338            String installerPackageName, int[] allUsers, int[] installedForUsers,
16339            PackageInstalledInfo res, UserHandle user, int installReason) {
16340        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16341
16342        String pkgName = newPackage.packageName;
16343        synchronized (mPackages) {
16344            //write settings. the installStatus will be incomplete at this stage.
16345            //note that the new package setting would have already been
16346            //added to mPackages. It hasn't been persisted yet.
16347            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16348            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16349            mSettings.writeLPr();
16350            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16351        }
16352
16353        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16354        synchronized (mPackages) {
16355            updatePermissionsLPw(newPackage.packageName, newPackage,
16356                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16357                            ? UPDATE_PERMISSIONS_ALL : 0));
16358            // For system-bundled packages, we assume that installing an upgraded version
16359            // of the package implies that the user actually wants to run that new code,
16360            // so we enable the package.
16361            PackageSetting ps = mSettings.mPackages.get(pkgName);
16362            final int userId = user.getIdentifier();
16363            if (ps != null) {
16364                if (isSystemApp(newPackage)) {
16365                    if (DEBUG_INSTALL) {
16366                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16367                    }
16368                    // Enable system package for requested users
16369                    if (res.origUsers != null) {
16370                        for (int origUserId : res.origUsers) {
16371                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16372                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16373                                        origUserId, installerPackageName);
16374                            }
16375                        }
16376                    }
16377                    // Also convey the prior install/uninstall state
16378                    if (allUsers != null && installedForUsers != null) {
16379                        for (int currentUserId : allUsers) {
16380                            final boolean installed = ArrayUtils.contains(
16381                                    installedForUsers, currentUserId);
16382                            if (DEBUG_INSTALL) {
16383                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16384                            }
16385                            ps.setInstalled(installed, currentUserId);
16386                        }
16387                        // these install state changes will be persisted in the
16388                        // upcoming call to mSettings.writeLPr().
16389                    }
16390                }
16391                // It's implied that when a user requests installation, they want the app to be
16392                // installed and enabled.
16393                if (userId != UserHandle.USER_ALL) {
16394                    ps.setInstalled(true, userId);
16395                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16396                }
16397
16398                // When replacing an existing package, preserve the original install reason for all
16399                // users that had the package installed before.
16400                final Set<Integer> previousUserIds = new ArraySet<>();
16401                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16402                    final int installReasonCount = res.removedInfo.installReasons.size();
16403                    for (int i = 0; i < installReasonCount; i++) {
16404                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16405                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16406                        ps.setInstallReason(previousInstallReason, previousUserId);
16407                        previousUserIds.add(previousUserId);
16408                    }
16409                }
16410
16411                // Set install reason for users that are having the package newly installed.
16412                if (userId == UserHandle.USER_ALL) {
16413                    for (int currentUserId : sUserManager.getUserIds()) {
16414                        if (!previousUserIds.contains(currentUserId)) {
16415                            ps.setInstallReason(installReason, currentUserId);
16416                        }
16417                    }
16418                } else if (!previousUserIds.contains(userId)) {
16419                    ps.setInstallReason(installReason, userId);
16420                }
16421            }
16422            res.name = pkgName;
16423            res.uid = newPackage.applicationInfo.uid;
16424            res.pkg = newPackage;
16425            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16426            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16427            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16428            //to update install status
16429            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16430            mSettings.writeLPr();
16431            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16432        }
16433
16434        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16435    }
16436
16437    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16438        try {
16439            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16440            installPackageLI(args, res);
16441        } finally {
16442            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16443        }
16444    }
16445
16446    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16447        final int installFlags = args.installFlags;
16448        final String installerPackageName = args.installerPackageName;
16449        final String volumeUuid = args.volumeUuid;
16450        final File tmpPackageFile = new File(args.getCodePath());
16451        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16452        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16453                || (args.volumeUuid != null));
16454        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16455        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16456        boolean replace = false;
16457        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16458        if (args.move != null) {
16459            // moving a complete application; perform an initial scan on the new install location
16460            scanFlags |= SCAN_INITIAL;
16461        }
16462        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16463            scanFlags |= SCAN_DONT_KILL_APP;
16464        }
16465
16466        // Result object to be returned
16467        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16468
16469        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16470
16471        // Sanity check
16472        if (ephemeral && (forwardLocked || onExternal)) {
16473            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16474                    + " external=" + onExternal);
16475            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16476            return;
16477        }
16478
16479        // Retrieve PackageSettings and parse package
16480        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16481                | PackageParser.PARSE_ENFORCE_CODE
16482                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16483                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16484                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16485                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16486        PackageParser pp = new PackageParser();
16487        pp.setSeparateProcesses(mSeparateProcesses);
16488        pp.setDisplayMetrics(mMetrics);
16489
16490        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16491        final PackageParser.Package pkg;
16492        try {
16493            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16494        } catch (PackageParserException e) {
16495            res.setError("Failed parse during installPackageLI", e);
16496            return;
16497        } finally {
16498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16499        }
16500
16501//        // Ephemeral apps must have target SDK >= O.
16502//        // TODO: Update conditional and error message when O gets locked down
16503//        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16504//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16505//                    "Ephemeral apps must have target SDK version of at least O");
16506//            return;
16507//        }
16508
16509        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16510            // Static shared libraries have synthetic package names
16511            renameStaticSharedLibraryPackage(pkg);
16512
16513            // No static shared libs on external storage
16514            if (onExternal) {
16515                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16516                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16517                        "Packages declaring static-shared libs cannot be updated");
16518                return;
16519            }
16520        }
16521
16522        // If we are installing a clustered package add results for the children
16523        if (pkg.childPackages != null) {
16524            synchronized (mPackages) {
16525                final int childCount = pkg.childPackages.size();
16526                for (int i = 0; i < childCount; i++) {
16527                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16528                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16529                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16530                    childRes.pkg = childPkg;
16531                    childRes.name = childPkg.packageName;
16532                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16533                    if (childPs != null) {
16534                        childRes.origUsers = childPs.queryInstalledUsers(
16535                                sUserManager.getUserIds(), true);
16536                    }
16537                    if ((mPackages.containsKey(childPkg.packageName))) {
16538                        childRes.removedInfo = new PackageRemovedInfo();
16539                        childRes.removedInfo.removedPackage = childPkg.packageName;
16540                    }
16541                    if (res.addedChildPackages == null) {
16542                        res.addedChildPackages = new ArrayMap<>();
16543                    }
16544                    res.addedChildPackages.put(childPkg.packageName, childRes);
16545                }
16546            }
16547        }
16548
16549        // If package doesn't declare API override, mark that we have an install
16550        // time CPU ABI override.
16551        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16552            pkg.cpuAbiOverride = args.abiOverride;
16553        }
16554
16555        String pkgName = res.name = pkg.packageName;
16556        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16557            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16558                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16559                return;
16560            }
16561        }
16562
16563        try {
16564            // either use what we've been given or parse directly from the APK
16565            if (args.certificates != null) {
16566                try {
16567                    PackageParser.populateCertificates(pkg, args.certificates);
16568                } catch (PackageParserException e) {
16569                    // there was something wrong with the certificates we were given;
16570                    // try to pull them from the APK
16571                    PackageParser.collectCertificates(pkg, parseFlags);
16572                }
16573            } else {
16574                PackageParser.collectCertificates(pkg, parseFlags);
16575            }
16576        } catch (PackageParserException e) {
16577            res.setError("Failed collect during installPackageLI", e);
16578            return;
16579        }
16580
16581        // Get rid of all references to package scan path via parser.
16582        pp = null;
16583        String oldCodePath = null;
16584        boolean systemApp = false;
16585        synchronized (mPackages) {
16586            // Check if installing already existing package
16587            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16588                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16589                if (pkg.mOriginalPackages != null
16590                        && pkg.mOriginalPackages.contains(oldName)
16591                        && mPackages.containsKey(oldName)) {
16592                    // This package is derived from an original package,
16593                    // and this device has been updating from that original
16594                    // name.  We must continue using the original name, so
16595                    // rename the new package here.
16596                    pkg.setPackageName(oldName);
16597                    pkgName = pkg.packageName;
16598                    replace = true;
16599                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16600                            + oldName + " pkgName=" + pkgName);
16601                } else if (mPackages.containsKey(pkgName)) {
16602                    // This package, under its official name, already exists
16603                    // on the device; we should replace it.
16604                    replace = true;
16605                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16606                }
16607
16608                // Child packages are installed through the parent package
16609                if (pkg.parentPackage != null) {
16610                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16611                            "Package " + pkg.packageName + " is child of package "
16612                                    + pkg.parentPackage.parentPackage + ". Child packages "
16613                                    + "can be updated only through the parent package.");
16614                    return;
16615                }
16616
16617                if (replace) {
16618                    // Prevent apps opting out from runtime permissions
16619                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16620                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16621                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16622                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16623                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16624                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16625                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16626                                        + " doesn't support runtime permissions but the old"
16627                                        + " target SDK " + oldTargetSdk + " does.");
16628                        return;
16629                    }
16630
16631                    // Prevent installing of child packages
16632                    if (oldPackage.parentPackage != null) {
16633                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16634                                "Package " + pkg.packageName + " is child of package "
16635                                        + oldPackage.parentPackage + ". Child packages "
16636                                        + "can be updated only through the parent package.");
16637                        return;
16638                    }
16639                }
16640            }
16641
16642            PackageSetting ps = mSettings.mPackages.get(pkgName);
16643            if (ps != null) {
16644                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16645
16646                // Static shared libs have same package with different versions where
16647                // we internally use a synthetic package name to allow multiple versions
16648                // of the same package, therefore we need to compare signatures against
16649                // the package setting for the latest library version.
16650                PackageSetting signatureCheckPs = ps;
16651                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16652                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16653                    if (libraryEntry != null) {
16654                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16655                    }
16656                }
16657
16658                // Quick sanity check that we're signed correctly if updating;
16659                // we'll check this again later when scanning, but we want to
16660                // bail early here before tripping over redefined permissions.
16661                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16662                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16663                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16664                                + pkg.packageName + " upgrade keys do not match the "
16665                                + "previously installed version");
16666                        return;
16667                    }
16668                } else {
16669                    try {
16670                        verifySignaturesLP(signatureCheckPs, pkg);
16671                    } catch (PackageManagerException e) {
16672                        res.setError(e.error, e.getMessage());
16673                        return;
16674                    }
16675                }
16676
16677                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16678                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16679                    systemApp = (ps.pkg.applicationInfo.flags &
16680                            ApplicationInfo.FLAG_SYSTEM) != 0;
16681                }
16682                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16683            }
16684
16685            // Check whether the newly-scanned package wants to define an already-defined perm
16686            int N = pkg.permissions.size();
16687            for (int i = N-1; i >= 0; i--) {
16688                PackageParser.Permission perm = pkg.permissions.get(i);
16689                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16690                if (bp != null) {
16691                    // If the defining package is signed with our cert, it's okay.  This
16692                    // also includes the "updating the same package" case, of course.
16693                    // "updating same package" could also involve key-rotation.
16694                    final boolean sigsOk;
16695                    if (bp.sourcePackage.equals(pkg.packageName)
16696                            && (bp.packageSetting instanceof PackageSetting)
16697                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16698                                    scanFlags))) {
16699                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16700                    } else {
16701                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16702                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16703                    }
16704                    if (!sigsOk) {
16705                        // If the owning package is the system itself, we log but allow
16706                        // install to proceed; we fail the install on all other permission
16707                        // redefinitions.
16708                        if (!bp.sourcePackage.equals("android")) {
16709                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16710                                    + pkg.packageName + " attempting to redeclare permission "
16711                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16712                            res.origPermission = perm.info.name;
16713                            res.origPackage = bp.sourcePackage;
16714                            return;
16715                        } else {
16716                            Slog.w(TAG, "Package " + pkg.packageName
16717                                    + " attempting to redeclare system permission "
16718                                    + perm.info.name + "; ignoring new declaration");
16719                            pkg.permissions.remove(i);
16720                        }
16721                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16722                        // Prevent apps to change protection level to dangerous from any other
16723                        // type as this would allow a privilege escalation where an app adds a
16724                        // normal/signature permission in other app's group and later redefines
16725                        // it as dangerous leading to the group auto-grant.
16726                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16727                                == PermissionInfo.PROTECTION_DANGEROUS) {
16728                            if (bp != null && !bp.isRuntime()) {
16729                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16730                                        + "non-runtime permission " + perm.info.name
16731                                        + " to runtime; keeping old protection level");
16732                                perm.info.protectionLevel = bp.protectionLevel;
16733                            }
16734                        }
16735                    }
16736                }
16737            }
16738        }
16739
16740        if (systemApp) {
16741            if (onExternal) {
16742                // Abort update; system app can't be replaced with app on sdcard
16743                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16744                        "Cannot install updates to system apps on sdcard");
16745                return;
16746            } else if (ephemeral) {
16747                // Abort update; system app can't be replaced with an ephemeral app
16748                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16749                        "Cannot update a system app with an ephemeral app");
16750                return;
16751            }
16752        }
16753
16754        if (args.move != null) {
16755            // We did an in-place move, so dex is ready to roll
16756            scanFlags |= SCAN_NO_DEX;
16757            scanFlags |= SCAN_MOVE;
16758
16759            synchronized (mPackages) {
16760                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16761                if (ps == null) {
16762                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16763                            "Missing settings for moved package " + pkgName);
16764                }
16765
16766                // We moved the entire application as-is, so bring over the
16767                // previously derived ABI information.
16768                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16769                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16770            }
16771
16772        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16773            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16774            scanFlags |= SCAN_NO_DEX;
16775
16776            try {
16777                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16778                    args.abiOverride : pkg.cpuAbiOverride);
16779                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16780                        true /*extractLibs*/, mAppLib32InstallDir);
16781            } catch (PackageManagerException pme) {
16782                Slog.e(TAG, "Error deriving application ABI", pme);
16783                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16784                return;
16785            }
16786
16787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16788            // Do not run PackageDexOptimizer through the local performDexOpt
16789            // method because `pkg` may not be in `mPackages` yet.
16790            //
16791            // Also, don't fail application installs if the dexopt step fails.
16792            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16793                    null /* instructionSets */, false /* checkProfiles */,
16794                    getCompilerFilterForReason(REASON_INSTALL),
16795                    getOrCreateCompilerPackageStats(pkg));
16796            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16797
16798            // Notify BackgroundDexOptJobService that the package has been changed.
16799            // If this is an update of a package which used to fail to compile,
16800            // BDOS will remove it from its blacklist.
16801            // TODO: Layering violation
16802            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16803        }
16804
16805        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16806            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16807            return;
16808        }
16809
16810        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16811
16812        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16813                "installPackageLI")) {
16814            if (replace) {
16815                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16816                    // Static libs have a synthetic package name containing the version
16817                    // and cannot be updated as an update would get a new package name,
16818                    // unless this is the exact same version code which is useful for
16819                    // development.
16820                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16821                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16822                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16823                                + "static-shared libs cannot be updated");
16824                        return;
16825                    }
16826                }
16827                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16828                        installerPackageName, res, args.installReason);
16829            } else {
16830                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16831                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16832            }
16833        }
16834        synchronized (mPackages) {
16835            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16836            if (ps != null) {
16837                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16838            }
16839
16840            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16841            for (int i = 0; i < childCount; i++) {
16842                PackageParser.Package childPkg = pkg.childPackages.get(i);
16843                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16844                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16845                if (childPs != null) {
16846                    childRes.newUsers = childPs.queryInstalledUsers(
16847                            sUserManager.getUserIds(), true);
16848                }
16849            }
16850        }
16851    }
16852
16853    private void startIntentFilterVerifications(int userId, boolean replacing,
16854            PackageParser.Package pkg) {
16855        if (mIntentFilterVerifierComponent == null) {
16856            Slog.w(TAG, "No IntentFilter verification will not be done as "
16857                    + "there is no IntentFilterVerifier available!");
16858            return;
16859        }
16860
16861        final int verifierUid = getPackageUid(
16862                mIntentFilterVerifierComponent.getPackageName(),
16863                MATCH_DEBUG_TRIAGED_MISSING,
16864                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16865
16866        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16867        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16868        mHandler.sendMessage(msg);
16869
16870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16871        for (int i = 0; i < childCount; i++) {
16872            PackageParser.Package childPkg = pkg.childPackages.get(i);
16873            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16874            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16875            mHandler.sendMessage(msg);
16876        }
16877    }
16878
16879    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16880            PackageParser.Package pkg) {
16881        int size = pkg.activities.size();
16882        if (size == 0) {
16883            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16884                    "No activity, so no need to verify any IntentFilter!");
16885            return;
16886        }
16887
16888        final boolean hasDomainURLs = hasDomainURLs(pkg);
16889        if (!hasDomainURLs) {
16890            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16891                    "No domain URLs, so no need to verify any IntentFilter!");
16892            return;
16893        }
16894
16895        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16896                + " if any IntentFilter from the " + size
16897                + " Activities needs verification ...");
16898
16899        int count = 0;
16900        final String packageName = pkg.packageName;
16901
16902        synchronized (mPackages) {
16903            // If this is a new install and we see that we've already run verification for this
16904            // package, we have nothing to do: it means the state was restored from backup.
16905            if (!replacing) {
16906                IntentFilterVerificationInfo ivi =
16907                        mSettings.getIntentFilterVerificationLPr(packageName);
16908                if (ivi != null) {
16909                    if (DEBUG_DOMAIN_VERIFICATION) {
16910                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16911                                + ivi.getStatusString());
16912                    }
16913                    return;
16914                }
16915            }
16916
16917            // If any filters need to be verified, then all need to be.
16918            boolean needToVerify = false;
16919            for (PackageParser.Activity a : pkg.activities) {
16920                for (ActivityIntentInfo filter : a.intents) {
16921                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16922                        if (DEBUG_DOMAIN_VERIFICATION) {
16923                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16924                        }
16925                        needToVerify = true;
16926                        break;
16927                    }
16928                }
16929            }
16930
16931            if (needToVerify) {
16932                final int verificationId = mIntentFilterVerificationToken++;
16933                for (PackageParser.Activity a : pkg.activities) {
16934                    for (ActivityIntentInfo filter : a.intents) {
16935                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16936                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16937                                    "Verification needed for IntentFilter:" + filter.toString());
16938                            mIntentFilterVerifier.addOneIntentFilterVerification(
16939                                    verifierUid, userId, verificationId, filter, packageName);
16940                            count++;
16941                        }
16942                    }
16943                }
16944            }
16945        }
16946
16947        if (count > 0) {
16948            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16949                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16950                    +  " for userId:" + userId);
16951            mIntentFilterVerifier.startVerifications(userId);
16952        } else {
16953            if (DEBUG_DOMAIN_VERIFICATION) {
16954                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16955            }
16956        }
16957    }
16958
16959    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16960        final ComponentName cn  = filter.activity.getComponentName();
16961        final String packageName = cn.getPackageName();
16962
16963        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16964                packageName);
16965        if (ivi == null) {
16966            return true;
16967        }
16968        int status = ivi.getStatus();
16969        switch (status) {
16970            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16971            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16972                return true;
16973
16974            default:
16975                // Nothing to do
16976                return false;
16977        }
16978    }
16979
16980    private static boolean isMultiArch(ApplicationInfo info) {
16981        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16982    }
16983
16984    private static boolean isExternal(PackageParser.Package pkg) {
16985        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16986    }
16987
16988    private static boolean isExternal(PackageSetting ps) {
16989        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16990    }
16991
16992    private static boolean isEphemeral(PackageParser.Package pkg) {
16993        return pkg.applicationInfo.isInstantApp();
16994    }
16995
16996    private static boolean isEphemeral(PackageSetting ps) {
16997        return ps.pkg != null && isEphemeral(ps.pkg);
16998    }
16999
17000    private static boolean isSystemApp(PackageParser.Package pkg) {
17001        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17002    }
17003
17004    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17005        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17006    }
17007
17008    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17009        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17010    }
17011
17012    private static boolean isSystemApp(PackageSetting ps) {
17013        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17014    }
17015
17016    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17017        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17018    }
17019
17020    private int packageFlagsToInstallFlags(PackageSetting ps) {
17021        int installFlags = 0;
17022        if (isEphemeral(ps)) {
17023            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17024        }
17025        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17026            // This existing package was an external ASEC install when we have
17027            // the external flag without a UUID
17028            installFlags |= PackageManager.INSTALL_EXTERNAL;
17029        }
17030        if (ps.isForwardLocked()) {
17031            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17032        }
17033        return installFlags;
17034    }
17035
17036    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17037        if (isExternal(pkg)) {
17038            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17039                return StorageManager.UUID_PRIMARY_PHYSICAL;
17040            } else {
17041                return pkg.volumeUuid;
17042            }
17043        } else {
17044            return StorageManager.UUID_PRIVATE_INTERNAL;
17045        }
17046    }
17047
17048    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17049        if (isExternal(pkg)) {
17050            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17051                return mSettings.getExternalVersion();
17052            } else {
17053                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17054            }
17055        } else {
17056            return mSettings.getInternalVersion();
17057        }
17058    }
17059
17060    private void deleteTempPackageFiles() {
17061        final FilenameFilter filter = new FilenameFilter() {
17062            public boolean accept(File dir, String name) {
17063                return name.startsWith("vmdl") && name.endsWith(".tmp");
17064            }
17065        };
17066        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17067            file.delete();
17068        }
17069    }
17070
17071    @Override
17072    public void deletePackageAsUser(String packageName, int versionCode,
17073            IPackageDeleteObserver observer, int userId, int flags) {
17074        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17075                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17076    }
17077
17078    @Override
17079    public void deletePackageVersioned(VersionedPackage versionedPackage,
17080            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17081        mContext.enforceCallingOrSelfPermission(
17082                android.Manifest.permission.DELETE_PACKAGES, null);
17083        Preconditions.checkNotNull(versionedPackage);
17084        Preconditions.checkNotNull(observer);
17085        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17086                PackageManager.VERSION_CODE_HIGHEST,
17087                Integer.MAX_VALUE, "versionCode must be >= -1");
17088
17089        final String packageName = versionedPackage.getPackageName();
17090        // TODO: We will change version code to long, so in the new API it is long
17091        final int versionCode = (int) versionedPackage.getVersionCode();
17092        final String internalPackageName;
17093        synchronized (mPackages) {
17094            // Normalize package name to handle renamed packages and static libs
17095            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17096                    // TODO: We will change version code to long, so in the new API it is long
17097                    (int) versionedPackage.getVersionCode());
17098        }
17099
17100        final int uid = Binder.getCallingUid();
17101        if (!isOrphaned(internalPackageName)
17102                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17103            try {
17104                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17105                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17106                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17107                observer.onUserActionRequired(intent);
17108            } catch (RemoteException re) {
17109            }
17110            return;
17111        }
17112        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17113        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17114        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17115            mContext.enforceCallingOrSelfPermission(
17116                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17117                    "deletePackage for user " + userId);
17118        }
17119
17120        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17121            try {
17122                observer.onPackageDeleted(packageName,
17123                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17124            } catch (RemoteException re) {
17125            }
17126            return;
17127        }
17128
17129        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17130            try {
17131                observer.onPackageDeleted(packageName,
17132                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17133            } catch (RemoteException re) {
17134            }
17135            return;
17136        }
17137
17138        if (DEBUG_REMOVE) {
17139            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17140                    + " deleteAllUsers: " + deleteAllUsers + " version="
17141                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17142                    ? "VERSION_CODE_HIGHEST" : versionCode));
17143        }
17144        // Queue up an async operation since the package deletion may take a little while.
17145        mHandler.post(new Runnable() {
17146            public void run() {
17147                mHandler.removeCallbacks(this);
17148                int returnCode;
17149                if (!deleteAllUsers) {
17150                    returnCode = deletePackageX(internalPackageName, versionCode,
17151                            userId, deleteFlags);
17152                } else {
17153                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17154                            internalPackageName, users);
17155                    // If nobody is blocking uninstall, proceed with delete for all users
17156                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17157                        returnCode = deletePackageX(internalPackageName, versionCode,
17158                                userId, deleteFlags);
17159                    } else {
17160                        // Otherwise uninstall individually for users with blockUninstalls=false
17161                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17162                        for (int userId : users) {
17163                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17164                                returnCode = deletePackageX(internalPackageName, versionCode,
17165                                        userId, userFlags);
17166                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17167                                    Slog.w(TAG, "Package delete failed for user " + userId
17168                                            + ", returnCode " + returnCode);
17169                                }
17170                            }
17171                        }
17172                        // The app has only been marked uninstalled for certain users.
17173                        // We still need to report that delete was blocked
17174                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17175                    }
17176                }
17177                try {
17178                    observer.onPackageDeleted(packageName, returnCode, null);
17179                } catch (RemoteException e) {
17180                    Log.i(TAG, "Observer no longer exists.");
17181                } //end catch
17182            } //end run
17183        });
17184    }
17185
17186    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17187        if (pkg.staticSharedLibName != null) {
17188            return pkg.manifestPackageName;
17189        }
17190        return pkg.packageName;
17191    }
17192
17193    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17194        // Handle renamed packages
17195        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17196        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17197
17198        // Is this a static library?
17199        SparseArray<SharedLibraryEntry> versionedLib =
17200                mStaticLibsByDeclaringPackage.get(packageName);
17201        if (versionedLib == null || versionedLib.size() <= 0) {
17202            return packageName;
17203        }
17204
17205        // Figure out which lib versions the caller can see
17206        SparseIntArray versionsCallerCanSee = null;
17207        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17208        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17209                && callingAppId != Process.ROOT_UID) {
17210            versionsCallerCanSee = new SparseIntArray();
17211            String libName = versionedLib.valueAt(0).info.getName();
17212            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17213            if (uidPackages != null) {
17214                for (String uidPackage : uidPackages) {
17215                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17216                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17217                    if (libIdx >= 0) {
17218                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17219                        versionsCallerCanSee.append(libVersion, libVersion);
17220                    }
17221                }
17222            }
17223        }
17224
17225        // Caller can see nothing - done
17226        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17227            return packageName;
17228        }
17229
17230        // Find the version the caller can see and the app version code
17231        SharedLibraryEntry highestVersion = null;
17232        final int versionCount = versionedLib.size();
17233        for (int i = 0; i < versionCount; i++) {
17234            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17235            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17236                    libEntry.info.getVersion()) < 0) {
17237                continue;
17238            }
17239            // TODO: We will change version code to long, so in the new API it is long
17240            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17241            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17242                if (libVersionCode == versionCode) {
17243                    return libEntry.apk;
17244                }
17245            } else if (highestVersion == null) {
17246                highestVersion = libEntry;
17247            } else if (libVersionCode  > highestVersion.info
17248                    .getDeclaringPackage().getVersionCode()) {
17249                highestVersion = libEntry;
17250            }
17251        }
17252
17253        if (highestVersion != null) {
17254            return highestVersion.apk;
17255        }
17256
17257        return packageName;
17258    }
17259
17260    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17261        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17262              || callingUid == Process.SYSTEM_UID) {
17263            return true;
17264        }
17265        final int callingUserId = UserHandle.getUserId(callingUid);
17266        // If the caller installed the pkgName, then allow it to silently uninstall.
17267        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17268            return true;
17269        }
17270
17271        // Allow package verifier to silently uninstall.
17272        if (mRequiredVerifierPackage != null &&
17273                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17274            return true;
17275        }
17276
17277        // Allow package uninstaller to silently uninstall.
17278        if (mRequiredUninstallerPackage != null &&
17279                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17280            return true;
17281        }
17282
17283        // Allow storage manager to silently uninstall.
17284        if (mStorageManagerPackage != null &&
17285                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17286            return true;
17287        }
17288        return false;
17289    }
17290
17291    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17292        int[] result = EMPTY_INT_ARRAY;
17293        for (int userId : userIds) {
17294            if (getBlockUninstallForUser(packageName, userId)) {
17295                result = ArrayUtils.appendInt(result, userId);
17296            }
17297        }
17298        return result;
17299    }
17300
17301    @Override
17302    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17303        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17304    }
17305
17306    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17307        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17308                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17309        try {
17310            if (dpm != null) {
17311                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17312                        /* callingUserOnly =*/ false);
17313                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17314                        : deviceOwnerComponentName.getPackageName();
17315                // Does the package contains the device owner?
17316                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17317                // this check is probably not needed, since DO should be registered as a device
17318                // admin on some user too. (Original bug for this: b/17657954)
17319                if (packageName.equals(deviceOwnerPackageName)) {
17320                    return true;
17321                }
17322                // Does it contain a device admin for any user?
17323                int[] users;
17324                if (userId == UserHandle.USER_ALL) {
17325                    users = sUserManager.getUserIds();
17326                } else {
17327                    users = new int[]{userId};
17328                }
17329                for (int i = 0; i < users.length; ++i) {
17330                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17331                        return true;
17332                    }
17333                }
17334            }
17335        } catch (RemoteException e) {
17336        }
17337        return false;
17338    }
17339
17340    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17341        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17342    }
17343
17344    /**
17345     *  This method is an internal method that could be get invoked either
17346     *  to delete an installed package or to clean up a failed installation.
17347     *  After deleting an installed package, a broadcast is sent to notify any
17348     *  listeners that the package has been removed. For cleaning up a failed
17349     *  installation, the broadcast is not necessary since the package's
17350     *  installation wouldn't have sent the initial broadcast either
17351     *  The key steps in deleting a package are
17352     *  deleting the package information in internal structures like mPackages,
17353     *  deleting the packages base directories through installd
17354     *  updating mSettings to reflect current status
17355     *  persisting settings for later use
17356     *  sending a broadcast if necessary
17357     */
17358    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17359        final PackageRemovedInfo info = new PackageRemovedInfo();
17360        final boolean res;
17361
17362        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17363                ? UserHandle.USER_ALL : userId;
17364
17365        if (isPackageDeviceAdmin(packageName, removeUser)) {
17366            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17367            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17368        }
17369
17370        PackageSetting uninstalledPs = null;
17371
17372        // for the uninstall-updates case and restricted profiles, remember the per-
17373        // user handle installed state
17374        int[] allUsers;
17375        synchronized (mPackages) {
17376            uninstalledPs = mSettings.mPackages.get(packageName);
17377            if (uninstalledPs == null) {
17378                Slog.w(TAG, "Not removing non-existent package " + packageName);
17379                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17380            }
17381
17382            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17383                    && uninstalledPs.versionCode != versionCode) {
17384                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17385                        + uninstalledPs.versionCode + " != " + versionCode);
17386                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17387            }
17388
17389            // Static shared libs can be declared by any package, so let us not
17390            // allow removing a package if it provides a lib others depend on.
17391            PackageParser.Package pkg = mPackages.get(packageName);
17392            if (pkg != null && pkg.staticSharedLibName != null) {
17393                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17394                        pkg.staticSharedLibVersion);
17395                if (libEntry != null) {
17396                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17397                            libEntry.info, 0, userId);
17398                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17399                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17400                                + " hosting lib " + libEntry.info.getName() + " version "
17401                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17402                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17403                    }
17404                }
17405            }
17406
17407            allUsers = sUserManager.getUserIds();
17408            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17409        }
17410
17411        final int freezeUser;
17412        if (isUpdatedSystemApp(uninstalledPs)
17413                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17414            // We're downgrading a system app, which will apply to all users, so
17415            // freeze them all during the downgrade
17416            freezeUser = UserHandle.USER_ALL;
17417        } else {
17418            freezeUser = removeUser;
17419        }
17420
17421        synchronized (mInstallLock) {
17422            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17423            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17424                    deleteFlags, "deletePackageX")) {
17425                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17426                        deleteFlags | REMOVE_CHATTY, info, true, null);
17427            }
17428            synchronized (mPackages) {
17429                if (res) {
17430                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17431                            info.removedUsers);
17432                }
17433            }
17434        }
17435
17436        if (res) {
17437            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17438            info.sendPackageRemovedBroadcasts(killApp);
17439            info.sendSystemPackageUpdatedBroadcasts();
17440            info.sendSystemPackageAppearedBroadcasts();
17441        }
17442        // Force a gc here.
17443        Runtime.getRuntime().gc();
17444        // Delete the resources here after sending the broadcast to let
17445        // other processes clean up before deleting resources.
17446        if (info.args != null) {
17447            synchronized (mInstallLock) {
17448                info.args.doPostDeleteLI(true);
17449            }
17450        }
17451
17452        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17453    }
17454
17455    class PackageRemovedInfo {
17456        String removedPackage;
17457        int uid = -1;
17458        int removedAppId = -1;
17459        int[] origUsers;
17460        int[] removedUsers = null;
17461        SparseArray<Integer> installReasons;
17462        boolean isRemovedPackageSystemUpdate = false;
17463        boolean isUpdate;
17464        boolean dataRemoved;
17465        boolean removedForAllUsers;
17466        boolean isStaticSharedLib;
17467        // Clean up resources deleted packages.
17468        InstallArgs args = null;
17469        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17470        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17471
17472        void sendPackageRemovedBroadcasts(boolean killApp) {
17473            sendPackageRemovedBroadcastInternal(killApp);
17474            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17475            for (int i = 0; i < childCount; i++) {
17476                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17477                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17478            }
17479        }
17480
17481        void sendSystemPackageUpdatedBroadcasts() {
17482            if (isRemovedPackageSystemUpdate) {
17483                sendSystemPackageUpdatedBroadcastsInternal();
17484                final int childCount = (removedChildPackages != null)
17485                        ? removedChildPackages.size() : 0;
17486                for (int i = 0; i < childCount; i++) {
17487                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17488                    if (childInfo.isRemovedPackageSystemUpdate) {
17489                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17490                    }
17491                }
17492            }
17493        }
17494
17495        void sendSystemPackageAppearedBroadcasts() {
17496            final int packageCount = (appearedChildPackages != null)
17497                    ? appearedChildPackages.size() : 0;
17498            for (int i = 0; i < packageCount; i++) {
17499                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17500                sendPackageAddedForNewUsers(installedInfo.name, true,
17501                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17502            }
17503        }
17504
17505        private void sendSystemPackageUpdatedBroadcastsInternal() {
17506            Bundle extras = new Bundle(2);
17507            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17508            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17509            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17510                    extras, 0, null, null, null);
17511            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17512                    extras, 0, null, null, null);
17513            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17514                    null, 0, removedPackage, null, null);
17515        }
17516
17517        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17518            // Don't send static shared library removal broadcasts as these
17519            // libs are visible only the the apps that depend on them an one
17520            // cannot remove the library if it has a dependency.
17521            if (isStaticSharedLib) {
17522                return;
17523            }
17524            Bundle extras = new Bundle(2);
17525            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17526            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17527            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17528            if (isUpdate || isRemovedPackageSystemUpdate) {
17529                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17530            }
17531            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17532            if (removedPackage != null) {
17533                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17534                        extras, 0, null, null, removedUsers);
17535                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17536                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17537                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17538                            null, null, removedUsers);
17539                }
17540            }
17541            if (removedAppId >= 0) {
17542                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17543                        removedUsers);
17544            }
17545        }
17546    }
17547
17548    /*
17549     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17550     * flag is not set, the data directory is removed as well.
17551     * make sure this flag is set for partially installed apps. If not its meaningless to
17552     * delete a partially installed application.
17553     */
17554    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17555            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17556        String packageName = ps.name;
17557        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17558        // Retrieve object to delete permissions for shared user later on
17559        final PackageParser.Package deletedPkg;
17560        final PackageSetting deletedPs;
17561        // reader
17562        synchronized (mPackages) {
17563            deletedPkg = mPackages.get(packageName);
17564            deletedPs = mSettings.mPackages.get(packageName);
17565            if (outInfo != null) {
17566                outInfo.removedPackage = packageName;
17567                outInfo.isStaticSharedLib = deletedPkg != null
17568                        && deletedPkg.staticSharedLibName != null;
17569                outInfo.removedUsers = deletedPs != null
17570                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17571                        : null;
17572            }
17573        }
17574
17575        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17576
17577        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17578            final PackageParser.Package resolvedPkg;
17579            if (deletedPkg != null) {
17580                resolvedPkg = deletedPkg;
17581            } else {
17582                // We don't have a parsed package when it lives on an ejected
17583                // adopted storage device, so fake something together
17584                resolvedPkg = new PackageParser.Package(ps.name);
17585                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17586            }
17587            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17588                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17589            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17590            if (outInfo != null) {
17591                outInfo.dataRemoved = true;
17592            }
17593            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17594        }
17595
17596        int removedAppId = -1;
17597
17598        // writer
17599        synchronized (mPackages) {
17600            if (deletedPs != null) {
17601                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17602                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17603                    clearDefaultBrowserIfNeeded(packageName);
17604                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17605                    removedAppId = mSettings.removePackageLPw(packageName);
17606                    if (outInfo != null) {
17607                        outInfo.removedAppId = removedAppId;
17608                    }
17609                    updatePermissionsLPw(deletedPs.name, null, 0);
17610                    if (deletedPs.sharedUser != null) {
17611                        // Remove permissions associated with package. Since runtime
17612                        // permissions are per user we have to kill the removed package
17613                        // or packages running under the shared user of the removed
17614                        // package if revoking the permissions requested only by the removed
17615                        // package is successful and this causes a change in gids.
17616                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17617                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17618                                    userId);
17619                            if (userIdToKill == UserHandle.USER_ALL
17620                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17621                                // If gids changed for this user, kill all affected packages.
17622                                mHandler.post(new Runnable() {
17623                                    @Override
17624                                    public void run() {
17625                                        // This has to happen with no lock held.
17626                                        killApplication(deletedPs.name, deletedPs.appId,
17627                                                KILL_APP_REASON_GIDS_CHANGED);
17628                                    }
17629                                });
17630                                break;
17631                            }
17632                        }
17633                    }
17634                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17635                }
17636                // make sure to preserve per-user disabled state if this removal was just
17637                // a downgrade of a system app to the factory package
17638                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17639                    if (DEBUG_REMOVE) {
17640                        Slog.d(TAG, "Propagating install state across downgrade");
17641                    }
17642                    for (int userId : allUserHandles) {
17643                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17644                        if (DEBUG_REMOVE) {
17645                            Slog.d(TAG, "    user " + userId + " => " + installed);
17646                        }
17647                        ps.setInstalled(installed, userId);
17648                    }
17649                }
17650            }
17651            // can downgrade to reader
17652            if (writeSettings) {
17653                // Save settings now
17654                mSettings.writeLPr();
17655            }
17656        }
17657        if (removedAppId != -1) {
17658            // A user ID was deleted here. Go through all users and remove it
17659            // from KeyStore.
17660            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17661        }
17662    }
17663
17664    static boolean locationIsPrivileged(File path) {
17665        try {
17666            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17667                    .getCanonicalPath();
17668            return path.getCanonicalPath().startsWith(privilegedAppDir);
17669        } catch (IOException e) {
17670            Slog.e(TAG, "Unable to access code path " + path);
17671        }
17672        return false;
17673    }
17674
17675    /*
17676     * Tries to delete system package.
17677     */
17678    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17679            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17680            boolean writeSettings) {
17681        if (deletedPs.parentPackageName != null) {
17682            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17683            return false;
17684        }
17685
17686        final boolean applyUserRestrictions
17687                = (allUserHandles != null) && (outInfo.origUsers != null);
17688        final PackageSetting disabledPs;
17689        // Confirm if the system package has been updated
17690        // An updated system app can be deleted. This will also have to restore
17691        // the system pkg from system partition
17692        // reader
17693        synchronized (mPackages) {
17694            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17695        }
17696
17697        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17698                + " disabledPs=" + disabledPs);
17699
17700        if (disabledPs == null) {
17701            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17702            return false;
17703        } else if (DEBUG_REMOVE) {
17704            Slog.d(TAG, "Deleting system pkg from data partition");
17705        }
17706
17707        if (DEBUG_REMOVE) {
17708            if (applyUserRestrictions) {
17709                Slog.d(TAG, "Remembering install states:");
17710                for (int userId : allUserHandles) {
17711                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17712                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17713                }
17714            }
17715        }
17716
17717        // Delete the updated package
17718        outInfo.isRemovedPackageSystemUpdate = true;
17719        if (outInfo.removedChildPackages != null) {
17720            final int childCount = (deletedPs.childPackageNames != null)
17721                    ? deletedPs.childPackageNames.size() : 0;
17722            for (int i = 0; i < childCount; i++) {
17723                String childPackageName = deletedPs.childPackageNames.get(i);
17724                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17725                        .contains(childPackageName)) {
17726                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17727                            childPackageName);
17728                    if (childInfo != null) {
17729                        childInfo.isRemovedPackageSystemUpdate = true;
17730                    }
17731                }
17732            }
17733        }
17734
17735        if (disabledPs.versionCode < deletedPs.versionCode) {
17736            // Delete data for downgrades
17737            flags &= ~PackageManager.DELETE_KEEP_DATA;
17738        } else {
17739            // Preserve data by setting flag
17740            flags |= PackageManager.DELETE_KEEP_DATA;
17741        }
17742
17743        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17744                outInfo, writeSettings, disabledPs.pkg);
17745        if (!ret) {
17746            return false;
17747        }
17748
17749        // writer
17750        synchronized (mPackages) {
17751            // Reinstate the old system package
17752            enableSystemPackageLPw(disabledPs.pkg);
17753            // Remove any native libraries from the upgraded package.
17754            removeNativeBinariesLI(deletedPs);
17755        }
17756
17757        // Install the system package
17758        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17759        int parseFlags = mDefParseFlags
17760                | PackageParser.PARSE_MUST_BE_APK
17761                | PackageParser.PARSE_IS_SYSTEM
17762                | PackageParser.PARSE_IS_SYSTEM_DIR;
17763        if (locationIsPrivileged(disabledPs.codePath)) {
17764            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17765        }
17766
17767        final PackageParser.Package newPkg;
17768        try {
17769            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17770                0 /* currentTime */, null);
17771        } catch (PackageManagerException e) {
17772            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17773                    + e.getMessage());
17774            return false;
17775        }
17776
17777        try {
17778            // update shared libraries for the newly re-installed system package
17779            updateSharedLibrariesLPr(newPkg, null);
17780        } catch (PackageManagerException e) {
17781            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17782        }
17783
17784        prepareAppDataAfterInstallLIF(newPkg);
17785
17786        // writer
17787        synchronized (mPackages) {
17788            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17789
17790            // Propagate the permissions state as we do not want to drop on the floor
17791            // runtime permissions. The update permissions method below will take
17792            // care of removing obsolete permissions and grant install permissions.
17793            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17794            updatePermissionsLPw(newPkg.packageName, newPkg,
17795                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17796
17797            if (applyUserRestrictions) {
17798                if (DEBUG_REMOVE) {
17799                    Slog.d(TAG, "Propagating install state across reinstall");
17800                }
17801                for (int userId : allUserHandles) {
17802                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17803                    if (DEBUG_REMOVE) {
17804                        Slog.d(TAG, "    user " + userId + " => " + installed);
17805                    }
17806                    ps.setInstalled(installed, userId);
17807
17808                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17809                }
17810                // Regardless of writeSettings we need to ensure that this restriction
17811                // state propagation is persisted
17812                mSettings.writeAllUsersPackageRestrictionsLPr();
17813            }
17814            // can downgrade to reader here
17815            if (writeSettings) {
17816                mSettings.writeLPr();
17817            }
17818        }
17819        return true;
17820    }
17821
17822    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17823            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17824            PackageRemovedInfo outInfo, boolean writeSettings,
17825            PackageParser.Package replacingPackage) {
17826        synchronized (mPackages) {
17827            if (outInfo != null) {
17828                outInfo.uid = ps.appId;
17829            }
17830
17831            if (outInfo != null && outInfo.removedChildPackages != null) {
17832                final int childCount = (ps.childPackageNames != null)
17833                        ? ps.childPackageNames.size() : 0;
17834                for (int i = 0; i < childCount; i++) {
17835                    String childPackageName = ps.childPackageNames.get(i);
17836                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17837                    if (childPs == null) {
17838                        return false;
17839                    }
17840                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17841                            childPackageName);
17842                    if (childInfo != null) {
17843                        childInfo.uid = childPs.appId;
17844                    }
17845                }
17846            }
17847        }
17848
17849        // Delete package data from internal structures and also remove data if flag is set
17850        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17851
17852        // Delete the child packages data
17853        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17854        for (int i = 0; i < childCount; i++) {
17855            PackageSetting childPs;
17856            synchronized (mPackages) {
17857                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17858            }
17859            if (childPs != null) {
17860                PackageRemovedInfo childOutInfo = (outInfo != null
17861                        && outInfo.removedChildPackages != null)
17862                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17863                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17864                        && (replacingPackage != null
17865                        && !replacingPackage.hasChildPackage(childPs.name))
17866                        ? flags & ~DELETE_KEEP_DATA : flags;
17867                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17868                        deleteFlags, writeSettings);
17869            }
17870        }
17871
17872        // Delete application code and resources only for parent packages
17873        if (ps.parentPackageName == null) {
17874            if (deleteCodeAndResources && (outInfo != null)) {
17875                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17876                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17877                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17878            }
17879        }
17880
17881        return true;
17882    }
17883
17884    @Override
17885    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17886            int userId) {
17887        mContext.enforceCallingOrSelfPermission(
17888                android.Manifest.permission.DELETE_PACKAGES, null);
17889        synchronized (mPackages) {
17890            PackageSetting ps = mSettings.mPackages.get(packageName);
17891            if (ps == null) {
17892                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17893                return false;
17894            }
17895            // Cannot block uninstall of static shared libs as they are
17896            // considered a part of the using app (emulating static linking).
17897            // Also static libs are installed always on internal storage.
17898            PackageParser.Package pkg = mPackages.get(packageName);
17899            if (pkg != null && pkg.staticSharedLibName != null) {
17900                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17901                        + " providing static shared library: " + pkg.staticSharedLibName);
17902                return false;
17903            }
17904            if (!ps.getInstalled(userId)) {
17905                // Can't block uninstall for an app that is not installed or enabled.
17906                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17907                return false;
17908            }
17909            ps.setBlockUninstall(blockUninstall, userId);
17910            mSettings.writePackageRestrictionsLPr(userId);
17911        }
17912        return true;
17913    }
17914
17915    @Override
17916    public boolean getBlockUninstallForUser(String packageName, int userId) {
17917        synchronized (mPackages) {
17918            PackageSetting ps = mSettings.mPackages.get(packageName);
17919            if (ps == null) {
17920                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17921                return false;
17922            }
17923            return ps.getBlockUninstall(userId);
17924        }
17925    }
17926
17927    @Override
17928    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17929        int callingUid = Binder.getCallingUid();
17930        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17931            throw new SecurityException(
17932                    "setRequiredForSystemUser can only be run by the system or root");
17933        }
17934        synchronized (mPackages) {
17935            PackageSetting ps = mSettings.mPackages.get(packageName);
17936            if (ps == null) {
17937                Log.w(TAG, "Package doesn't exist: " + packageName);
17938                return false;
17939            }
17940            if (systemUserApp) {
17941                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17942            } else {
17943                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17944            }
17945            mSettings.writeLPr();
17946        }
17947        return true;
17948    }
17949
17950    /*
17951     * This method handles package deletion in general
17952     */
17953    private boolean deletePackageLIF(String packageName, UserHandle user,
17954            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17955            PackageRemovedInfo outInfo, boolean writeSettings,
17956            PackageParser.Package replacingPackage) {
17957        if (packageName == null) {
17958            Slog.w(TAG, "Attempt to delete null packageName.");
17959            return false;
17960        }
17961
17962        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17963
17964        PackageSetting ps;
17965        synchronized (mPackages) {
17966            ps = mSettings.mPackages.get(packageName);
17967            if (ps == null) {
17968                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17969                return false;
17970            }
17971
17972            if (ps.parentPackageName != null && (!isSystemApp(ps)
17973                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17974                if (DEBUG_REMOVE) {
17975                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17976                            + ((user == null) ? UserHandle.USER_ALL : user));
17977                }
17978                final int removedUserId = (user != null) ? user.getIdentifier()
17979                        : UserHandle.USER_ALL;
17980                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17981                    return false;
17982                }
17983                markPackageUninstalledForUserLPw(ps, user);
17984                scheduleWritePackageRestrictionsLocked(user);
17985                return true;
17986            }
17987        }
17988
17989        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17990                && user.getIdentifier() != UserHandle.USER_ALL)) {
17991            // The caller is asking that the package only be deleted for a single
17992            // user.  To do this, we just mark its uninstalled state and delete
17993            // its data. If this is a system app, we only allow this to happen if
17994            // they have set the special DELETE_SYSTEM_APP which requests different
17995            // semantics than normal for uninstalling system apps.
17996            markPackageUninstalledForUserLPw(ps, user);
17997
17998            if (!isSystemApp(ps)) {
17999                // Do not uninstall the APK if an app should be cached
18000                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18001                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18002                    // Other user still have this package installed, so all
18003                    // we need to do is clear this user's data and save that
18004                    // it is uninstalled.
18005                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18006                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18007                        return false;
18008                    }
18009                    scheduleWritePackageRestrictionsLocked(user);
18010                    return true;
18011                } else {
18012                    // We need to set it back to 'installed' so the uninstall
18013                    // broadcasts will be sent correctly.
18014                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18015                    ps.setInstalled(true, user.getIdentifier());
18016                }
18017            } else {
18018                // This is a system app, so we assume that the
18019                // other users still have this package installed, so all
18020                // we need to do is clear this user's data and save that
18021                // it is uninstalled.
18022                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18023                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18024                    return false;
18025                }
18026                scheduleWritePackageRestrictionsLocked(user);
18027                return true;
18028            }
18029        }
18030
18031        // If we are deleting a composite package for all users, keep track
18032        // of result for each child.
18033        if (ps.childPackageNames != null && outInfo != null) {
18034            synchronized (mPackages) {
18035                final int childCount = ps.childPackageNames.size();
18036                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18037                for (int i = 0; i < childCount; i++) {
18038                    String childPackageName = ps.childPackageNames.get(i);
18039                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18040                    childInfo.removedPackage = childPackageName;
18041                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18042                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18043                    if (childPs != null) {
18044                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18045                    }
18046                }
18047            }
18048        }
18049
18050        boolean ret = false;
18051        if (isSystemApp(ps)) {
18052            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18053            // When an updated system application is deleted we delete the existing resources
18054            // as well and fall back to existing code in system partition
18055            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18056        } else {
18057            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18058            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18059                    outInfo, writeSettings, replacingPackage);
18060        }
18061
18062        // Take a note whether we deleted the package for all users
18063        if (outInfo != null) {
18064            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18065            if (outInfo.removedChildPackages != null) {
18066                synchronized (mPackages) {
18067                    final int childCount = outInfo.removedChildPackages.size();
18068                    for (int i = 0; i < childCount; i++) {
18069                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18070                        if (childInfo != null) {
18071                            childInfo.removedForAllUsers = mPackages.get(
18072                                    childInfo.removedPackage) == null;
18073                        }
18074                    }
18075                }
18076            }
18077            // If we uninstalled an update to a system app there may be some
18078            // child packages that appeared as they are declared in the system
18079            // app but were not declared in the update.
18080            if (isSystemApp(ps)) {
18081                synchronized (mPackages) {
18082                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18083                    final int childCount = (updatedPs.childPackageNames != null)
18084                            ? updatedPs.childPackageNames.size() : 0;
18085                    for (int i = 0; i < childCount; i++) {
18086                        String childPackageName = updatedPs.childPackageNames.get(i);
18087                        if (outInfo.removedChildPackages == null
18088                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18089                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18090                            if (childPs == null) {
18091                                continue;
18092                            }
18093                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18094                            installRes.name = childPackageName;
18095                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18096                            installRes.pkg = mPackages.get(childPackageName);
18097                            installRes.uid = childPs.pkg.applicationInfo.uid;
18098                            if (outInfo.appearedChildPackages == null) {
18099                                outInfo.appearedChildPackages = new ArrayMap<>();
18100                            }
18101                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18102                        }
18103                    }
18104                }
18105            }
18106        }
18107
18108        return ret;
18109    }
18110
18111    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18112        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18113                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18114        for (int nextUserId : userIds) {
18115            if (DEBUG_REMOVE) {
18116                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18117            }
18118            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18119                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18120                    false /*hidden*/, false /*suspended*/, null, null, null,
18121                    false /*blockUninstall*/,
18122                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18123                    PackageManager.INSTALL_REASON_UNKNOWN);
18124        }
18125    }
18126
18127    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18128            PackageRemovedInfo outInfo) {
18129        final PackageParser.Package pkg;
18130        synchronized (mPackages) {
18131            pkg = mPackages.get(ps.name);
18132        }
18133
18134        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18135                : new int[] {userId};
18136        for (int nextUserId : userIds) {
18137            if (DEBUG_REMOVE) {
18138                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18139                        + nextUserId);
18140            }
18141
18142            destroyAppDataLIF(pkg, userId,
18143                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18144            destroyAppProfilesLIF(pkg, userId);
18145            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18146            schedulePackageCleaning(ps.name, nextUserId, false);
18147            synchronized (mPackages) {
18148                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18149                    scheduleWritePackageRestrictionsLocked(nextUserId);
18150                }
18151                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18152            }
18153        }
18154
18155        if (outInfo != null) {
18156            outInfo.removedPackage = ps.name;
18157            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18158            outInfo.removedAppId = ps.appId;
18159            outInfo.removedUsers = userIds;
18160        }
18161
18162        return true;
18163    }
18164
18165    private final class ClearStorageConnection implements ServiceConnection {
18166        IMediaContainerService mContainerService;
18167
18168        @Override
18169        public void onServiceConnected(ComponentName name, IBinder service) {
18170            synchronized (this) {
18171                mContainerService = IMediaContainerService.Stub
18172                        .asInterface(Binder.allowBlocking(service));
18173                notifyAll();
18174            }
18175        }
18176
18177        @Override
18178        public void onServiceDisconnected(ComponentName name) {
18179        }
18180    }
18181
18182    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18183        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18184
18185        final boolean mounted;
18186        if (Environment.isExternalStorageEmulated()) {
18187            mounted = true;
18188        } else {
18189            final String status = Environment.getExternalStorageState();
18190
18191            mounted = status.equals(Environment.MEDIA_MOUNTED)
18192                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18193        }
18194
18195        if (!mounted) {
18196            return;
18197        }
18198
18199        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18200        int[] users;
18201        if (userId == UserHandle.USER_ALL) {
18202            users = sUserManager.getUserIds();
18203        } else {
18204            users = new int[] { userId };
18205        }
18206        final ClearStorageConnection conn = new ClearStorageConnection();
18207        if (mContext.bindServiceAsUser(
18208                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18209            try {
18210                for (int curUser : users) {
18211                    long timeout = SystemClock.uptimeMillis() + 5000;
18212                    synchronized (conn) {
18213                        long now;
18214                        while (conn.mContainerService == null &&
18215                                (now = SystemClock.uptimeMillis()) < timeout) {
18216                            try {
18217                                conn.wait(timeout - now);
18218                            } catch (InterruptedException e) {
18219                            }
18220                        }
18221                    }
18222                    if (conn.mContainerService == null) {
18223                        return;
18224                    }
18225
18226                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18227                    clearDirectory(conn.mContainerService,
18228                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18229                    if (allData) {
18230                        clearDirectory(conn.mContainerService,
18231                                userEnv.buildExternalStorageAppDataDirs(packageName));
18232                        clearDirectory(conn.mContainerService,
18233                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18234                    }
18235                }
18236            } finally {
18237                mContext.unbindService(conn);
18238            }
18239        }
18240    }
18241
18242    @Override
18243    public void clearApplicationProfileData(String packageName) {
18244        enforceSystemOrRoot("Only the system can clear all profile data");
18245
18246        final PackageParser.Package pkg;
18247        synchronized (mPackages) {
18248            pkg = mPackages.get(packageName);
18249        }
18250
18251        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18252            synchronized (mInstallLock) {
18253                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18254                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18255                        true /* removeBaseMarker */);
18256            }
18257        }
18258    }
18259
18260    @Override
18261    public void clearApplicationUserData(final String packageName,
18262            final IPackageDataObserver observer, final int userId) {
18263        mContext.enforceCallingOrSelfPermission(
18264                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18265
18266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18267                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18268
18269        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18270            throw new SecurityException("Cannot clear data for a protected package: "
18271                    + packageName);
18272        }
18273        // Queue up an async operation since the package deletion may take a little while.
18274        mHandler.post(new Runnable() {
18275            public void run() {
18276                mHandler.removeCallbacks(this);
18277                final boolean succeeded;
18278                try (PackageFreezer freezer = freezePackage(packageName,
18279                        "clearApplicationUserData")) {
18280                    synchronized (mInstallLock) {
18281                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18282                    }
18283                    clearExternalStorageDataSync(packageName, userId, true);
18284                    synchronized (mPackages) {
18285                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18286                                packageName, userId);
18287                    }
18288                }
18289                if (succeeded) {
18290                    // invoke DeviceStorageMonitor's update method to clear any notifications
18291                    DeviceStorageMonitorInternal dsm = LocalServices
18292                            .getService(DeviceStorageMonitorInternal.class);
18293                    if (dsm != null) {
18294                        dsm.checkMemory();
18295                    }
18296                }
18297                if(observer != null) {
18298                    try {
18299                        observer.onRemoveCompleted(packageName, succeeded);
18300                    } catch (RemoteException e) {
18301                        Log.i(TAG, "Observer no longer exists.");
18302                    }
18303                } //end if observer
18304            } //end run
18305        });
18306    }
18307
18308    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18309        if (packageName == null) {
18310            Slog.w(TAG, "Attempt to delete null packageName.");
18311            return false;
18312        }
18313
18314        // Try finding details about the requested package
18315        PackageParser.Package pkg;
18316        synchronized (mPackages) {
18317            pkg = mPackages.get(packageName);
18318            if (pkg == null) {
18319                final PackageSetting ps = mSettings.mPackages.get(packageName);
18320                if (ps != null) {
18321                    pkg = ps.pkg;
18322                }
18323            }
18324
18325            if (pkg == null) {
18326                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18327                return false;
18328            }
18329
18330            PackageSetting ps = (PackageSetting) pkg.mExtras;
18331            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18332        }
18333
18334        clearAppDataLIF(pkg, userId,
18335                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18336
18337        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18338        removeKeystoreDataIfNeeded(userId, appId);
18339
18340        UserManagerInternal umInternal = getUserManagerInternal();
18341        final int flags;
18342        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18343            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18344        } else if (umInternal.isUserRunning(userId)) {
18345            flags = StorageManager.FLAG_STORAGE_DE;
18346        } else {
18347            flags = 0;
18348        }
18349        prepareAppDataContentsLIF(pkg, userId, flags);
18350
18351        return true;
18352    }
18353
18354    /**
18355     * Reverts user permission state changes (permissions and flags) in
18356     * all packages for a given user.
18357     *
18358     * @param userId The device user for which to do a reset.
18359     */
18360    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18361        final int packageCount = mPackages.size();
18362        for (int i = 0; i < packageCount; i++) {
18363            PackageParser.Package pkg = mPackages.valueAt(i);
18364            PackageSetting ps = (PackageSetting) pkg.mExtras;
18365            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18366        }
18367    }
18368
18369    private void resetNetworkPolicies(int userId) {
18370        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18371    }
18372
18373    /**
18374     * Reverts user permission state changes (permissions and flags).
18375     *
18376     * @param ps The package for which to reset.
18377     * @param userId The device user for which to do a reset.
18378     */
18379    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18380            final PackageSetting ps, final int userId) {
18381        if (ps.pkg == null) {
18382            return;
18383        }
18384
18385        // These are flags that can change base on user actions.
18386        final int userSettableMask = FLAG_PERMISSION_USER_SET
18387                | FLAG_PERMISSION_USER_FIXED
18388                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18389                | FLAG_PERMISSION_REVIEW_REQUIRED;
18390
18391        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18392                | FLAG_PERMISSION_POLICY_FIXED;
18393
18394        boolean writeInstallPermissions = false;
18395        boolean writeRuntimePermissions = false;
18396
18397        final int permissionCount = ps.pkg.requestedPermissions.size();
18398        for (int i = 0; i < permissionCount; i++) {
18399            String permission = ps.pkg.requestedPermissions.get(i);
18400
18401            BasePermission bp = mSettings.mPermissions.get(permission);
18402            if (bp == null) {
18403                continue;
18404            }
18405
18406            // If shared user we just reset the state to which only this app contributed.
18407            if (ps.sharedUser != null) {
18408                boolean used = false;
18409                final int packageCount = ps.sharedUser.packages.size();
18410                for (int j = 0; j < packageCount; j++) {
18411                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18412                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18413                            && pkg.pkg.requestedPermissions.contains(permission)) {
18414                        used = true;
18415                        break;
18416                    }
18417                }
18418                if (used) {
18419                    continue;
18420                }
18421            }
18422
18423            PermissionsState permissionsState = ps.getPermissionsState();
18424
18425            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18426
18427            // Always clear the user settable flags.
18428            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18429                    bp.name) != null;
18430            // If permission review is enabled and this is a legacy app, mark the
18431            // permission as requiring a review as this is the initial state.
18432            int flags = 0;
18433            if (mPermissionReviewRequired
18434                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18435                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18436            }
18437            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18438                if (hasInstallState) {
18439                    writeInstallPermissions = true;
18440                } else {
18441                    writeRuntimePermissions = true;
18442                }
18443            }
18444
18445            // Below is only runtime permission handling.
18446            if (!bp.isRuntime()) {
18447                continue;
18448            }
18449
18450            // Never clobber system or policy.
18451            if ((oldFlags & policyOrSystemFlags) != 0) {
18452                continue;
18453            }
18454
18455            // If this permission was granted by default, make sure it is.
18456            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18457                if (permissionsState.grantRuntimePermission(bp, userId)
18458                        != PERMISSION_OPERATION_FAILURE) {
18459                    writeRuntimePermissions = true;
18460                }
18461            // If permission review is enabled the permissions for a legacy apps
18462            // are represented as constantly granted runtime ones, so don't revoke.
18463            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18464                // Otherwise, reset the permission.
18465                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18466                switch (revokeResult) {
18467                    case PERMISSION_OPERATION_SUCCESS:
18468                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18469                        writeRuntimePermissions = true;
18470                        final int appId = ps.appId;
18471                        mHandler.post(new Runnable() {
18472                            @Override
18473                            public void run() {
18474                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18475                            }
18476                        });
18477                    } break;
18478                }
18479            }
18480        }
18481
18482        // Synchronously write as we are taking permissions away.
18483        if (writeRuntimePermissions) {
18484            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18485        }
18486
18487        // Synchronously write as we are taking permissions away.
18488        if (writeInstallPermissions) {
18489            mSettings.writeLPr();
18490        }
18491    }
18492
18493    /**
18494     * Remove entries from the keystore daemon. Will only remove it if the
18495     * {@code appId} is valid.
18496     */
18497    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18498        if (appId < 0) {
18499            return;
18500        }
18501
18502        final KeyStore keyStore = KeyStore.getInstance();
18503        if (keyStore != null) {
18504            if (userId == UserHandle.USER_ALL) {
18505                for (final int individual : sUserManager.getUserIds()) {
18506                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18507                }
18508            } else {
18509                keyStore.clearUid(UserHandle.getUid(userId, appId));
18510            }
18511        } else {
18512            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18513        }
18514    }
18515
18516    @Override
18517    public void deleteApplicationCacheFiles(final String packageName,
18518            final IPackageDataObserver observer) {
18519        final int userId = UserHandle.getCallingUserId();
18520        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18521    }
18522
18523    @Override
18524    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18525            final IPackageDataObserver observer) {
18526        mContext.enforceCallingOrSelfPermission(
18527                android.Manifest.permission.DELETE_CACHE_FILES, null);
18528        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18529                /* requireFullPermission= */ true, /* checkShell= */ false,
18530                "delete application cache files");
18531
18532        final PackageParser.Package pkg;
18533        synchronized (mPackages) {
18534            pkg = mPackages.get(packageName);
18535        }
18536
18537        // Queue up an async operation since the package deletion may take a little while.
18538        mHandler.post(new Runnable() {
18539            public void run() {
18540                synchronized (mInstallLock) {
18541                    final int flags = StorageManager.FLAG_STORAGE_DE
18542                            | StorageManager.FLAG_STORAGE_CE;
18543                    // We're only clearing cache files, so we don't care if the
18544                    // app is unfrozen and still able to run
18545                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18546                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18547                }
18548                clearExternalStorageDataSync(packageName, userId, false);
18549                if (observer != null) {
18550                    try {
18551                        observer.onRemoveCompleted(packageName, true);
18552                    } catch (RemoteException e) {
18553                        Log.i(TAG, "Observer no longer exists.");
18554                    }
18555                }
18556            }
18557        });
18558    }
18559
18560    @Override
18561    public void getPackageSizeInfo(final String packageName, int userHandle,
18562            final IPackageStatsObserver observer) {
18563        mContext.enforceCallingOrSelfPermission(
18564                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18565        if (packageName == null) {
18566            throw new IllegalArgumentException("Attempt to get size of null packageName");
18567        }
18568
18569        PackageStats stats = new PackageStats(packageName, userHandle);
18570
18571        /*
18572         * Queue up an async operation since the package measurement may take a
18573         * little while.
18574         */
18575        Message msg = mHandler.obtainMessage(INIT_COPY);
18576        msg.obj = new MeasureParams(stats, observer);
18577        mHandler.sendMessage(msg);
18578    }
18579
18580    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18581        final PackageSetting ps;
18582        synchronized (mPackages) {
18583            ps = mSettings.mPackages.get(packageName);
18584            if (ps == null) {
18585                Slog.w(TAG, "Failed to find settings for " + packageName);
18586                return false;
18587            }
18588        }
18589
18590        final String[] packageNames = { packageName };
18591        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18592        final String[] codePaths = { ps.codePathString };
18593
18594        try {
18595            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18596                    ps.appId, ceDataInodes, codePaths, stats);
18597
18598            // For now, ignore code size of packages on system partition
18599            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18600                stats.codeSize = 0;
18601            }
18602
18603            // External clients expect these to be tracked separately
18604            stats.dataSize -= stats.cacheSize;
18605
18606        } catch (InstallerException e) {
18607            Slog.w(TAG, String.valueOf(e));
18608            return false;
18609        }
18610
18611        return true;
18612    }
18613
18614    private int getUidTargetSdkVersionLockedLPr(int uid) {
18615        Object obj = mSettings.getUserIdLPr(uid);
18616        if (obj instanceof SharedUserSetting) {
18617            final SharedUserSetting sus = (SharedUserSetting) obj;
18618            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18619            final Iterator<PackageSetting> it = sus.packages.iterator();
18620            while (it.hasNext()) {
18621                final PackageSetting ps = it.next();
18622                if (ps.pkg != null) {
18623                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18624                    if (v < vers) vers = v;
18625                }
18626            }
18627            return vers;
18628        } else if (obj instanceof PackageSetting) {
18629            final PackageSetting ps = (PackageSetting) obj;
18630            if (ps.pkg != null) {
18631                return ps.pkg.applicationInfo.targetSdkVersion;
18632            }
18633        }
18634        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18635    }
18636
18637    @Override
18638    public void addPreferredActivity(IntentFilter filter, int match,
18639            ComponentName[] set, ComponentName activity, int userId) {
18640        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18641                "Adding preferred");
18642    }
18643
18644    private void addPreferredActivityInternal(IntentFilter filter, int match,
18645            ComponentName[] set, ComponentName activity, boolean always, int userId,
18646            String opname) {
18647        // writer
18648        int callingUid = Binder.getCallingUid();
18649        enforceCrossUserPermission(callingUid, userId,
18650                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18651        if (filter.countActions() == 0) {
18652            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18653            return;
18654        }
18655        synchronized (mPackages) {
18656            if (mContext.checkCallingOrSelfPermission(
18657                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18658                    != PackageManager.PERMISSION_GRANTED) {
18659                if (getUidTargetSdkVersionLockedLPr(callingUid)
18660                        < Build.VERSION_CODES.FROYO) {
18661                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18662                            + callingUid);
18663                    return;
18664                }
18665                mContext.enforceCallingOrSelfPermission(
18666                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18667            }
18668
18669            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18670            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18671                    + userId + ":");
18672            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18673            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18674            scheduleWritePackageRestrictionsLocked(userId);
18675            postPreferredActivityChangedBroadcast(userId);
18676        }
18677    }
18678
18679    private void postPreferredActivityChangedBroadcast(int userId) {
18680        mHandler.post(() -> {
18681            final IActivityManager am = ActivityManager.getService();
18682            if (am == null) {
18683                return;
18684            }
18685
18686            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18687            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18688            try {
18689                am.broadcastIntent(null, intent, null, null,
18690                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18691                        null, false, false, userId);
18692            } catch (RemoteException e) {
18693            }
18694        });
18695    }
18696
18697    @Override
18698    public void replacePreferredActivity(IntentFilter filter, int match,
18699            ComponentName[] set, ComponentName activity, int userId) {
18700        if (filter.countActions() != 1) {
18701            throw new IllegalArgumentException(
18702                    "replacePreferredActivity expects filter to have only 1 action.");
18703        }
18704        if (filter.countDataAuthorities() != 0
18705                || filter.countDataPaths() != 0
18706                || filter.countDataSchemes() > 1
18707                || filter.countDataTypes() != 0) {
18708            throw new IllegalArgumentException(
18709                    "replacePreferredActivity expects filter to have no data authorities, " +
18710                    "paths, or types; and at most one scheme.");
18711        }
18712
18713        final int callingUid = Binder.getCallingUid();
18714        enforceCrossUserPermission(callingUid, userId,
18715                true /* requireFullPermission */, false /* checkShell */,
18716                "replace preferred activity");
18717        synchronized (mPackages) {
18718            if (mContext.checkCallingOrSelfPermission(
18719                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18720                    != PackageManager.PERMISSION_GRANTED) {
18721                if (getUidTargetSdkVersionLockedLPr(callingUid)
18722                        < Build.VERSION_CODES.FROYO) {
18723                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18724                            + Binder.getCallingUid());
18725                    return;
18726                }
18727                mContext.enforceCallingOrSelfPermission(
18728                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18729            }
18730
18731            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18732            if (pir != null) {
18733                // Get all of the existing entries that exactly match this filter.
18734                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18735                if (existing != null && existing.size() == 1) {
18736                    PreferredActivity cur = existing.get(0);
18737                    if (DEBUG_PREFERRED) {
18738                        Slog.i(TAG, "Checking replace of preferred:");
18739                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18740                        if (!cur.mPref.mAlways) {
18741                            Slog.i(TAG, "  -- CUR; not mAlways!");
18742                        } else {
18743                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18744                            Slog.i(TAG, "  -- CUR: mSet="
18745                                    + Arrays.toString(cur.mPref.mSetComponents));
18746                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18747                            Slog.i(TAG, "  -- NEW: mMatch="
18748                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18749                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18750                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18751                        }
18752                    }
18753                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18754                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18755                            && cur.mPref.sameSet(set)) {
18756                        // Setting the preferred activity to what it happens to be already
18757                        if (DEBUG_PREFERRED) {
18758                            Slog.i(TAG, "Replacing with same preferred activity "
18759                                    + cur.mPref.mShortComponent + " for user "
18760                                    + userId + ":");
18761                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18762                        }
18763                        return;
18764                    }
18765                }
18766
18767                if (existing != null) {
18768                    if (DEBUG_PREFERRED) {
18769                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18770                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18771                    }
18772                    for (int i = 0; i < existing.size(); i++) {
18773                        PreferredActivity pa = existing.get(i);
18774                        if (DEBUG_PREFERRED) {
18775                            Slog.i(TAG, "Removing existing preferred activity "
18776                                    + pa.mPref.mComponent + ":");
18777                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18778                        }
18779                        pir.removeFilter(pa);
18780                    }
18781                }
18782            }
18783            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18784                    "Replacing preferred");
18785        }
18786    }
18787
18788    @Override
18789    public void clearPackagePreferredActivities(String packageName) {
18790        final int uid = Binder.getCallingUid();
18791        // writer
18792        synchronized (mPackages) {
18793            PackageParser.Package pkg = mPackages.get(packageName);
18794            if (pkg == null || pkg.applicationInfo.uid != uid) {
18795                if (mContext.checkCallingOrSelfPermission(
18796                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18797                        != PackageManager.PERMISSION_GRANTED) {
18798                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18799                            < Build.VERSION_CODES.FROYO) {
18800                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18801                                + Binder.getCallingUid());
18802                        return;
18803                    }
18804                    mContext.enforceCallingOrSelfPermission(
18805                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18806                }
18807            }
18808
18809            int user = UserHandle.getCallingUserId();
18810            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18811                scheduleWritePackageRestrictionsLocked(user);
18812            }
18813        }
18814    }
18815
18816    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18817    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18818        ArrayList<PreferredActivity> removed = null;
18819        boolean changed = false;
18820        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18821            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18822            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18823            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18824                continue;
18825            }
18826            Iterator<PreferredActivity> it = pir.filterIterator();
18827            while (it.hasNext()) {
18828                PreferredActivity pa = it.next();
18829                // Mark entry for removal only if it matches the package name
18830                // and the entry is of type "always".
18831                if (packageName == null ||
18832                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18833                                && pa.mPref.mAlways)) {
18834                    if (removed == null) {
18835                        removed = new ArrayList<PreferredActivity>();
18836                    }
18837                    removed.add(pa);
18838                }
18839            }
18840            if (removed != null) {
18841                for (int j=0; j<removed.size(); j++) {
18842                    PreferredActivity pa = removed.get(j);
18843                    pir.removeFilter(pa);
18844                }
18845                changed = true;
18846            }
18847        }
18848        if (changed) {
18849            postPreferredActivityChangedBroadcast(userId);
18850        }
18851        return changed;
18852    }
18853
18854    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18855    private void clearIntentFilterVerificationsLPw(int userId) {
18856        final int packageCount = mPackages.size();
18857        for (int i = 0; i < packageCount; i++) {
18858            PackageParser.Package pkg = mPackages.valueAt(i);
18859            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18860        }
18861    }
18862
18863    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18864    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18865        if (userId == UserHandle.USER_ALL) {
18866            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18867                    sUserManager.getUserIds())) {
18868                for (int oneUserId : sUserManager.getUserIds()) {
18869                    scheduleWritePackageRestrictionsLocked(oneUserId);
18870                }
18871            }
18872        } else {
18873            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18874                scheduleWritePackageRestrictionsLocked(userId);
18875            }
18876        }
18877    }
18878
18879    void clearDefaultBrowserIfNeeded(String packageName) {
18880        for (int oneUserId : sUserManager.getUserIds()) {
18881            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18882            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18883            if (packageName.equals(defaultBrowserPackageName)) {
18884                setDefaultBrowserPackageName(null, oneUserId);
18885            }
18886        }
18887    }
18888
18889    @Override
18890    public void resetApplicationPreferences(int userId) {
18891        mContext.enforceCallingOrSelfPermission(
18892                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18893        final long identity = Binder.clearCallingIdentity();
18894        // writer
18895        try {
18896            synchronized (mPackages) {
18897                clearPackagePreferredActivitiesLPw(null, userId);
18898                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18899                // TODO: We have to reset the default SMS and Phone. This requires
18900                // significant refactoring to keep all default apps in the package
18901                // manager (cleaner but more work) or have the services provide
18902                // callbacks to the package manager to request a default app reset.
18903                applyFactoryDefaultBrowserLPw(userId);
18904                clearIntentFilterVerificationsLPw(userId);
18905                primeDomainVerificationsLPw(userId);
18906                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18907                scheduleWritePackageRestrictionsLocked(userId);
18908            }
18909            resetNetworkPolicies(userId);
18910        } finally {
18911            Binder.restoreCallingIdentity(identity);
18912        }
18913    }
18914
18915    @Override
18916    public int getPreferredActivities(List<IntentFilter> outFilters,
18917            List<ComponentName> outActivities, String packageName) {
18918
18919        int num = 0;
18920        final int userId = UserHandle.getCallingUserId();
18921        // reader
18922        synchronized (mPackages) {
18923            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18924            if (pir != null) {
18925                final Iterator<PreferredActivity> it = pir.filterIterator();
18926                while (it.hasNext()) {
18927                    final PreferredActivity pa = it.next();
18928                    if (packageName == null
18929                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18930                                    && pa.mPref.mAlways)) {
18931                        if (outFilters != null) {
18932                            outFilters.add(new IntentFilter(pa));
18933                        }
18934                        if (outActivities != null) {
18935                            outActivities.add(pa.mPref.mComponent);
18936                        }
18937                    }
18938                }
18939            }
18940        }
18941
18942        return num;
18943    }
18944
18945    @Override
18946    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18947            int userId) {
18948        int callingUid = Binder.getCallingUid();
18949        if (callingUid != Process.SYSTEM_UID) {
18950            throw new SecurityException(
18951                    "addPersistentPreferredActivity can only be run by the system");
18952        }
18953        if (filter.countActions() == 0) {
18954            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18955            return;
18956        }
18957        synchronized (mPackages) {
18958            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18959                    ":");
18960            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18961            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18962                    new PersistentPreferredActivity(filter, activity));
18963            scheduleWritePackageRestrictionsLocked(userId);
18964            postPreferredActivityChangedBroadcast(userId);
18965        }
18966    }
18967
18968    @Override
18969    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18970        int callingUid = Binder.getCallingUid();
18971        if (callingUid != Process.SYSTEM_UID) {
18972            throw new SecurityException(
18973                    "clearPackagePersistentPreferredActivities can only be run by the system");
18974        }
18975        ArrayList<PersistentPreferredActivity> removed = null;
18976        boolean changed = false;
18977        synchronized (mPackages) {
18978            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18979                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18980                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18981                        .valueAt(i);
18982                if (userId != thisUserId) {
18983                    continue;
18984                }
18985                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18986                while (it.hasNext()) {
18987                    PersistentPreferredActivity ppa = it.next();
18988                    // Mark entry for removal only if it matches the package name.
18989                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18990                        if (removed == null) {
18991                            removed = new ArrayList<PersistentPreferredActivity>();
18992                        }
18993                        removed.add(ppa);
18994                    }
18995                }
18996                if (removed != null) {
18997                    for (int j=0; j<removed.size(); j++) {
18998                        PersistentPreferredActivity ppa = removed.get(j);
18999                        ppir.removeFilter(ppa);
19000                    }
19001                    changed = true;
19002                }
19003            }
19004
19005            if (changed) {
19006                scheduleWritePackageRestrictionsLocked(userId);
19007                postPreferredActivityChangedBroadcast(userId);
19008            }
19009        }
19010    }
19011
19012    /**
19013     * Common machinery for picking apart a restored XML blob and passing
19014     * it to a caller-supplied functor to be applied to the running system.
19015     */
19016    private void restoreFromXml(XmlPullParser parser, int userId,
19017            String expectedStartTag, BlobXmlRestorer functor)
19018            throws IOException, XmlPullParserException {
19019        int type;
19020        while ((type = parser.next()) != XmlPullParser.START_TAG
19021                && type != XmlPullParser.END_DOCUMENT) {
19022        }
19023        if (type != XmlPullParser.START_TAG) {
19024            // oops didn't find a start tag?!
19025            if (DEBUG_BACKUP) {
19026                Slog.e(TAG, "Didn't find start tag during restore");
19027            }
19028            return;
19029        }
19030Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19031        // this is supposed to be TAG_PREFERRED_BACKUP
19032        if (!expectedStartTag.equals(parser.getName())) {
19033            if (DEBUG_BACKUP) {
19034                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19035            }
19036            return;
19037        }
19038
19039        // skip interfering stuff, then we're aligned with the backing implementation
19040        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19041Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19042        functor.apply(parser, userId);
19043    }
19044
19045    private interface BlobXmlRestorer {
19046        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19047    }
19048
19049    /**
19050     * Non-Binder method, support for the backup/restore mechanism: write the
19051     * full set of preferred activities in its canonical XML format.  Returns the
19052     * XML output as a byte array, or null if there is none.
19053     */
19054    @Override
19055    public byte[] getPreferredActivityBackup(int userId) {
19056        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19057            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19058        }
19059
19060        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19061        try {
19062            final XmlSerializer serializer = new FastXmlSerializer();
19063            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19064            serializer.startDocument(null, true);
19065            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19066
19067            synchronized (mPackages) {
19068                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19069            }
19070
19071            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19072            serializer.endDocument();
19073            serializer.flush();
19074        } catch (Exception e) {
19075            if (DEBUG_BACKUP) {
19076                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19077            }
19078            return null;
19079        }
19080
19081        return dataStream.toByteArray();
19082    }
19083
19084    @Override
19085    public void restorePreferredActivities(byte[] backup, int userId) {
19086        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19087            throw new SecurityException("Only the system may call restorePreferredActivities()");
19088        }
19089
19090        try {
19091            final XmlPullParser parser = Xml.newPullParser();
19092            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19093            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19094                    new BlobXmlRestorer() {
19095                        @Override
19096                        public void apply(XmlPullParser parser, int userId)
19097                                throws XmlPullParserException, IOException {
19098                            synchronized (mPackages) {
19099                                mSettings.readPreferredActivitiesLPw(parser, userId);
19100                            }
19101                        }
19102                    } );
19103        } catch (Exception e) {
19104            if (DEBUG_BACKUP) {
19105                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19106            }
19107        }
19108    }
19109
19110    /**
19111     * Non-Binder method, support for the backup/restore mechanism: write the
19112     * default browser (etc) settings in its canonical XML format.  Returns the default
19113     * browser XML representation as a byte array, or null if there is none.
19114     */
19115    @Override
19116    public byte[] getDefaultAppsBackup(int userId) {
19117        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19118            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19119        }
19120
19121        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19122        try {
19123            final XmlSerializer serializer = new FastXmlSerializer();
19124            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19125            serializer.startDocument(null, true);
19126            serializer.startTag(null, TAG_DEFAULT_APPS);
19127
19128            synchronized (mPackages) {
19129                mSettings.writeDefaultAppsLPr(serializer, userId);
19130            }
19131
19132            serializer.endTag(null, TAG_DEFAULT_APPS);
19133            serializer.endDocument();
19134            serializer.flush();
19135        } catch (Exception e) {
19136            if (DEBUG_BACKUP) {
19137                Slog.e(TAG, "Unable to write default apps for backup", e);
19138            }
19139            return null;
19140        }
19141
19142        return dataStream.toByteArray();
19143    }
19144
19145    @Override
19146    public void restoreDefaultApps(byte[] backup, int userId) {
19147        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19148            throw new SecurityException("Only the system may call restoreDefaultApps()");
19149        }
19150
19151        try {
19152            final XmlPullParser parser = Xml.newPullParser();
19153            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19154            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19155                    new BlobXmlRestorer() {
19156                        @Override
19157                        public void apply(XmlPullParser parser, int userId)
19158                                throws XmlPullParserException, IOException {
19159                            synchronized (mPackages) {
19160                                mSettings.readDefaultAppsLPw(parser, userId);
19161                            }
19162                        }
19163                    } );
19164        } catch (Exception e) {
19165            if (DEBUG_BACKUP) {
19166                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19167            }
19168        }
19169    }
19170
19171    @Override
19172    public byte[] getIntentFilterVerificationBackup(int userId) {
19173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19174            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19175        }
19176
19177        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19178        try {
19179            final XmlSerializer serializer = new FastXmlSerializer();
19180            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19181            serializer.startDocument(null, true);
19182            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19183
19184            synchronized (mPackages) {
19185                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19186            }
19187
19188            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19189            serializer.endDocument();
19190            serializer.flush();
19191        } catch (Exception e) {
19192            if (DEBUG_BACKUP) {
19193                Slog.e(TAG, "Unable to write default apps for backup", e);
19194            }
19195            return null;
19196        }
19197
19198        return dataStream.toByteArray();
19199    }
19200
19201    @Override
19202    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19203        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19204            throw new SecurityException("Only the system may call restorePreferredActivities()");
19205        }
19206
19207        try {
19208            final XmlPullParser parser = Xml.newPullParser();
19209            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19210            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19211                    new BlobXmlRestorer() {
19212                        @Override
19213                        public void apply(XmlPullParser parser, int userId)
19214                                throws XmlPullParserException, IOException {
19215                            synchronized (mPackages) {
19216                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19217                                mSettings.writeLPr();
19218                            }
19219                        }
19220                    } );
19221        } catch (Exception e) {
19222            if (DEBUG_BACKUP) {
19223                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19224            }
19225        }
19226    }
19227
19228    @Override
19229    public byte[] getPermissionGrantBackup(int userId) {
19230        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19231            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19232        }
19233
19234        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19235        try {
19236            final XmlSerializer serializer = new FastXmlSerializer();
19237            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19238            serializer.startDocument(null, true);
19239            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19240
19241            synchronized (mPackages) {
19242                serializeRuntimePermissionGrantsLPr(serializer, userId);
19243            }
19244
19245            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19246            serializer.endDocument();
19247            serializer.flush();
19248        } catch (Exception e) {
19249            if (DEBUG_BACKUP) {
19250                Slog.e(TAG, "Unable to write default apps for backup", e);
19251            }
19252            return null;
19253        }
19254
19255        return dataStream.toByteArray();
19256    }
19257
19258    @Override
19259    public void restorePermissionGrants(byte[] backup, int userId) {
19260        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19261            throw new SecurityException("Only the system may call restorePermissionGrants()");
19262        }
19263
19264        try {
19265            final XmlPullParser parser = Xml.newPullParser();
19266            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19267            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19268                    new BlobXmlRestorer() {
19269                        @Override
19270                        public void apply(XmlPullParser parser, int userId)
19271                                throws XmlPullParserException, IOException {
19272                            synchronized (mPackages) {
19273                                processRestoredPermissionGrantsLPr(parser, userId);
19274                            }
19275                        }
19276                    } );
19277        } catch (Exception e) {
19278            if (DEBUG_BACKUP) {
19279                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19280            }
19281        }
19282    }
19283
19284    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19285            throws IOException {
19286        serializer.startTag(null, TAG_ALL_GRANTS);
19287
19288        final int N = mSettings.mPackages.size();
19289        for (int i = 0; i < N; i++) {
19290            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19291            boolean pkgGrantsKnown = false;
19292
19293            PermissionsState packagePerms = ps.getPermissionsState();
19294
19295            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19296                final int grantFlags = state.getFlags();
19297                // only look at grants that are not system/policy fixed
19298                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19299                    final boolean isGranted = state.isGranted();
19300                    // And only back up the user-twiddled state bits
19301                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19302                        final String packageName = mSettings.mPackages.keyAt(i);
19303                        if (!pkgGrantsKnown) {
19304                            serializer.startTag(null, TAG_GRANT);
19305                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19306                            pkgGrantsKnown = true;
19307                        }
19308
19309                        final boolean userSet =
19310                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19311                        final boolean userFixed =
19312                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19313                        final boolean revoke =
19314                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19315
19316                        serializer.startTag(null, TAG_PERMISSION);
19317                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19318                        if (isGranted) {
19319                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19320                        }
19321                        if (userSet) {
19322                            serializer.attribute(null, ATTR_USER_SET, "true");
19323                        }
19324                        if (userFixed) {
19325                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19326                        }
19327                        if (revoke) {
19328                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19329                        }
19330                        serializer.endTag(null, TAG_PERMISSION);
19331                    }
19332                }
19333            }
19334
19335            if (pkgGrantsKnown) {
19336                serializer.endTag(null, TAG_GRANT);
19337            }
19338        }
19339
19340        serializer.endTag(null, TAG_ALL_GRANTS);
19341    }
19342
19343    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19344            throws XmlPullParserException, IOException {
19345        String pkgName = null;
19346        int outerDepth = parser.getDepth();
19347        int type;
19348        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19349                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19350            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19351                continue;
19352            }
19353
19354            final String tagName = parser.getName();
19355            if (tagName.equals(TAG_GRANT)) {
19356                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19357                if (DEBUG_BACKUP) {
19358                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19359                }
19360            } else if (tagName.equals(TAG_PERMISSION)) {
19361
19362                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19363                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19364
19365                int newFlagSet = 0;
19366                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19367                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19368                }
19369                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19370                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19371                }
19372                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19373                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19374                }
19375                if (DEBUG_BACKUP) {
19376                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19377                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19378                }
19379                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19380                if (ps != null) {
19381                    // Already installed so we apply the grant immediately
19382                    if (DEBUG_BACKUP) {
19383                        Slog.v(TAG, "        + already installed; applying");
19384                    }
19385                    PermissionsState perms = ps.getPermissionsState();
19386                    BasePermission bp = mSettings.mPermissions.get(permName);
19387                    if (bp != null) {
19388                        if (isGranted) {
19389                            perms.grantRuntimePermission(bp, userId);
19390                        }
19391                        if (newFlagSet != 0) {
19392                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19393                        }
19394                    }
19395                } else {
19396                    // Need to wait for post-restore install to apply the grant
19397                    if (DEBUG_BACKUP) {
19398                        Slog.v(TAG, "        - not yet installed; saving for later");
19399                    }
19400                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19401                            isGranted, newFlagSet, userId);
19402                }
19403            } else {
19404                PackageManagerService.reportSettingsProblem(Log.WARN,
19405                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19406                XmlUtils.skipCurrentTag(parser);
19407            }
19408        }
19409
19410        scheduleWriteSettingsLocked();
19411        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19412    }
19413
19414    @Override
19415    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19416            int sourceUserId, int targetUserId, int flags) {
19417        mContext.enforceCallingOrSelfPermission(
19418                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19419        int callingUid = Binder.getCallingUid();
19420        enforceOwnerRights(ownerPackage, callingUid);
19421        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19422        if (intentFilter.countActions() == 0) {
19423            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19424            return;
19425        }
19426        synchronized (mPackages) {
19427            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19428                    ownerPackage, targetUserId, flags);
19429            CrossProfileIntentResolver resolver =
19430                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19431            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19432            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19433            if (existing != null) {
19434                int size = existing.size();
19435                for (int i = 0; i < size; i++) {
19436                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19437                        return;
19438                    }
19439                }
19440            }
19441            resolver.addFilter(newFilter);
19442            scheduleWritePackageRestrictionsLocked(sourceUserId);
19443        }
19444    }
19445
19446    @Override
19447    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19448        mContext.enforceCallingOrSelfPermission(
19449                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19450        int callingUid = Binder.getCallingUid();
19451        enforceOwnerRights(ownerPackage, callingUid);
19452        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19453        synchronized (mPackages) {
19454            CrossProfileIntentResolver resolver =
19455                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19456            ArraySet<CrossProfileIntentFilter> set =
19457                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19458            for (CrossProfileIntentFilter filter : set) {
19459                if (filter.getOwnerPackage().equals(ownerPackage)) {
19460                    resolver.removeFilter(filter);
19461                }
19462            }
19463            scheduleWritePackageRestrictionsLocked(sourceUserId);
19464        }
19465    }
19466
19467    // Enforcing that callingUid is owning pkg on userId
19468    private void enforceOwnerRights(String pkg, int callingUid) {
19469        // The system owns everything.
19470        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19471            return;
19472        }
19473        int callingUserId = UserHandle.getUserId(callingUid);
19474        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19475        if (pi == null) {
19476            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19477                    + callingUserId);
19478        }
19479        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19480            throw new SecurityException("Calling uid " + callingUid
19481                    + " does not own package " + pkg);
19482        }
19483    }
19484
19485    @Override
19486    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19487        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19488    }
19489
19490    private Intent getHomeIntent() {
19491        Intent intent = new Intent(Intent.ACTION_MAIN);
19492        intent.addCategory(Intent.CATEGORY_HOME);
19493        intent.addCategory(Intent.CATEGORY_DEFAULT);
19494        return intent;
19495    }
19496
19497    private IntentFilter getHomeFilter() {
19498        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19499        filter.addCategory(Intent.CATEGORY_HOME);
19500        filter.addCategory(Intent.CATEGORY_DEFAULT);
19501        return filter;
19502    }
19503
19504    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19505            int userId) {
19506        Intent intent  = getHomeIntent();
19507        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19508                PackageManager.GET_META_DATA, userId);
19509        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19510                true, false, false, userId);
19511
19512        allHomeCandidates.clear();
19513        if (list != null) {
19514            for (ResolveInfo ri : list) {
19515                allHomeCandidates.add(ri);
19516            }
19517        }
19518        return (preferred == null || preferred.activityInfo == null)
19519                ? null
19520                : new ComponentName(preferred.activityInfo.packageName,
19521                        preferred.activityInfo.name);
19522    }
19523
19524    @Override
19525    public void setHomeActivity(ComponentName comp, int userId) {
19526        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19527        getHomeActivitiesAsUser(homeActivities, userId);
19528
19529        boolean found = false;
19530
19531        final int size = homeActivities.size();
19532        final ComponentName[] set = new ComponentName[size];
19533        for (int i = 0; i < size; i++) {
19534            final ResolveInfo candidate = homeActivities.get(i);
19535            final ActivityInfo info = candidate.activityInfo;
19536            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19537            set[i] = activityName;
19538            if (!found && activityName.equals(comp)) {
19539                found = true;
19540            }
19541        }
19542        if (!found) {
19543            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19544                    + userId);
19545        }
19546        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19547                set, comp, userId);
19548    }
19549
19550    private @Nullable String getSetupWizardPackageName() {
19551        final Intent intent = new Intent(Intent.ACTION_MAIN);
19552        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19553
19554        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19555                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19556                        | MATCH_DISABLED_COMPONENTS,
19557                UserHandle.myUserId());
19558        if (matches.size() == 1) {
19559            return matches.get(0).getComponentInfo().packageName;
19560        } else {
19561            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19562                    + ": matches=" + matches);
19563            return null;
19564        }
19565    }
19566
19567    private @Nullable String getStorageManagerPackageName() {
19568        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19569
19570        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19571                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19572                        | MATCH_DISABLED_COMPONENTS,
19573                UserHandle.myUserId());
19574        if (matches.size() == 1) {
19575            return matches.get(0).getComponentInfo().packageName;
19576        } else {
19577            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19578                    + matches.size() + ": matches=" + matches);
19579            return null;
19580        }
19581    }
19582
19583    @Override
19584    public void setApplicationEnabledSetting(String appPackageName,
19585            int newState, int flags, int userId, String callingPackage) {
19586        if (!sUserManager.exists(userId)) return;
19587        if (callingPackage == null) {
19588            callingPackage = Integer.toString(Binder.getCallingUid());
19589        }
19590        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19591    }
19592
19593    @Override
19594    public void setComponentEnabledSetting(ComponentName componentName,
19595            int newState, int flags, int userId) {
19596        if (!sUserManager.exists(userId)) return;
19597        setEnabledSetting(componentName.getPackageName(),
19598                componentName.getClassName(), newState, flags, userId, null);
19599    }
19600
19601    private void setEnabledSetting(final String packageName, String className, int newState,
19602            final int flags, int userId, String callingPackage) {
19603        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19604              || newState == COMPONENT_ENABLED_STATE_ENABLED
19605              || newState == COMPONENT_ENABLED_STATE_DISABLED
19606              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19607              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19608            throw new IllegalArgumentException("Invalid new component state: "
19609                    + newState);
19610        }
19611        PackageSetting pkgSetting;
19612        final int uid = Binder.getCallingUid();
19613        final int permission;
19614        if (uid == Process.SYSTEM_UID) {
19615            permission = PackageManager.PERMISSION_GRANTED;
19616        } else {
19617            permission = mContext.checkCallingOrSelfPermission(
19618                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19619        }
19620        enforceCrossUserPermission(uid, userId,
19621                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19622        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19623        boolean sendNow = false;
19624        boolean isApp = (className == null);
19625        String componentName = isApp ? packageName : className;
19626        int packageUid = -1;
19627        ArrayList<String> components;
19628
19629        // writer
19630        synchronized (mPackages) {
19631            pkgSetting = mSettings.mPackages.get(packageName);
19632            if (pkgSetting == null) {
19633                if (className == null) {
19634                    throw new IllegalArgumentException("Unknown package: " + packageName);
19635                }
19636                throw new IllegalArgumentException(
19637                        "Unknown component: " + packageName + "/" + className);
19638            }
19639        }
19640
19641        // Limit who can change which apps
19642        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19643            // Don't allow apps that don't have permission to modify other apps
19644            if (!allowedByPermission) {
19645                throw new SecurityException(
19646                        "Permission Denial: attempt to change component state from pid="
19647                        + Binder.getCallingPid()
19648                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19649            }
19650            // Don't allow changing protected packages.
19651            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19652                throw new SecurityException("Cannot disable a protected package: " + packageName);
19653            }
19654        }
19655
19656        synchronized (mPackages) {
19657            if (uid == Process.SHELL_UID
19658                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19659                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19660                // unless it is a test package.
19661                int oldState = pkgSetting.getEnabled(userId);
19662                if (className == null
19663                    &&
19664                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19665                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19666                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19667                    &&
19668                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19669                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19670                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19671                    // ok
19672                } else {
19673                    throw new SecurityException(
19674                            "Shell cannot change component state for " + packageName + "/"
19675                            + className + " to " + newState);
19676                }
19677            }
19678            if (className == null) {
19679                // We're dealing with an application/package level state change
19680                if (pkgSetting.getEnabled(userId) == newState) {
19681                    // Nothing to do
19682                    return;
19683                }
19684                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19685                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19686                    // Don't care about who enables an app.
19687                    callingPackage = null;
19688                }
19689                pkgSetting.setEnabled(newState, userId, callingPackage);
19690                // pkgSetting.pkg.mSetEnabled = newState;
19691            } else {
19692                // We're dealing with a component level state change
19693                // First, verify that this is a valid class name.
19694                PackageParser.Package pkg = pkgSetting.pkg;
19695                if (pkg == null || !pkg.hasComponentClassName(className)) {
19696                    if (pkg != null &&
19697                            pkg.applicationInfo.targetSdkVersion >=
19698                                    Build.VERSION_CODES.JELLY_BEAN) {
19699                        throw new IllegalArgumentException("Component class " + className
19700                                + " does not exist in " + packageName);
19701                    } else {
19702                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19703                                + className + " does not exist in " + packageName);
19704                    }
19705                }
19706                switch (newState) {
19707                case COMPONENT_ENABLED_STATE_ENABLED:
19708                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19709                        return;
19710                    }
19711                    break;
19712                case COMPONENT_ENABLED_STATE_DISABLED:
19713                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19714                        return;
19715                    }
19716                    break;
19717                case COMPONENT_ENABLED_STATE_DEFAULT:
19718                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19719                        return;
19720                    }
19721                    break;
19722                default:
19723                    Slog.e(TAG, "Invalid new component state: " + newState);
19724                    return;
19725                }
19726            }
19727            scheduleWritePackageRestrictionsLocked(userId);
19728            components = mPendingBroadcasts.get(userId, packageName);
19729            final boolean newPackage = components == null;
19730            if (newPackage) {
19731                components = new ArrayList<String>();
19732            }
19733            if (!components.contains(componentName)) {
19734                components.add(componentName);
19735            }
19736            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19737                sendNow = true;
19738                // Purge entry from pending broadcast list if another one exists already
19739                // since we are sending one right away.
19740                mPendingBroadcasts.remove(userId, packageName);
19741            } else {
19742                if (newPackage) {
19743                    mPendingBroadcasts.put(userId, packageName, components);
19744                }
19745                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19746                    // Schedule a message
19747                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19748                }
19749            }
19750        }
19751
19752        long callingId = Binder.clearCallingIdentity();
19753        try {
19754            if (sendNow) {
19755                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19756                sendPackageChangedBroadcast(packageName,
19757                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19758            }
19759        } finally {
19760            Binder.restoreCallingIdentity(callingId);
19761        }
19762    }
19763
19764    @Override
19765    public void flushPackageRestrictionsAsUser(int userId) {
19766        if (!sUserManager.exists(userId)) {
19767            return;
19768        }
19769        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19770                false /* checkShell */, "flushPackageRestrictions");
19771        synchronized (mPackages) {
19772            mSettings.writePackageRestrictionsLPr(userId);
19773            mDirtyUsers.remove(userId);
19774            if (mDirtyUsers.isEmpty()) {
19775                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19776            }
19777        }
19778    }
19779
19780    private void sendPackageChangedBroadcast(String packageName,
19781            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19782        if (DEBUG_INSTALL)
19783            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19784                    + componentNames);
19785        Bundle extras = new Bundle(4);
19786        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19787        String nameList[] = new String[componentNames.size()];
19788        componentNames.toArray(nameList);
19789        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19790        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19791        extras.putInt(Intent.EXTRA_UID, packageUid);
19792        // If this is not reporting a change of the overall package, then only send it
19793        // to registered receivers.  We don't want to launch a swath of apps for every
19794        // little component state change.
19795        final int flags = !componentNames.contains(packageName)
19796                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19797        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19798                new int[] {UserHandle.getUserId(packageUid)});
19799    }
19800
19801    @Override
19802    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19803        if (!sUserManager.exists(userId)) return;
19804        final int uid = Binder.getCallingUid();
19805        final int permission = mContext.checkCallingOrSelfPermission(
19806                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19807        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19808        enforceCrossUserPermission(uid, userId,
19809                true /* requireFullPermission */, true /* checkShell */, "stop package");
19810        // writer
19811        synchronized (mPackages) {
19812            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19813                    allowedByPermission, uid, userId)) {
19814                scheduleWritePackageRestrictionsLocked(userId);
19815            }
19816        }
19817    }
19818
19819    @Override
19820    public String getInstallerPackageName(String packageName) {
19821        // reader
19822        synchronized (mPackages) {
19823            return mSettings.getInstallerPackageNameLPr(packageName);
19824        }
19825    }
19826
19827    public boolean isOrphaned(String packageName) {
19828        // reader
19829        synchronized (mPackages) {
19830            return mSettings.isOrphaned(packageName);
19831        }
19832    }
19833
19834    @Override
19835    public int getApplicationEnabledSetting(String packageName, int userId) {
19836        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19837        int uid = Binder.getCallingUid();
19838        enforceCrossUserPermission(uid, userId,
19839                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19840        // reader
19841        synchronized (mPackages) {
19842            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19843        }
19844    }
19845
19846    @Override
19847    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19848        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19849        int uid = Binder.getCallingUid();
19850        enforceCrossUserPermission(uid, userId,
19851                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19852        // reader
19853        synchronized (mPackages) {
19854            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19855        }
19856    }
19857
19858    @Override
19859    public void enterSafeMode() {
19860        enforceSystemOrRoot("Only the system can request entering safe mode");
19861
19862        if (!mSystemReady) {
19863            mSafeMode = true;
19864        }
19865    }
19866
19867    @Override
19868    public void systemReady() {
19869        mSystemReady = true;
19870
19871        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19872        // disabled after already being started.
19873        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19874                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19875
19876        // Read the compatibilty setting when the system is ready.
19877        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19878                mContext.getContentResolver(),
19879                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19880        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19881        if (DEBUG_SETTINGS) {
19882            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19883        }
19884
19885        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19886
19887        synchronized (mPackages) {
19888            // Verify that all of the preferred activity components actually
19889            // exist.  It is possible for applications to be updated and at
19890            // that point remove a previously declared activity component that
19891            // had been set as a preferred activity.  We try to clean this up
19892            // the next time we encounter that preferred activity, but it is
19893            // possible for the user flow to never be able to return to that
19894            // situation so here we do a sanity check to make sure we haven't
19895            // left any junk around.
19896            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19897            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19898                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19899                removed.clear();
19900                for (PreferredActivity pa : pir.filterSet()) {
19901                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19902                        removed.add(pa);
19903                    }
19904                }
19905                if (removed.size() > 0) {
19906                    for (int r=0; r<removed.size(); r++) {
19907                        PreferredActivity pa = removed.get(r);
19908                        Slog.w(TAG, "Removing dangling preferred activity: "
19909                                + pa.mPref.mComponent);
19910                        pir.removeFilter(pa);
19911                    }
19912                    mSettings.writePackageRestrictionsLPr(
19913                            mSettings.mPreferredActivities.keyAt(i));
19914                }
19915            }
19916
19917            for (int userId : UserManagerService.getInstance().getUserIds()) {
19918                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19919                    grantPermissionsUserIds = ArrayUtils.appendInt(
19920                            grantPermissionsUserIds, userId);
19921                }
19922            }
19923        }
19924        sUserManager.systemReady();
19925
19926        // If we upgraded grant all default permissions before kicking off.
19927        for (int userId : grantPermissionsUserIds) {
19928            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19929        }
19930
19931        // If we did not grant default permissions, we preload from this the
19932        // default permission exceptions lazily to ensure we don't hit the
19933        // disk on a new user creation.
19934        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19935            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19936        }
19937
19938        // Kick off any messages waiting for system ready
19939        if (mPostSystemReadyMessages != null) {
19940            for (Message msg : mPostSystemReadyMessages) {
19941                msg.sendToTarget();
19942            }
19943            mPostSystemReadyMessages = null;
19944        }
19945
19946        // Watch for external volumes that come and go over time
19947        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19948        storage.registerListener(mStorageListener);
19949
19950        mInstallerService.systemReady();
19951        mPackageDexOptimizer.systemReady();
19952
19953        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19954                StorageManagerInternal.class);
19955        StorageManagerInternal.addExternalStoragePolicy(
19956                new StorageManagerInternal.ExternalStorageMountPolicy() {
19957            @Override
19958            public int getMountMode(int uid, String packageName) {
19959                if (Process.isIsolated(uid)) {
19960                    return Zygote.MOUNT_EXTERNAL_NONE;
19961                }
19962                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19963                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19964                }
19965                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19966                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19967                }
19968                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19969                    return Zygote.MOUNT_EXTERNAL_READ;
19970                }
19971                return Zygote.MOUNT_EXTERNAL_WRITE;
19972            }
19973
19974            @Override
19975            public boolean hasExternalStorage(int uid, String packageName) {
19976                return true;
19977            }
19978        });
19979
19980        // Now that we're mostly running, clean up stale users and apps
19981        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19982        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19983
19984        if (mPrivappPermissionsViolations != null) {
19985            Slog.wtf(TAG,"Signature|privileged permissions not in "
19986                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
19987            mPrivappPermissionsViolations = null;
19988        }
19989    }
19990
19991    @Override
19992    public boolean isSafeMode() {
19993        return mSafeMode;
19994    }
19995
19996    @Override
19997    public boolean hasSystemUidErrors() {
19998        return mHasSystemUidErrors;
19999    }
20000
20001    static String arrayToString(int[] array) {
20002        StringBuffer buf = new StringBuffer(128);
20003        buf.append('[');
20004        if (array != null) {
20005            for (int i=0; i<array.length; i++) {
20006                if (i > 0) buf.append(", ");
20007                buf.append(array[i]);
20008            }
20009        }
20010        buf.append(']');
20011        return buf.toString();
20012    }
20013
20014    static class DumpState {
20015        public static final int DUMP_LIBS = 1 << 0;
20016        public static final int DUMP_FEATURES = 1 << 1;
20017        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20018        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20019        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20020        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20021        public static final int DUMP_PERMISSIONS = 1 << 6;
20022        public static final int DUMP_PACKAGES = 1 << 7;
20023        public static final int DUMP_SHARED_USERS = 1 << 8;
20024        public static final int DUMP_MESSAGES = 1 << 9;
20025        public static final int DUMP_PROVIDERS = 1 << 10;
20026        public static final int DUMP_VERIFIERS = 1 << 11;
20027        public static final int DUMP_PREFERRED = 1 << 12;
20028        public static final int DUMP_PREFERRED_XML = 1 << 13;
20029        public static final int DUMP_KEYSETS = 1 << 14;
20030        public static final int DUMP_VERSION = 1 << 15;
20031        public static final int DUMP_INSTALLS = 1 << 16;
20032        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20033        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20034        public static final int DUMP_FROZEN = 1 << 19;
20035        public static final int DUMP_DEXOPT = 1 << 20;
20036        public static final int DUMP_COMPILER_STATS = 1 << 21;
20037
20038        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20039
20040        private int mTypes;
20041
20042        private int mOptions;
20043
20044        private boolean mTitlePrinted;
20045
20046        private SharedUserSetting mSharedUser;
20047
20048        public boolean isDumping(int type) {
20049            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20050                return true;
20051            }
20052
20053            return (mTypes & type) != 0;
20054        }
20055
20056        public void setDump(int type) {
20057            mTypes |= type;
20058        }
20059
20060        public boolean isOptionEnabled(int option) {
20061            return (mOptions & option) != 0;
20062        }
20063
20064        public void setOptionEnabled(int option) {
20065            mOptions |= option;
20066        }
20067
20068        public boolean onTitlePrinted() {
20069            final boolean printed = mTitlePrinted;
20070            mTitlePrinted = true;
20071            return printed;
20072        }
20073
20074        public boolean getTitlePrinted() {
20075            return mTitlePrinted;
20076        }
20077
20078        public void setTitlePrinted(boolean enabled) {
20079            mTitlePrinted = enabled;
20080        }
20081
20082        public SharedUserSetting getSharedUser() {
20083            return mSharedUser;
20084        }
20085
20086        public void setSharedUser(SharedUserSetting user) {
20087            mSharedUser = user;
20088        }
20089    }
20090
20091    @Override
20092    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20093            FileDescriptor err, String[] args, ShellCallback callback,
20094            ResultReceiver resultReceiver) {
20095        (new PackageManagerShellCommand(this)).exec(
20096                this, in, out, err, args, callback, resultReceiver);
20097    }
20098
20099    @Override
20100    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20101        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20102                != PackageManager.PERMISSION_GRANTED) {
20103            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20104                    + Binder.getCallingPid()
20105                    + ", uid=" + Binder.getCallingUid()
20106                    + " without permission "
20107                    + android.Manifest.permission.DUMP);
20108            return;
20109        }
20110
20111        DumpState dumpState = new DumpState();
20112        boolean fullPreferred = false;
20113        boolean checkin = false;
20114
20115        String packageName = null;
20116        ArraySet<String> permissionNames = null;
20117
20118        int opti = 0;
20119        while (opti < args.length) {
20120            String opt = args[opti];
20121            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20122                break;
20123            }
20124            opti++;
20125
20126            if ("-a".equals(opt)) {
20127                // Right now we only know how to print all.
20128            } else if ("-h".equals(opt)) {
20129                pw.println("Package manager dump options:");
20130                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20131                pw.println("    --checkin: dump for a checkin");
20132                pw.println("    -f: print details of intent filters");
20133                pw.println("    -h: print this help");
20134                pw.println("  cmd may be one of:");
20135                pw.println("    l[ibraries]: list known shared libraries");
20136                pw.println("    f[eatures]: list device features");
20137                pw.println("    k[eysets]: print known keysets");
20138                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20139                pw.println("    perm[issions]: dump permissions");
20140                pw.println("    permission [name ...]: dump declaration and use of given permission");
20141                pw.println("    pref[erred]: print preferred package settings");
20142                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20143                pw.println("    prov[iders]: dump content providers");
20144                pw.println("    p[ackages]: dump installed packages");
20145                pw.println("    s[hared-users]: dump shared user IDs");
20146                pw.println("    m[essages]: print collected runtime messages");
20147                pw.println("    v[erifiers]: print package verifier info");
20148                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20149                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20150                pw.println("    version: print database version info");
20151                pw.println("    write: write current settings now");
20152                pw.println("    installs: details about install sessions");
20153                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20154                pw.println("    dexopt: dump dexopt state");
20155                pw.println("    compiler-stats: dump compiler statistics");
20156                pw.println("    <package.name>: info about given package");
20157                return;
20158            } else if ("--checkin".equals(opt)) {
20159                checkin = true;
20160            } else if ("-f".equals(opt)) {
20161                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20162            } else {
20163                pw.println("Unknown argument: " + opt + "; use -h for help");
20164            }
20165        }
20166
20167        // Is the caller requesting to dump a particular piece of data?
20168        if (opti < args.length) {
20169            String cmd = args[opti];
20170            opti++;
20171            // Is this a package name?
20172            if ("android".equals(cmd) || cmd.contains(".")) {
20173                packageName = cmd;
20174                // When dumping a single package, we always dump all of its
20175                // filter information since the amount of data will be reasonable.
20176                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20177            } else if ("check-permission".equals(cmd)) {
20178                if (opti >= args.length) {
20179                    pw.println("Error: check-permission missing permission argument");
20180                    return;
20181                }
20182                String perm = args[opti];
20183                opti++;
20184                if (opti >= args.length) {
20185                    pw.println("Error: check-permission missing package argument");
20186                    return;
20187                }
20188
20189                String pkg = args[opti];
20190                opti++;
20191                int user = UserHandle.getUserId(Binder.getCallingUid());
20192                if (opti < args.length) {
20193                    try {
20194                        user = Integer.parseInt(args[opti]);
20195                    } catch (NumberFormatException e) {
20196                        pw.println("Error: check-permission user argument is not a number: "
20197                                + args[opti]);
20198                        return;
20199                    }
20200                }
20201
20202                // Normalize package name to handle renamed packages and static libs
20203                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20204
20205                pw.println(checkPermission(perm, pkg, user));
20206                return;
20207            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20208                dumpState.setDump(DumpState.DUMP_LIBS);
20209            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20210                dumpState.setDump(DumpState.DUMP_FEATURES);
20211            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20212                if (opti >= args.length) {
20213                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20214                            | DumpState.DUMP_SERVICE_RESOLVERS
20215                            | DumpState.DUMP_RECEIVER_RESOLVERS
20216                            | DumpState.DUMP_CONTENT_RESOLVERS);
20217                } else {
20218                    while (opti < args.length) {
20219                        String name = args[opti];
20220                        if ("a".equals(name) || "activity".equals(name)) {
20221                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20222                        } else if ("s".equals(name) || "service".equals(name)) {
20223                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20224                        } else if ("r".equals(name) || "receiver".equals(name)) {
20225                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20226                        } else if ("c".equals(name) || "content".equals(name)) {
20227                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20228                        } else {
20229                            pw.println("Error: unknown resolver table type: " + name);
20230                            return;
20231                        }
20232                        opti++;
20233                    }
20234                }
20235            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20236                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20237            } else if ("permission".equals(cmd)) {
20238                if (opti >= args.length) {
20239                    pw.println("Error: permission requires permission name");
20240                    return;
20241                }
20242                permissionNames = new ArraySet<>();
20243                while (opti < args.length) {
20244                    permissionNames.add(args[opti]);
20245                    opti++;
20246                }
20247                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20248                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20249            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20250                dumpState.setDump(DumpState.DUMP_PREFERRED);
20251            } else if ("preferred-xml".equals(cmd)) {
20252                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20253                if (opti < args.length && "--full".equals(args[opti])) {
20254                    fullPreferred = true;
20255                    opti++;
20256                }
20257            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20258                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20259            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20260                dumpState.setDump(DumpState.DUMP_PACKAGES);
20261            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20262                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20263            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20264                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20265            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20266                dumpState.setDump(DumpState.DUMP_MESSAGES);
20267            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20268                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20269            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20270                    || "intent-filter-verifiers".equals(cmd)) {
20271                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20272            } else if ("version".equals(cmd)) {
20273                dumpState.setDump(DumpState.DUMP_VERSION);
20274            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20275                dumpState.setDump(DumpState.DUMP_KEYSETS);
20276            } else if ("installs".equals(cmd)) {
20277                dumpState.setDump(DumpState.DUMP_INSTALLS);
20278            } else if ("frozen".equals(cmd)) {
20279                dumpState.setDump(DumpState.DUMP_FROZEN);
20280            } else if ("dexopt".equals(cmd)) {
20281                dumpState.setDump(DumpState.DUMP_DEXOPT);
20282            } else if ("compiler-stats".equals(cmd)) {
20283                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20284            } else if ("write".equals(cmd)) {
20285                synchronized (mPackages) {
20286                    mSettings.writeLPr();
20287                    pw.println("Settings written.");
20288                    return;
20289                }
20290            }
20291        }
20292
20293        if (checkin) {
20294            pw.println("vers,1");
20295        }
20296
20297        // reader
20298        synchronized (mPackages) {
20299            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20300                if (!checkin) {
20301                    if (dumpState.onTitlePrinted())
20302                        pw.println();
20303                    pw.println("Database versions:");
20304                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20305                }
20306            }
20307
20308            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20309                if (!checkin) {
20310                    if (dumpState.onTitlePrinted())
20311                        pw.println();
20312                    pw.println("Verifiers:");
20313                    pw.print("  Required: ");
20314                    pw.print(mRequiredVerifierPackage);
20315                    pw.print(" (uid=");
20316                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20317                            UserHandle.USER_SYSTEM));
20318                    pw.println(")");
20319                } else if (mRequiredVerifierPackage != null) {
20320                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20321                    pw.print(",");
20322                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20323                            UserHandle.USER_SYSTEM));
20324                }
20325            }
20326
20327            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20328                    packageName == null) {
20329                if (mIntentFilterVerifierComponent != null) {
20330                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20331                    if (!checkin) {
20332                        if (dumpState.onTitlePrinted())
20333                            pw.println();
20334                        pw.println("Intent Filter Verifier:");
20335                        pw.print("  Using: ");
20336                        pw.print(verifierPackageName);
20337                        pw.print(" (uid=");
20338                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20339                                UserHandle.USER_SYSTEM));
20340                        pw.println(")");
20341                    } else if (verifierPackageName != null) {
20342                        pw.print("ifv,"); pw.print(verifierPackageName);
20343                        pw.print(",");
20344                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20345                                UserHandle.USER_SYSTEM));
20346                    }
20347                } else {
20348                    pw.println();
20349                    pw.println("No Intent Filter Verifier available!");
20350                }
20351            }
20352
20353            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20354                boolean printedHeader = false;
20355                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20356                while (it.hasNext()) {
20357                    String libName = it.next();
20358                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20359                    if (versionedLib == null) {
20360                        continue;
20361                    }
20362                    final int versionCount = versionedLib.size();
20363                    for (int i = 0; i < versionCount; i++) {
20364                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20365                        if (!checkin) {
20366                            if (!printedHeader) {
20367                                if (dumpState.onTitlePrinted())
20368                                    pw.println();
20369                                pw.println("Libraries:");
20370                                printedHeader = true;
20371                            }
20372                            pw.print("  ");
20373                        } else {
20374                            pw.print("lib,");
20375                        }
20376                        pw.print(libEntry.info.getName());
20377                        if (libEntry.info.isStatic()) {
20378                            pw.print(" version=" + libEntry.info.getVersion());
20379                        }
20380                        if (!checkin) {
20381                            pw.print(" -> ");
20382                        }
20383                        if (libEntry.path != null) {
20384                            pw.print(" (jar) ");
20385                            pw.print(libEntry.path);
20386                        } else {
20387                            pw.print(" (apk) ");
20388                            pw.print(libEntry.apk);
20389                        }
20390                        pw.println();
20391                    }
20392                }
20393            }
20394
20395            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20396                if (dumpState.onTitlePrinted())
20397                    pw.println();
20398                if (!checkin) {
20399                    pw.println("Features:");
20400                }
20401
20402                synchronized (mAvailableFeatures) {
20403                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20404                        if (checkin) {
20405                            pw.print("feat,");
20406                            pw.print(feat.name);
20407                            pw.print(",");
20408                            pw.println(feat.version);
20409                        } else {
20410                            pw.print("  ");
20411                            pw.print(feat.name);
20412                            if (feat.version > 0) {
20413                                pw.print(" version=");
20414                                pw.print(feat.version);
20415                            }
20416                            pw.println();
20417                        }
20418                    }
20419                }
20420            }
20421
20422            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20423                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20424                        : "Activity Resolver Table:", "  ", packageName,
20425                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20426                    dumpState.setTitlePrinted(true);
20427                }
20428            }
20429            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20430                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20431                        : "Receiver Resolver Table:", "  ", packageName,
20432                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20433                    dumpState.setTitlePrinted(true);
20434                }
20435            }
20436            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20437                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20438                        : "Service Resolver Table:", "  ", packageName,
20439                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20440                    dumpState.setTitlePrinted(true);
20441                }
20442            }
20443            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20444                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20445                        : "Provider Resolver Table:", "  ", packageName,
20446                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20447                    dumpState.setTitlePrinted(true);
20448                }
20449            }
20450
20451            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20452                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20453                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20454                    int user = mSettings.mPreferredActivities.keyAt(i);
20455                    if (pir.dump(pw,
20456                            dumpState.getTitlePrinted()
20457                                ? "\nPreferred Activities User " + user + ":"
20458                                : "Preferred Activities User " + user + ":", "  ",
20459                            packageName, true, false)) {
20460                        dumpState.setTitlePrinted(true);
20461                    }
20462                }
20463            }
20464
20465            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20466                pw.flush();
20467                FileOutputStream fout = new FileOutputStream(fd);
20468                BufferedOutputStream str = new BufferedOutputStream(fout);
20469                XmlSerializer serializer = new FastXmlSerializer();
20470                try {
20471                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20472                    serializer.startDocument(null, true);
20473                    serializer.setFeature(
20474                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20475                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20476                    serializer.endDocument();
20477                    serializer.flush();
20478                } catch (IllegalArgumentException e) {
20479                    pw.println("Failed writing: " + e);
20480                } catch (IllegalStateException e) {
20481                    pw.println("Failed writing: " + e);
20482                } catch (IOException e) {
20483                    pw.println("Failed writing: " + e);
20484                }
20485            }
20486
20487            if (!checkin
20488                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20489                    && packageName == null) {
20490                pw.println();
20491                int count = mSettings.mPackages.size();
20492                if (count == 0) {
20493                    pw.println("No applications!");
20494                    pw.println();
20495                } else {
20496                    final String prefix = "  ";
20497                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20498                    if (allPackageSettings.size() == 0) {
20499                        pw.println("No domain preferred apps!");
20500                        pw.println();
20501                    } else {
20502                        pw.println("App verification status:");
20503                        pw.println();
20504                        count = 0;
20505                        for (PackageSetting ps : allPackageSettings) {
20506                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20507                            if (ivi == null || ivi.getPackageName() == null) continue;
20508                            pw.println(prefix + "Package: " + ivi.getPackageName());
20509                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20510                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20511                            pw.println();
20512                            count++;
20513                        }
20514                        if (count == 0) {
20515                            pw.println(prefix + "No app verification established.");
20516                            pw.println();
20517                        }
20518                        for (int userId : sUserManager.getUserIds()) {
20519                            pw.println("App linkages for user " + userId + ":");
20520                            pw.println();
20521                            count = 0;
20522                            for (PackageSetting ps : allPackageSettings) {
20523                                final long status = ps.getDomainVerificationStatusForUser(userId);
20524                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20525                                        && !DEBUG_DOMAIN_VERIFICATION) {
20526                                    continue;
20527                                }
20528                                pw.println(prefix + "Package: " + ps.name);
20529                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20530                                String statusStr = IntentFilterVerificationInfo.
20531                                        getStatusStringFromValue(status);
20532                                pw.println(prefix + "Status:  " + statusStr);
20533                                pw.println();
20534                                count++;
20535                            }
20536                            if (count == 0) {
20537                                pw.println(prefix + "No configured app linkages.");
20538                                pw.println();
20539                            }
20540                        }
20541                    }
20542                }
20543            }
20544
20545            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20546                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20547                if (packageName == null && permissionNames == null) {
20548                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20549                        if (iperm == 0) {
20550                            if (dumpState.onTitlePrinted())
20551                                pw.println();
20552                            pw.println("AppOp Permissions:");
20553                        }
20554                        pw.print("  AppOp Permission ");
20555                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20556                        pw.println(":");
20557                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20558                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20559                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20560                        }
20561                    }
20562                }
20563            }
20564
20565            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20566                boolean printedSomething = false;
20567                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20568                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20569                        continue;
20570                    }
20571                    if (!printedSomething) {
20572                        if (dumpState.onTitlePrinted())
20573                            pw.println();
20574                        pw.println("Registered ContentProviders:");
20575                        printedSomething = true;
20576                    }
20577                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20578                    pw.print("    "); pw.println(p.toString());
20579                }
20580                printedSomething = false;
20581                for (Map.Entry<String, PackageParser.Provider> entry :
20582                        mProvidersByAuthority.entrySet()) {
20583                    PackageParser.Provider p = entry.getValue();
20584                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20585                        continue;
20586                    }
20587                    if (!printedSomething) {
20588                        if (dumpState.onTitlePrinted())
20589                            pw.println();
20590                        pw.println("ContentProvider Authorities:");
20591                        printedSomething = true;
20592                    }
20593                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20594                    pw.print("    "); pw.println(p.toString());
20595                    if (p.info != null && p.info.applicationInfo != null) {
20596                        final String appInfo = p.info.applicationInfo.toString();
20597                        pw.print("      applicationInfo="); pw.println(appInfo);
20598                    }
20599                }
20600            }
20601
20602            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20603                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20604            }
20605
20606            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20607                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20608            }
20609
20610            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20611                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20612            }
20613
20614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20615                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20616            }
20617
20618            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20619                // XXX should handle packageName != null by dumping only install data that
20620                // the given package is involved with.
20621                if (dumpState.onTitlePrinted()) pw.println();
20622                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20623            }
20624
20625            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20626                // XXX should handle packageName != null by dumping only install data that
20627                // the given package is involved with.
20628                if (dumpState.onTitlePrinted()) pw.println();
20629
20630                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20631                ipw.println();
20632                ipw.println("Frozen packages:");
20633                ipw.increaseIndent();
20634                if (mFrozenPackages.size() == 0) {
20635                    ipw.println("(none)");
20636                } else {
20637                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20638                        ipw.println(mFrozenPackages.valueAt(i));
20639                    }
20640                }
20641                ipw.decreaseIndent();
20642            }
20643
20644            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20645                if (dumpState.onTitlePrinted()) pw.println();
20646                dumpDexoptStateLPr(pw, packageName);
20647            }
20648
20649            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20650                if (dumpState.onTitlePrinted()) pw.println();
20651                dumpCompilerStatsLPr(pw, packageName);
20652            }
20653
20654            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20655                if (dumpState.onTitlePrinted()) pw.println();
20656                mSettings.dumpReadMessagesLPr(pw, dumpState);
20657
20658                pw.println();
20659                pw.println("Package warning messages:");
20660                BufferedReader in = null;
20661                String line = null;
20662                try {
20663                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20664                    while ((line = in.readLine()) != null) {
20665                        if (line.contains("ignored: updated version")) continue;
20666                        pw.println(line);
20667                    }
20668                } catch (IOException ignored) {
20669                } finally {
20670                    IoUtils.closeQuietly(in);
20671                }
20672            }
20673
20674            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20675                BufferedReader in = null;
20676                String line = null;
20677                try {
20678                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20679                    while ((line = in.readLine()) != null) {
20680                        if (line.contains("ignored: updated version")) continue;
20681                        pw.print("msg,");
20682                        pw.println(line);
20683                    }
20684                } catch (IOException ignored) {
20685                } finally {
20686                    IoUtils.closeQuietly(in);
20687                }
20688            }
20689        }
20690    }
20691
20692    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20693        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20694        ipw.println();
20695        ipw.println("Dexopt state:");
20696        ipw.increaseIndent();
20697        Collection<PackageParser.Package> packages = null;
20698        if (packageName != null) {
20699            PackageParser.Package targetPackage = mPackages.get(packageName);
20700            if (targetPackage != null) {
20701                packages = Collections.singletonList(targetPackage);
20702            } else {
20703                ipw.println("Unable to find package: " + packageName);
20704                return;
20705            }
20706        } else {
20707            packages = mPackages.values();
20708        }
20709
20710        for (PackageParser.Package pkg : packages) {
20711            ipw.println("[" + pkg.packageName + "]");
20712            ipw.increaseIndent();
20713            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20714            ipw.decreaseIndent();
20715        }
20716    }
20717
20718    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20719        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20720        ipw.println();
20721        ipw.println("Compiler stats:");
20722        ipw.increaseIndent();
20723        Collection<PackageParser.Package> packages = null;
20724        if (packageName != null) {
20725            PackageParser.Package targetPackage = mPackages.get(packageName);
20726            if (targetPackage != null) {
20727                packages = Collections.singletonList(targetPackage);
20728            } else {
20729                ipw.println("Unable to find package: " + packageName);
20730                return;
20731            }
20732        } else {
20733            packages = mPackages.values();
20734        }
20735
20736        for (PackageParser.Package pkg : packages) {
20737            ipw.println("[" + pkg.packageName + "]");
20738            ipw.increaseIndent();
20739
20740            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20741            if (stats == null) {
20742                ipw.println("(No recorded stats)");
20743            } else {
20744                stats.dump(ipw);
20745            }
20746            ipw.decreaseIndent();
20747        }
20748    }
20749
20750    private String dumpDomainString(String packageName) {
20751        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20752                .getList();
20753        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20754
20755        ArraySet<String> result = new ArraySet<>();
20756        if (iviList.size() > 0) {
20757            for (IntentFilterVerificationInfo ivi : iviList) {
20758                for (String host : ivi.getDomains()) {
20759                    result.add(host);
20760                }
20761            }
20762        }
20763        if (filters != null && filters.size() > 0) {
20764            for (IntentFilter filter : filters) {
20765                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20766                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20767                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20768                    result.addAll(filter.getHostsList());
20769                }
20770            }
20771        }
20772
20773        StringBuilder sb = new StringBuilder(result.size() * 16);
20774        for (String domain : result) {
20775            if (sb.length() > 0) sb.append(" ");
20776            sb.append(domain);
20777        }
20778        return sb.toString();
20779    }
20780
20781    // ------- apps on sdcard specific code -------
20782    static final boolean DEBUG_SD_INSTALL = false;
20783
20784    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20785
20786    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20787
20788    private boolean mMediaMounted = false;
20789
20790    static String getEncryptKey() {
20791        try {
20792            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20793                    SD_ENCRYPTION_KEYSTORE_NAME);
20794            if (sdEncKey == null) {
20795                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20796                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20797                if (sdEncKey == null) {
20798                    Slog.e(TAG, "Failed to create encryption keys");
20799                    return null;
20800                }
20801            }
20802            return sdEncKey;
20803        } catch (NoSuchAlgorithmException nsae) {
20804            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20805            return null;
20806        } catch (IOException ioe) {
20807            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20808            return null;
20809        }
20810    }
20811
20812    /*
20813     * Update media status on PackageManager.
20814     */
20815    @Override
20816    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20817        int callingUid = Binder.getCallingUid();
20818        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20819            throw new SecurityException("Media status can only be updated by the system");
20820        }
20821        // reader; this apparently protects mMediaMounted, but should probably
20822        // be a different lock in that case.
20823        synchronized (mPackages) {
20824            Log.i(TAG, "Updating external media status from "
20825                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20826                    + (mediaStatus ? "mounted" : "unmounted"));
20827            if (DEBUG_SD_INSTALL)
20828                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20829                        + ", mMediaMounted=" + mMediaMounted);
20830            if (mediaStatus == mMediaMounted) {
20831                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20832                        : 0, -1);
20833                mHandler.sendMessage(msg);
20834                return;
20835            }
20836            mMediaMounted = mediaStatus;
20837        }
20838        // Queue up an async operation since the package installation may take a
20839        // little while.
20840        mHandler.post(new Runnable() {
20841            public void run() {
20842                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20843            }
20844        });
20845    }
20846
20847    /**
20848     * Called by StorageManagerService when the initial ASECs to scan are available.
20849     * Should block until all the ASEC containers are finished being scanned.
20850     */
20851    public void scanAvailableAsecs() {
20852        updateExternalMediaStatusInner(true, false, false);
20853    }
20854
20855    /*
20856     * Collect information of applications on external media, map them against
20857     * existing containers and update information based on current mount status.
20858     * Please note that we always have to report status if reportStatus has been
20859     * set to true especially when unloading packages.
20860     */
20861    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20862            boolean externalStorage) {
20863        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20864        int[] uidArr = EmptyArray.INT;
20865
20866        final String[] list = PackageHelper.getSecureContainerList();
20867        if (ArrayUtils.isEmpty(list)) {
20868            Log.i(TAG, "No secure containers found");
20869        } else {
20870            // Process list of secure containers and categorize them
20871            // as active or stale based on their package internal state.
20872
20873            // reader
20874            synchronized (mPackages) {
20875                for (String cid : list) {
20876                    // Leave stages untouched for now; installer service owns them
20877                    if (PackageInstallerService.isStageName(cid)) continue;
20878
20879                    if (DEBUG_SD_INSTALL)
20880                        Log.i(TAG, "Processing container " + cid);
20881                    String pkgName = getAsecPackageName(cid);
20882                    if (pkgName == null) {
20883                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20884                        continue;
20885                    }
20886                    if (DEBUG_SD_INSTALL)
20887                        Log.i(TAG, "Looking for pkg : " + pkgName);
20888
20889                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20890                    if (ps == null) {
20891                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20892                        continue;
20893                    }
20894
20895                    /*
20896                     * Skip packages that are not external if we're unmounting
20897                     * external storage.
20898                     */
20899                    if (externalStorage && !isMounted && !isExternal(ps)) {
20900                        continue;
20901                    }
20902
20903                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20904                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20905                    // The package status is changed only if the code path
20906                    // matches between settings and the container id.
20907                    if (ps.codePathString != null
20908                            && ps.codePathString.startsWith(args.getCodePath())) {
20909                        if (DEBUG_SD_INSTALL) {
20910                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20911                                    + " at code path: " + ps.codePathString);
20912                        }
20913
20914                        // We do have a valid package installed on sdcard
20915                        processCids.put(args, ps.codePathString);
20916                        final int uid = ps.appId;
20917                        if (uid != -1) {
20918                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20919                        }
20920                    } else {
20921                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20922                                + ps.codePathString);
20923                    }
20924                }
20925            }
20926
20927            Arrays.sort(uidArr);
20928        }
20929
20930        // Process packages with valid entries.
20931        if (isMounted) {
20932            if (DEBUG_SD_INSTALL)
20933                Log.i(TAG, "Loading packages");
20934            loadMediaPackages(processCids, uidArr, externalStorage);
20935            startCleaningPackages();
20936            mInstallerService.onSecureContainersAvailable();
20937        } else {
20938            if (DEBUG_SD_INSTALL)
20939                Log.i(TAG, "Unloading packages");
20940            unloadMediaPackages(processCids, uidArr, reportStatus);
20941        }
20942    }
20943
20944    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20945            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20946        final int size = infos.size();
20947        final String[] packageNames = new String[size];
20948        final int[] packageUids = new int[size];
20949        for (int i = 0; i < size; i++) {
20950            final ApplicationInfo info = infos.get(i);
20951            packageNames[i] = info.packageName;
20952            packageUids[i] = info.uid;
20953        }
20954        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20955                finishedReceiver);
20956    }
20957
20958    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20959            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20960        sendResourcesChangedBroadcast(mediaStatus, replacing,
20961                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20962    }
20963
20964    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20965            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20966        int size = pkgList.length;
20967        if (size > 0) {
20968            // Send broadcasts here
20969            Bundle extras = new Bundle();
20970            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20971            if (uidArr != null) {
20972                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20973            }
20974            if (replacing) {
20975                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20976            }
20977            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20978                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20979            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20980        }
20981    }
20982
20983   /*
20984     * Look at potentially valid container ids from processCids If package
20985     * information doesn't match the one on record or package scanning fails,
20986     * the cid is added to list of removeCids. We currently don't delete stale
20987     * containers.
20988     */
20989    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20990            boolean externalStorage) {
20991        ArrayList<String> pkgList = new ArrayList<String>();
20992        Set<AsecInstallArgs> keys = processCids.keySet();
20993
20994        for (AsecInstallArgs args : keys) {
20995            String codePath = processCids.get(args);
20996            if (DEBUG_SD_INSTALL)
20997                Log.i(TAG, "Loading container : " + args.cid);
20998            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20999            try {
21000                // Make sure there are no container errors first.
21001                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21002                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21003                            + " when installing from sdcard");
21004                    continue;
21005                }
21006                // Check code path here.
21007                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21008                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21009                            + " does not match one in settings " + codePath);
21010                    continue;
21011                }
21012                // Parse package
21013                int parseFlags = mDefParseFlags;
21014                if (args.isExternalAsec()) {
21015                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21016                }
21017                if (args.isFwdLocked()) {
21018                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21019                }
21020
21021                synchronized (mInstallLock) {
21022                    PackageParser.Package pkg = null;
21023                    try {
21024                        // Sadly we don't know the package name yet to freeze it
21025                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21026                                SCAN_IGNORE_FROZEN, 0, null);
21027                    } catch (PackageManagerException e) {
21028                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21029                    }
21030                    // Scan the package
21031                    if (pkg != null) {
21032                        /*
21033                         * TODO why is the lock being held? doPostInstall is
21034                         * called in other places without the lock. This needs
21035                         * to be straightened out.
21036                         */
21037                        // writer
21038                        synchronized (mPackages) {
21039                            retCode = PackageManager.INSTALL_SUCCEEDED;
21040                            pkgList.add(pkg.packageName);
21041                            // Post process args
21042                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21043                                    pkg.applicationInfo.uid);
21044                        }
21045                    } else {
21046                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21047                    }
21048                }
21049
21050            } finally {
21051                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21052                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21053                }
21054            }
21055        }
21056        // writer
21057        synchronized (mPackages) {
21058            // If the platform SDK has changed since the last time we booted,
21059            // we need to re-grant app permission to catch any new ones that
21060            // appear. This is really a hack, and means that apps can in some
21061            // cases get permissions that the user didn't initially explicitly
21062            // allow... it would be nice to have some better way to handle
21063            // this situation.
21064            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21065                    : mSettings.getInternalVersion();
21066            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21067                    : StorageManager.UUID_PRIVATE_INTERNAL;
21068
21069            int updateFlags = UPDATE_PERMISSIONS_ALL;
21070            if (ver.sdkVersion != mSdkVersion) {
21071                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21072                        + mSdkVersion + "; regranting permissions for external");
21073                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21074            }
21075            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21076
21077            // Yay, everything is now upgraded
21078            ver.forceCurrent();
21079
21080            // can downgrade to reader
21081            // Persist settings
21082            mSettings.writeLPr();
21083        }
21084        // Send a broadcast to let everyone know we are done processing
21085        if (pkgList.size() > 0) {
21086            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21087        }
21088    }
21089
21090   /*
21091     * Utility method to unload a list of specified containers
21092     */
21093    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21094        // Just unmount all valid containers.
21095        for (AsecInstallArgs arg : cidArgs) {
21096            synchronized (mInstallLock) {
21097                arg.doPostDeleteLI(false);
21098           }
21099       }
21100   }
21101
21102    /*
21103     * Unload packages mounted on external media. This involves deleting package
21104     * data from internal structures, sending broadcasts about disabled packages,
21105     * gc'ing to free up references, unmounting all secure containers
21106     * corresponding to packages on external media, and posting a
21107     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21108     * that we always have to post this message if status has been requested no
21109     * matter what.
21110     */
21111    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21112            final boolean reportStatus) {
21113        if (DEBUG_SD_INSTALL)
21114            Log.i(TAG, "unloading media packages");
21115        ArrayList<String> pkgList = new ArrayList<String>();
21116        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21117        final Set<AsecInstallArgs> keys = processCids.keySet();
21118        for (AsecInstallArgs args : keys) {
21119            String pkgName = args.getPackageName();
21120            if (DEBUG_SD_INSTALL)
21121                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21122            // Delete package internally
21123            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21124            synchronized (mInstallLock) {
21125                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21126                final boolean res;
21127                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21128                        "unloadMediaPackages")) {
21129                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21130                            null);
21131                }
21132                if (res) {
21133                    pkgList.add(pkgName);
21134                } else {
21135                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21136                    failedList.add(args);
21137                }
21138            }
21139        }
21140
21141        // reader
21142        synchronized (mPackages) {
21143            // We didn't update the settings after removing each package;
21144            // write them now for all packages.
21145            mSettings.writeLPr();
21146        }
21147
21148        // We have to absolutely send UPDATED_MEDIA_STATUS only
21149        // after confirming that all the receivers processed the ordered
21150        // broadcast when packages get disabled, force a gc to clean things up.
21151        // and unload all the containers.
21152        if (pkgList.size() > 0) {
21153            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21154                    new IIntentReceiver.Stub() {
21155                public void performReceive(Intent intent, int resultCode, String data,
21156                        Bundle extras, boolean ordered, boolean sticky,
21157                        int sendingUser) throws RemoteException {
21158                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21159                            reportStatus ? 1 : 0, 1, keys);
21160                    mHandler.sendMessage(msg);
21161                }
21162            });
21163        } else {
21164            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21165                    keys);
21166            mHandler.sendMessage(msg);
21167        }
21168    }
21169
21170    private void loadPrivatePackages(final VolumeInfo vol) {
21171        mHandler.post(new Runnable() {
21172            @Override
21173            public void run() {
21174                loadPrivatePackagesInner(vol);
21175            }
21176        });
21177    }
21178
21179    private void loadPrivatePackagesInner(VolumeInfo vol) {
21180        final String volumeUuid = vol.fsUuid;
21181        if (TextUtils.isEmpty(volumeUuid)) {
21182            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21183            return;
21184        }
21185
21186        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21187        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21188        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21189
21190        final VersionInfo ver;
21191        final List<PackageSetting> packages;
21192        synchronized (mPackages) {
21193            ver = mSettings.findOrCreateVersion(volumeUuid);
21194            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21195        }
21196
21197        for (PackageSetting ps : packages) {
21198            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21199            synchronized (mInstallLock) {
21200                final PackageParser.Package pkg;
21201                try {
21202                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21203                    loaded.add(pkg.applicationInfo);
21204
21205                } catch (PackageManagerException e) {
21206                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21207                }
21208
21209                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21210                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21211                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21212                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21213                }
21214            }
21215        }
21216
21217        // Reconcile app data for all started/unlocked users
21218        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21219        final UserManager um = mContext.getSystemService(UserManager.class);
21220        UserManagerInternal umInternal = getUserManagerInternal();
21221        for (UserInfo user : um.getUsers()) {
21222            final int flags;
21223            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21224                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21225            } else if (umInternal.isUserRunning(user.id)) {
21226                flags = StorageManager.FLAG_STORAGE_DE;
21227            } else {
21228                continue;
21229            }
21230
21231            try {
21232                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21233                synchronized (mInstallLock) {
21234                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21235                }
21236            } catch (IllegalStateException e) {
21237                // Device was probably ejected, and we'll process that event momentarily
21238                Slog.w(TAG, "Failed to prepare storage: " + e);
21239            }
21240        }
21241
21242        synchronized (mPackages) {
21243            int updateFlags = UPDATE_PERMISSIONS_ALL;
21244            if (ver.sdkVersion != mSdkVersion) {
21245                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21246                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21247                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21248            }
21249            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21250
21251            // Yay, everything is now upgraded
21252            ver.forceCurrent();
21253
21254            mSettings.writeLPr();
21255        }
21256
21257        for (PackageFreezer freezer : freezers) {
21258            freezer.close();
21259        }
21260
21261        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21262        sendResourcesChangedBroadcast(true, false, loaded, null);
21263    }
21264
21265    private void unloadPrivatePackages(final VolumeInfo vol) {
21266        mHandler.post(new Runnable() {
21267            @Override
21268            public void run() {
21269                unloadPrivatePackagesInner(vol);
21270            }
21271        });
21272    }
21273
21274    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21275        final String volumeUuid = vol.fsUuid;
21276        if (TextUtils.isEmpty(volumeUuid)) {
21277            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21278            return;
21279        }
21280
21281        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21282        synchronized (mInstallLock) {
21283        synchronized (mPackages) {
21284            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21285            for (PackageSetting ps : packages) {
21286                if (ps.pkg == null) continue;
21287
21288                final ApplicationInfo info = ps.pkg.applicationInfo;
21289                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21290                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21291
21292                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21293                        "unloadPrivatePackagesInner")) {
21294                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21295                            false, null)) {
21296                        unloaded.add(info);
21297                    } else {
21298                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21299                    }
21300                }
21301
21302                // Try very hard to release any references to this package
21303                // so we don't risk the system server being killed due to
21304                // open FDs
21305                AttributeCache.instance().removePackage(ps.name);
21306            }
21307
21308            mSettings.writeLPr();
21309        }
21310        }
21311
21312        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21313        sendResourcesChangedBroadcast(false, false, unloaded, null);
21314
21315        // Try very hard to release any references to this path so we don't risk
21316        // the system server being killed due to open FDs
21317        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21318
21319        for (int i = 0; i < 3; i++) {
21320            System.gc();
21321            System.runFinalization();
21322        }
21323    }
21324
21325    private void assertPackageKnown(String volumeUuid, String packageName)
21326            throws PackageManagerException {
21327        synchronized (mPackages) {
21328            // Normalize package name to handle renamed packages
21329            packageName = normalizePackageNameLPr(packageName);
21330
21331            final PackageSetting ps = mSettings.mPackages.get(packageName);
21332            if (ps == null) {
21333                throw new PackageManagerException("Package " + packageName + " is unknown");
21334            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21335                throw new PackageManagerException(
21336                        "Package " + packageName + " found on unknown volume " + volumeUuid
21337                                + "; expected volume " + ps.volumeUuid);
21338            }
21339        }
21340    }
21341
21342    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21343            throws PackageManagerException {
21344        synchronized (mPackages) {
21345            // Normalize package name to handle renamed packages
21346            packageName = normalizePackageNameLPr(packageName);
21347
21348            final PackageSetting ps = mSettings.mPackages.get(packageName);
21349            if (ps == null) {
21350                throw new PackageManagerException("Package " + packageName + " is unknown");
21351            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21352                throw new PackageManagerException(
21353                        "Package " + packageName + " found on unknown volume " + volumeUuid
21354                                + "; expected volume " + ps.volumeUuid);
21355            } else if (!ps.getInstalled(userId)) {
21356                throw new PackageManagerException(
21357                        "Package " + packageName + " not installed for user " + userId);
21358            }
21359        }
21360    }
21361
21362    private List<String> collectAbsoluteCodePaths() {
21363        synchronized (mPackages) {
21364            List<String> codePaths = new ArrayList<>();
21365            final int packageCount = mSettings.mPackages.size();
21366            for (int i = 0; i < packageCount; i++) {
21367                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21368                codePaths.add(ps.codePath.getAbsolutePath());
21369            }
21370            return codePaths;
21371        }
21372    }
21373
21374    /**
21375     * Examine all apps present on given mounted volume, and destroy apps that
21376     * aren't expected, either due to uninstallation or reinstallation on
21377     * another volume.
21378     */
21379    private void reconcileApps(String volumeUuid) {
21380        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21381        List<File> filesToDelete = null;
21382
21383        final File[] files = FileUtils.listFilesOrEmpty(
21384                Environment.getDataAppDirectory(volumeUuid));
21385        for (File file : files) {
21386            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21387                    && !PackageInstallerService.isStageName(file.getName());
21388            if (!isPackage) {
21389                // Ignore entries which are not packages
21390                continue;
21391            }
21392
21393            String absolutePath = file.getAbsolutePath();
21394
21395            boolean pathValid = false;
21396            final int absoluteCodePathCount = absoluteCodePaths.size();
21397            for (int i = 0; i < absoluteCodePathCount; i++) {
21398                String absoluteCodePath = absoluteCodePaths.get(i);
21399                if (absolutePath.startsWith(absoluteCodePath)) {
21400                    pathValid = true;
21401                    break;
21402                }
21403            }
21404
21405            if (!pathValid) {
21406                if (filesToDelete == null) {
21407                    filesToDelete = new ArrayList<>();
21408                }
21409                filesToDelete.add(file);
21410            }
21411        }
21412
21413        if (filesToDelete != null) {
21414            final int fileToDeleteCount = filesToDelete.size();
21415            for (int i = 0; i < fileToDeleteCount; i++) {
21416                File fileToDelete = filesToDelete.get(i);
21417                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21418                synchronized (mInstallLock) {
21419                    removeCodePathLI(fileToDelete);
21420                }
21421            }
21422        }
21423    }
21424
21425    /**
21426     * Reconcile all app data for the given user.
21427     * <p>
21428     * Verifies that directories exist and that ownership and labeling is
21429     * correct for all installed apps on all mounted volumes.
21430     */
21431    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21432        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21433        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21434            final String volumeUuid = vol.getFsUuid();
21435            synchronized (mInstallLock) {
21436                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21437            }
21438        }
21439    }
21440
21441    /**
21442     * Reconcile all app data on given mounted volume.
21443     * <p>
21444     * Destroys app data that isn't expected, either due to uninstallation or
21445     * reinstallation on another volume.
21446     * <p>
21447     * Verifies that directories exist and that ownership and labeling is
21448     * correct for all installed apps.
21449     */
21450    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21451            boolean migrateAppData) {
21452        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21453                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21454
21455        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21456        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21457
21458        // First look for stale data that doesn't belong, and check if things
21459        // have changed since we did our last restorecon
21460        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21461            if (StorageManager.isFileEncryptedNativeOrEmulated()
21462                    && !StorageManager.isUserKeyUnlocked(userId)) {
21463                throw new RuntimeException(
21464                        "Yikes, someone asked us to reconcile CE storage while " + userId
21465                                + " was still locked; this would have caused massive data loss!");
21466            }
21467
21468            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21469            for (File file : files) {
21470                final String packageName = file.getName();
21471                try {
21472                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21473                } catch (PackageManagerException e) {
21474                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21475                    try {
21476                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21477                                StorageManager.FLAG_STORAGE_CE, 0);
21478                    } catch (InstallerException e2) {
21479                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21480                    }
21481                }
21482            }
21483        }
21484        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21485            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21486            for (File file : files) {
21487                final String packageName = file.getName();
21488                try {
21489                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21490                } catch (PackageManagerException e) {
21491                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21492                    try {
21493                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21494                                StorageManager.FLAG_STORAGE_DE, 0);
21495                    } catch (InstallerException e2) {
21496                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21497                    }
21498                }
21499            }
21500        }
21501
21502        // Ensure that data directories are ready to roll for all packages
21503        // installed for this volume and user
21504        final List<PackageSetting> packages;
21505        synchronized (mPackages) {
21506            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21507        }
21508        int preparedCount = 0;
21509        for (PackageSetting ps : packages) {
21510            final String packageName = ps.name;
21511            if (ps.pkg == null) {
21512                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21513                // TODO: might be due to legacy ASEC apps; we should circle back
21514                // and reconcile again once they're scanned
21515                continue;
21516            }
21517
21518            if (ps.getInstalled(userId)) {
21519                prepareAppDataLIF(ps.pkg, userId, flags);
21520
21521                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21522                    // We may have just shuffled around app data directories, so
21523                    // prepare them one more time
21524                    prepareAppDataLIF(ps.pkg, userId, flags);
21525                }
21526
21527                preparedCount++;
21528            }
21529        }
21530
21531        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21532    }
21533
21534    /**
21535     * Prepare app data for the given app just after it was installed or
21536     * upgraded. This method carefully only touches users that it's installed
21537     * for, and it forces a restorecon to handle any seinfo changes.
21538     * <p>
21539     * Verifies that directories exist and that ownership and labeling is
21540     * correct for all installed apps. If there is an ownership mismatch, it
21541     * will try recovering system apps by wiping data; third-party app data is
21542     * left intact.
21543     * <p>
21544     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21545     */
21546    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21547        final PackageSetting ps;
21548        synchronized (mPackages) {
21549            ps = mSettings.mPackages.get(pkg.packageName);
21550            mSettings.writeKernelMappingLPr(ps);
21551        }
21552
21553        final UserManager um = mContext.getSystemService(UserManager.class);
21554        UserManagerInternal umInternal = getUserManagerInternal();
21555        for (UserInfo user : um.getUsers()) {
21556            final int flags;
21557            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21558                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21559            } else if (umInternal.isUserRunning(user.id)) {
21560                flags = StorageManager.FLAG_STORAGE_DE;
21561            } else {
21562                continue;
21563            }
21564
21565            if (ps.getInstalled(user.id)) {
21566                // TODO: when user data is locked, mark that we're still dirty
21567                prepareAppDataLIF(pkg, user.id, flags);
21568            }
21569        }
21570    }
21571
21572    /**
21573     * Prepare app data for the given app.
21574     * <p>
21575     * Verifies that directories exist and that ownership and labeling is
21576     * correct for all installed apps. If there is an ownership mismatch, this
21577     * will try recovering system apps by wiping data; third-party app data is
21578     * left intact.
21579     */
21580    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21581        if (pkg == null) {
21582            Slog.wtf(TAG, "Package was null!", new Throwable());
21583            return;
21584        }
21585        prepareAppDataLeafLIF(pkg, userId, flags);
21586        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21587        for (int i = 0; i < childCount; i++) {
21588            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21589        }
21590    }
21591
21592    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21593        if (DEBUG_APP_DATA) {
21594            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21595                    + Integer.toHexString(flags));
21596        }
21597
21598        final String volumeUuid = pkg.volumeUuid;
21599        final String packageName = pkg.packageName;
21600        final ApplicationInfo app = pkg.applicationInfo;
21601        final int appId = UserHandle.getAppId(app.uid);
21602
21603        Preconditions.checkNotNull(app.seinfo);
21604
21605        long ceDataInode = -1;
21606        try {
21607            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21608                    appId, app.seinfo, app.targetSdkVersion);
21609        } catch (InstallerException e) {
21610            if (app.isSystemApp()) {
21611                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21612                        + ", but trying to recover: " + e);
21613                destroyAppDataLeafLIF(pkg, userId, flags);
21614                try {
21615                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21616                            appId, app.seinfo, app.targetSdkVersion);
21617                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21618                } catch (InstallerException e2) {
21619                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21620                }
21621            } else {
21622                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21623            }
21624        }
21625
21626        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21627            // TODO: mark this structure as dirty so we persist it!
21628            synchronized (mPackages) {
21629                final PackageSetting ps = mSettings.mPackages.get(packageName);
21630                if (ps != null) {
21631                    ps.setCeDataInode(ceDataInode, userId);
21632                }
21633            }
21634        }
21635
21636        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21637    }
21638
21639    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21640        if (pkg == null) {
21641            Slog.wtf(TAG, "Package was null!", new Throwable());
21642            return;
21643        }
21644        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21645        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21646        for (int i = 0; i < childCount; i++) {
21647            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21648        }
21649    }
21650
21651    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21652        final String volumeUuid = pkg.volumeUuid;
21653        final String packageName = pkg.packageName;
21654        final ApplicationInfo app = pkg.applicationInfo;
21655
21656        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21657            // Create a native library symlink only if we have native libraries
21658            // and if the native libraries are 32 bit libraries. We do not provide
21659            // this symlink for 64 bit libraries.
21660            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21661                final String nativeLibPath = app.nativeLibraryDir;
21662                try {
21663                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21664                            nativeLibPath, userId);
21665                } catch (InstallerException e) {
21666                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21667                }
21668            }
21669        }
21670    }
21671
21672    /**
21673     * For system apps on non-FBE devices, this method migrates any existing
21674     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21675     * requested by the app.
21676     */
21677    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21678        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21679                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21680            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21681                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21682            try {
21683                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21684                        storageTarget);
21685            } catch (InstallerException e) {
21686                logCriticalInfo(Log.WARN,
21687                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21688            }
21689            return true;
21690        } else {
21691            return false;
21692        }
21693    }
21694
21695    public PackageFreezer freezePackage(String packageName, String killReason) {
21696        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21697    }
21698
21699    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21700        return new PackageFreezer(packageName, userId, killReason);
21701    }
21702
21703    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21704            String killReason) {
21705        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21706    }
21707
21708    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21709            String killReason) {
21710        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21711            return new PackageFreezer();
21712        } else {
21713            return freezePackage(packageName, userId, killReason);
21714        }
21715    }
21716
21717    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21718            String killReason) {
21719        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21720    }
21721
21722    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21723            String killReason) {
21724        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21725            return new PackageFreezer();
21726        } else {
21727            return freezePackage(packageName, userId, killReason);
21728        }
21729    }
21730
21731    /**
21732     * Class that freezes and kills the given package upon creation, and
21733     * unfreezes it upon closing. This is typically used when doing surgery on
21734     * app code/data to prevent the app from running while you're working.
21735     */
21736    private class PackageFreezer implements AutoCloseable {
21737        private final String mPackageName;
21738        private final PackageFreezer[] mChildren;
21739
21740        private final boolean mWeFroze;
21741
21742        private final AtomicBoolean mClosed = new AtomicBoolean();
21743        private final CloseGuard mCloseGuard = CloseGuard.get();
21744
21745        /**
21746         * Create and return a stub freezer that doesn't actually do anything,
21747         * typically used when someone requested
21748         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21749         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21750         */
21751        public PackageFreezer() {
21752            mPackageName = null;
21753            mChildren = null;
21754            mWeFroze = false;
21755            mCloseGuard.open("close");
21756        }
21757
21758        public PackageFreezer(String packageName, int userId, String killReason) {
21759            synchronized (mPackages) {
21760                mPackageName = packageName;
21761                mWeFroze = mFrozenPackages.add(mPackageName);
21762
21763                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21764                if (ps != null) {
21765                    killApplication(ps.name, ps.appId, userId, killReason);
21766                }
21767
21768                final PackageParser.Package p = mPackages.get(packageName);
21769                if (p != null && p.childPackages != null) {
21770                    final int N = p.childPackages.size();
21771                    mChildren = new PackageFreezer[N];
21772                    for (int i = 0; i < N; i++) {
21773                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21774                                userId, killReason);
21775                    }
21776                } else {
21777                    mChildren = null;
21778                }
21779            }
21780            mCloseGuard.open("close");
21781        }
21782
21783        @Override
21784        protected void finalize() throws Throwable {
21785            try {
21786                mCloseGuard.warnIfOpen();
21787                close();
21788            } finally {
21789                super.finalize();
21790            }
21791        }
21792
21793        @Override
21794        public void close() {
21795            mCloseGuard.close();
21796            if (mClosed.compareAndSet(false, true)) {
21797                synchronized (mPackages) {
21798                    if (mWeFroze) {
21799                        mFrozenPackages.remove(mPackageName);
21800                    }
21801
21802                    if (mChildren != null) {
21803                        for (PackageFreezer freezer : mChildren) {
21804                            freezer.close();
21805                        }
21806                    }
21807                }
21808            }
21809        }
21810    }
21811
21812    /**
21813     * Verify that given package is currently frozen.
21814     */
21815    private void checkPackageFrozen(String packageName) {
21816        synchronized (mPackages) {
21817            if (!mFrozenPackages.contains(packageName)) {
21818                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21819            }
21820        }
21821    }
21822
21823    @Override
21824    public int movePackage(final String packageName, final String volumeUuid) {
21825        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21826
21827        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21828        final int moveId = mNextMoveId.getAndIncrement();
21829        mHandler.post(new Runnable() {
21830            @Override
21831            public void run() {
21832                try {
21833                    movePackageInternal(packageName, volumeUuid, moveId, user);
21834                } catch (PackageManagerException e) {
21835                    Slog.w(TAG, "Failed to move " + packageName, e);
21836                    mMoveCallbacks.notifyStatusChanged(moveId,
21837                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21838                }
21839            }
21840        });
21841        return moveId;
21842    }
21843
21844    private void movePackageInternal(final String packageName, final String volumeUuid,
21845            final int moveId, UserHandle user) throws PackageManagerException {
21846        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21847        final PackageManager pm = mContext.getPackageManager();
21848
21849        final boolean currentAsec;
21850        final String currentVolumeUuid;
21851        final File codeFile;
21852        final String installerPackageName;
21853        final String packageAbiOverride;
21854        final int appId;
21855        final String seinfo;
21856        final String label;
21857        final int targetSdkVersion;
21858        final PackageFreezer freezer;
21859        final int[] installedUserIds;
21860
21861        // reader
21862        synchronized (mPackages) {
21863            final PackageParser.Package pkg = mPackages.get(packageName);
21864            final PackageSetting ps = mSettings.mPackages.get(packageName);
21865            if (pkg == null || ps == null) {
21866                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21867            }
21868
21869            if (pkg.applicationInfo.isSystemApp()) {
21870                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21871                        "Cannot move system application");
21872            }
21873
21874            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21875            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21876                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21877            if (isInternalStorage && !allow3rdPartyOnInternal) {
21878                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21879                        "3rd party apps are not allowed on internal storage");
21880            }
21881
21882            if (pkg.applicationInfo.isExternalAsec()) {
21883                currentAsec = true;
21884                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21885            } else if (pkg.applicationInfo.isForwardLocked()) {
21886                currentAsec = true;
21887                currentVolumeUuid = "forward_locked";
21888            } else {
21889                currentAsec = false;
21890                currentVolumeUuid = ps.volumeUuid;
21891
21892                final File probe = new File(pkg.codePath);
21893                final File probeOat = new File(probe, "oat");
21894                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21895                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21896                            "Move only supported for modern cluster style installs");
21897                }
21898            }
21899
21900            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21901                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21902                        "Package already moved to " + volumeUuid);
21903            }
21904            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21905                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21906                        "Device admin cannot be moved");
21907            }
21908
21909            if (mFrozenPackages.contains(packageName)) {
21910                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21911                        "Failed to move already frozen package");
21912            }
21913
21914            codeFile = new File(pkg.codePath);
21915            installerPackageName = ps.installerPackageName;
21916            packageAbiOverride = ps.cpuAbiOverrideString;
21917            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21918            seinfo = pkg.applicationInfo.seinfo;
21919            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21920            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21921            freezer = freezePackage(packageName, "movePackageInternal");
21922            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21923        }
21924
21925        final Bundle extras = new Bundle();
21926        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21927        extras.putString(Intent.EXTRA_TITLE, label);
21928        mMoveCallbacks.notifyCreated(moveId, extras);
21929
21930        int installFlags;
21931        final boolean moveCompleteApp;
21932        final File measurePath;
21933
21934        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21935            installFlags = INSTALL_INTERNAL;
21936            moveCompleteApp = !currentAsec;
21937            measurePath = Environment.getDataAppDirectory(volumeUuid);
21938        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21939            installFlags = INSTALL_EXTERNAL;
21940            moveCompleteApp = false;
21941            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21942        } else {
21943            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21944            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21945                    || !volume.isMountedWritable()) {
21946                freezer.close();
21947                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21948                        "Move location not mounted private volume");
21949            }
21950
21951            Preconditions.checkState(!currentAsec);
21952
21953            installFlags = INSTALL_INTERNAL;
21954            moveCompleteApp = true;
21955            measurePath = Environment.getDataAppDirectory(volumeUuid);
21956        }
21957
21958        final PackageStats stats = new PackageStats(null, -1);
21959        synchronized (mInstaller) {
21960            for (int userId : installedUserIds) {
21961                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21962                    freezer.close();
21963                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21964                            "Failed to measure package size");
21965                }
21966            }
21967        }
21968
21969        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21970                + stats.dataSize);
21971
21972        final long startFreeBytes = measurePath.getFreeSpace();
21973        final long sizeBytes;
21974        if (moveCompleteApp) {
21975            sizeBytes = stats.codeSize + stats.dataSize;
21976        } else {
21977            sizeBytes = stats.codeSize;
21978        }
21979
21980        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21981            freezer.close();
21982            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21983                    "Not enough free space to move");
21984        }
21985
21986        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21987
21988        final CountDownLatch installedLatch = new CountDownLatch(1);
21989        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21990            @Override
21991            public void onUserActionRequired(Intent intent) throws RemoteException {
21992                throw new IllegalStateException();
21993            }
21994
21995            @Override
21996            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21997                    Bundle extras) throws RemoteException {
21998                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21999                        + PackageManager.installStatusToString(returnCode, msg));
22000
22001                installedLatch.countDown();
22002                freezer.close();
22003
22004                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22005                switch (status) {
22006                    case PackageInstaller.STATUS_SUCCESS:
22007                        mMoveCallbacks.notifyStatusChanged(moveId,
22008                                PackageManager.MOVE_SUCCEEDED);
22009                        break;
22010                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22011                        mMoveCallbacks.notifyStatusChanged(moveId,
22012                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22013                        break;
22014                    default:
22015                        mMoveCallbacks.notifyStatusChanged(moveId,
22016                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22017                        break;
22018                }
22019            }
22020        };
22021
22022        final MoveInfo move;
22023        if (moveCompleteApp) {
22024            // Kick off a thread to report progress estimates
22025            new Thread() {
22026                @Override
22027                public void run() {
22028                    while (true) {
22029                        try {
22030                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22031                                break;
22032                            }
22033                        } catch (InterruptedException ignored) {
22034                        }
22035
22036                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22037                        final int progress = 10 + (int) MathUtils.constrain(
22038                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22039                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22040                    }
22041                }
22042            }.start();
22043
22044            final String dataAppName = codeFile.getName();
22045            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22046                    dataAppName, appId, seinfo, targetSdkVersion);
22047        } else {
22048            move = null;
22049        }
22050
22051        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22052
22053        final Message msg = mHandler.obtainMessage(INIT_COPY);
22054        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22055        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22056                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22057                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22058                PackageManager.INSTALL_REASON_UNKNOWN);
22059        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22060        msg.obj = params;
22061
22062        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22063                System.identityHashCode(msg.obj));
22064        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22065                System.identityHashCode(msg.obj));
22066
22067        mHandler.sendMessage(msg);
22068    }
22069
22070    @Override
22071    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22072        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22073
22074        final int realMoveId = mNextMoveId.getAndIncrement();
22075        final Bundle extras = new Bundle();
22076        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22077        mMoveCallbacks.notifyCreated(realMoveId, extras);
22078
22079        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22080            @Override
22081            public void onCreated(int moveId, Bundle extras) {
22082                // Ignored
22083            }
22084
22085            @Override
22086            public void onStatusChanged(int moveId, int status, long estMillis) {
22087                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22088            }
22089        };
22090
22091        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22092        storage.setPrimaryStorageUuid(volumeUuid, callback);
22093        return realMoveId;
22094    }
22095
22096    @Override
22097    public int getMoveStatus(int moveId) {
22098        mContext.enforceCallingOrSelfPermission(
22099                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22100        return mMoveCallbacks.mLastStatus.get(moveId);
22101    }
22102
22103    @Override
22104    public void registerMoveCallback(IPackageMoveObserver callback) {
22105        mContext.enforceCallingOrSelfPermission(
22106                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22107        mMoveCallbacks.register(callback);
22108    }
22109
22110    @Override
22111    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22112        mContext.enforceCallingOrSelfPermission(
22113                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22114        mMoveCallbacks.unregister(callback);
22115    }
22116
22117    @Override
22118    public boolean setInstallLocation(int loc) {
22119        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22120                null);
22121        if (getInstallLocation() == loc) {
22122            return true;
22123        }
22124        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22125                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22126            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22127                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22128            return true;
22129        }
22130        return false;
22131   }
22132
22133    @Override
22134    public int getInstallLocation() {
22135        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22136                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22137                PackageHelper.APP_INSTALL_AUTO);
22138    }
22139
22140    /** Called by UserManagerService */
22141    void cleanUpUser(UserManagerService userManager, int userHandle) {
22142        synchronized (mPackages) {
22143            mDirtyUsers.remove(userHandle);
22144            mUserNeedsBadging.delete(userHandle);
22145            mSettings.removeUserLPw(userHandle);
22146            mPendingBroadcasts.remove(userHandle);
22147            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22148            removeUnusedPackagesLPw(userManager, userHandle);
22149        }
22150    }
22151
22152    /**
22153     * We're removing userHandle and would like to remove any downloaded packages
22154     * that are no longer in use by any other user.
22155     * @param userHandle the user being removed
22156     */
22157    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22158        final boolean DEBUG_CLEAN_APKS = false;
22159        int [] users = userManager.getUserIds();
22160        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22161        while (psit.hasNext()) {
22162            PackageSetting ps = psit.next();
22163            if (ps.pkg == null) {
22164                continue;
22165            }
22166            final String packageName = ps.pkg.packageName;
22167            // Skip over if system app
22168            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22169                continue;
22170            }
22171            if (DEBUG_CLEAN_APKS) {
22172                Slog.i(TAG, "Checking package " + packageName);
22173            }
22174            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22175            if (keep) {
22176                if (DEBUG_CLEAN_APKS) {
22177                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22178                }
22179            } else {
22180                for (int i = 0; i < users.length; i++) {
22181                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22182                        keep = true;
22183                        if (DEBUG_CLEAN_APKS) {
22184                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22185                                    + users[i]);
22186                        }
22187                        break;
22188                    }
22189                }
22190            }
22191            if (!keep) {
22192                if (DEBUG_CLEAN_APKS) {
22193                    Slog.i(TAG, "  Removing package " + packageName);
22194                }
22195                mHandler.post(new Runnable() {
22196                    public void run() {
22197                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22198                                userHandle, 0);
22199                    } //end run
22200                });
22201            }
22202        }
22203    }
22204
22205    /** Called by UserManagerService */
22206    void createNewUser(int userId, String[] disallowedPackages) {
22207        synchronized (mInstallLock) {
22208            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22209        }
22210        synchronized (mPackages) {
22211            scheduleWritePackageRestrictionsLocked(userId);
22212            scheduleWritePackageListLocked(userId);
22213            applyFactoryDefaultBrowserLPw(userId);
22214            primeDomainVerificationsLPw(userId);
22215        }
22216    }
22217
22218    void onNewUserCreated(final int userId) {
22219        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22220        // If permission review for legacy apps is required, we represent
22221        // dagerous permissions for such apps as always granted runtime
22222        // permissions to keep per user flag state whether review is needed.
22223        // Hence, if a new user is added we have to propagate dangerous
22224        // permission grants for these legacy apps.
22225        if (mPermissionReviewRequired) {
22226            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22227                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22228        }
22229    }
22230
22231    @Override
22232    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22233        mContext.enforceCallingOrSelfPermission(
22234                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22235                "Only package verification agents can read the verifier device identity");
22236
22237        synchronized (mPackages) {
22238            return mSettings.getVerifierDeviceIdentityLPw();
22239        }
22240    }
22241
22242    @Override
22243    public void setPermissionEnforced(String permission, boolean enforced) {
22244        // TODO: Now that we no longer change GID for storage, this should to away.
22245        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22246                "setPermissionEnforced");
22247        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22248            synchronized (mPackages) {
22249                if (mSettings.mReadExternalStorageEnforced == null
22250                        || mSettings.mReadExternalStorageEnforced != enforced) {
22251                    mSettings.mReadExternalStorageEnforced = enforced;
22252                    mSettings.writeLPr();
22253                }
22254            }
22255            // kill any non-foreground processes so we restart them and
22256            // grant/revoke the GID.
22257            final IActivityManager am = ActivityManager.getService();
22258            if (am != null) {
22259                final long token = Binder.clearCallingIdentity();
22260                try {
22261                    am.killProcessesBelowForeground("setPermissionEnforcement");
22262                } catch (RemoteException e) {
22263                } finally {
22264                    Binder.restoreCallingIdentity(token);
22265                }
22266            }
22267        } else {
22268            throw new IllegalArgumentException("No selective enforcement for " + permission);
22269        }
22270    }
22271
22272    @Override
22273    @Deprecated
22274    public boolean isPermissionEnforced(String permission) {
22275        return true;
22276    }
22277
22278    @Override
22279    public boolean isStorageLow() {
22280        final long token = Binder.clearCallingIdentity();
22281        try {
22282            final DeviceStorageMonitorInternal
22283                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22284            if (dsm != null) {
22285                return dsm.isMemoryLow();
22286            } else {
22287                return false;
22288            }
22289        } finally {
22290            Binder.restoreCallingIdentity(token);
22291        }
22292    }
22293
22294    @Override
22295    public IPackageInstaller getPackageInstaller() {
22296        return mInstallerService;
22297    }
22298
22299    private boolean userNeedsBadging(int userId) {
22300        int index = mUserNeedsBadging.indexOfKey(userId);
22301        if (index < 0) {
22302            final UserInfo userInfo;
22303            final long token = Binder.clearCallingIdentity();
22304            try {
22305                userInfo = sUserManager.getUserInfo(userId);
22306            } finally {
22307                Binder.restoreCallingIdentity(token);
22308            }
22309            final boolean b;
22310            if (userInfo != null && userInfo.isManagedProfile()) {
22311                b = true;
22312            } else {
22313                b = false;
22314            }
22315            mUserNeedsBadging.put(userId, b);
22316            return b;
22317        }
22318        return mUserNeedsBadging.valueAt(index);
22319    }
22320
22321    @Override
22322    public KeySet getKeySetByAlias(String packageName, String alias) {
22323        if (packageName == null || alias == null) {
22324            return null;
22325        }
22326        synchronized(mPackages) {
22327            final PackageParser.Package pkg = mPackages.get(packageName);
22328            if (pkg == null) {
22329                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22330                throw new IllegalArgumentException("Unknown package: " + packageName);
22331            }
22332            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22333            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22334        }
22335    }
22336
22337    @Override
22338    public KeySet getSigningKeySet(String packageName) {
22339        if (packageName == null) {
22340            return null;
22341        }
22342        synchronized(mPackages) {
22343            final PackageParser.Package pkg = mPackages.get(packageName);
22344            if (pkg == null) {
22345                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22346                throw new IllegalArgumentException("Unknown package: " + packageName);
22347            }
22348            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22349                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22350                throw new SecurityException("May not access signing KeySet of other apps.");
22351            }
22352            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22353            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22354        }
22355    }
22356
22357    @Override
22358    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22359        if (packageName == null || ks == null) {
22360            return false;
22361        }
22362        synchronized(mPackages) {
22363            final PackageParser.Package pkg = mPackages.get(packageName);
22364            if (pkg == null) {
22365                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22366                throw new IllegalArgumentException("Unknown package: " + packageName);
22367            }
22368            IBinder ksh = ks.getToken();
22369            if (ksh instanceof KeySetHandle) {
22370                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22371                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22372            }
22373            return false;
22374        }
22375    }
22376
22377    @Override
22378    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22379        if (packageName == null || ks == null) {
22380            return false;
22381        }
22382        synchronized(mPackages) {
22383            final PackageParser.Package pkg = mPackages.get(packageName);
22384            if (pkg == null) {
22385                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22386                throw new IllegalArgumentException("Unknown package: " + packageName);
22387            }
22388            IBinder ksh = ks.getToken();
22389            if (ksh instanceof KeySetHandle) {
22390                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22391                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22392            }
22393            return false;
22394        }
22395    }
22396
22397    private void deletePackageIfUnusedLPr(final String packageName) {
22398        PackageSetting ps = mSettings.mPackages.get(packageName);
22399        if (ps == null) {
22400            return;
22401        }
22402        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22403            // TODO Implement atomic delete if package is unused
22404            // It is currently possible that the package will be deleted even if it is installed
22405            // after this method returns.
22406            mHandler.post(new Runnable() {
22407                public void run() {
22408                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22409                            0, PackageManager.DELETE_ALL_USERS);
22410                }
22411            });
22412        }
22413    }
22414
22415    /**
22416     * Check and throw if the given before/after packages would be considered a
22417     * downgrade.
22418     */
22419    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22420            throws PackageManagerException {
22421        if (after.versionCode < before.mVersionCode) {
22422            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22423                    "Update version code " + after.versionCode + " is older than current "
22424                    + before.mVersionCode);
22425        } else if (after.versionCode == before.mVersionCode) {
22426            if (after.baseRevisionCode < before.baseRevisionCode) {
22427                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22428                        "Update base revision code " + after.baseRevisionCode
22429                        + " is older than current " + before.baseRevisionCode);
22430            }
22431
22432            if (!ArrayUtils.isEmpty(after.splitNames)) {
22433                for (int i = 0; i < after.splitNames.length; i++) {
22434                    final String splitName = after.splitNames[i];
22435                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22436                    if (j != -1) {
22437                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22438                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22439                                    "Update split " + splitName + " revision code "
22440                                    + after.splitRevisionCodes[i] + " is older than current "
22441                                    + before.splitRevisionCodes[j]);
22442                        }
22443                    }
22444                }
22445            }
22446        }
22447    }
22448
22449    private static class MoveCallbacks extends Handler {
22450        private static final int MSG_CREATED = 1;
22451        private static final int MSG_STATUS_CHANGED = 2;
22452
22453        private final RemoteCallbackList<IPackageMoveObserver>
22454                mCallbacks = new RemoteCallbackList<>();
22455
22456        private final SparseIntArray mLastStatus = new SparseIntArray();
22457
22458        public MoveCallbacks(Looper looper) {
22459            super(looper);
22460        }
22461
22462        public void register(IPackageMoveObserver callback) {
22463            mCallbacks.register(callback);
22464        }
22465
22466        public void unregister(IPackageMoveObserver callback) {
22467            mCallbacks.unregister(callback);
22468        }
22469
22470        @Override
22471        public void handleMessage(Message msg) {
22472            final SomeArgs args = (SomeArgs) msg.obj;
22473            final int n = mCallbacks.beginBroadcast();
22474            for (int i = 0; i < n; i++) {
22475                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22476                try {
22477                    invokeCallback(callback, msg.what, args);
22478                } catch (RemoteException ignored) {
22479                }
22480            }
22481            mCallbacks.finishBroadcast();
22482            args.recycle();
22483        }
22484
22485        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22486                throws RemoteException {
22487            switch (what) {
22488                case MSG_CREATED: {
22489                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22490                    break;
22491                }
22492                case MSG_STATUS_CHANGED: {
22493                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22494                    break;
22495                }
22496            }
22497        }
22498
22499        private void notifyCreated(int moveId, Bundle extras) {
22500            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22501
22502            final SomeArgs args = SomeArgs.obtain();
22503            args.argi1 = moveId;
22504            args.arg2 = extras;
22505            obtainMessage(MSG_CREATED, args).sendToTarget();
22506        }
22507
22508        private void notifyStatusChanged(int moveId, int status) {
22509            notifyStatusChanged(moveId, status, -1);
22510        }
22511
22512        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22513            Slog.v(TAG, "Move " + moveId + " status " + status);
22514
22515            final SomeArgs args = SomeArgs.obtain();
22516            args.argi1 = moveId;
22517            args.argi2 = status;
22518            args.arg3 = estMillis;
22519            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22520
22521            synchronized (mLastStatus) {
22522                mLastStatus.put(moveId, status);
22523            }
22524        }
22525    }
22526
22527    private final static class OnPermissionChangeListeners extends Handler {
22528        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22529
22530        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22531                new RemoteCallbackList<>();
22532
22533        public OnPermissionChangeListeners(Looper looper) {
22534            super(looper);
22535        }
22536
22537        @Override
22538        public void handleMessage(Message msg) {
22539            switch (msg.what) {
22540                case MSG_ON_PERMISSIONS_CHANGED: {
22541                    final int uid = msg.arg1;
22542                    handleOnPermissionsChanged(uid);
22543                } break;
22544            }
22545        }
22546
22547        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22548            mPermissionListeners.register(listener);
22549
22550        }
22551
22552        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22553            mPermissionListeners.unregister(listener);
22554        }
22555
22556        public void onPermissionsChanged(int uid) {
22557            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22558                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22559            }
22560        }
22561
22562        private void handleOnPermissionsChanged(int uid) {
22563            final int count = mPermissionListeners.beginBroadcast();
22564            try {
22565                for (int i = 0; i < count; i++) {
22566                    IOnPermissionsChangeListener callback = mPermissionListeners
22567                            .getBroadcastItem(i);
22568                    try {
22569                        callback.onPermissionsChanged(uid);
22570                    } catch (RemoteException e) {
22571                        Log.e(TAG, "Permission listener is dead", e);
22572                    }
22573                }
22574            } finally {
22575                mPermissionListeners.finishBroadcast();
22576            }
22577        }
22578    }
22579
22580    private class PackageManagerInternalImpl extends PackageManagerInternal {
22581        @Override
22582        public void setLocationPackagesProvider(PackagesProvider provider) {
22583            synchronized (mPackages) {
22584                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22585            }
22586        }
22587
22588        @Override
22589        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22590            synchronized (mPackages) {
22591                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22592            }
22593        }
22594
22595        @Override
22596        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22597            synchronized (mPackages) {
22598                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22599            }
22600        }
22601
22602        @Override
22603        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22604            synchronized (mPackages) {
22605                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22606            }
22607        }
22608
22609        @Override
22610        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22611            synchronized (mPackages) {
22612                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22613            }
22614        }
22615
22616        @Override
22617        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22618            synchronized (mPackages) {
22619                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22620            }
22621        }
22622
22623        @Override
22624        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22625            synchronized (mPackages) {
22626                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22627                        packageName, userId);
22628            }
22629        }
22630
22631        @Override
22632        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22633            synchronized (mPackages) {
22634                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22635                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22636                        packageName, userId);
22637            }
22638        }
22639
22640        @Override
22641        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22642            synchronized (mPackages) {
22643                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22644                        packageName, userId);
22645            }
22646        }
22647
22648        @Override
22649        public void setKeepUninstalledPackages(final List<String> packageList) {
22650            Preconditions.checkNotNull(packageList);
22651            List<String> removedFromList = null;
22652            synchronized (mPackages) {
22653                if (mKeepUninstalledPackages != null) {
22654                    final int packagesCount = mKeepUninstalledPackages.size();
22655                    for (int i = 0; i < packagesCount; i++) {
22656                        String oldPackage = mKeepUninstalledPackages.get(i);
22657                        if (packageList != null && packageList.contains(oldPackage)) {
22658                            continue;
22659                        }
22660                        if (removedFromList == null) {
22661                            removedFromList = new ArrayList<>();
22662                        }
22663                        removedFromList.add(oldPackage);
22664                    }
22665                }
22666                mKeepUninstalledPackages = new ArrayList<>(packageList);
22667                if (removedFromList != null) {
22668                    final int removedCount = removedFromList.size();
22669                    for (int i = 0; i < removedCount; i++) {
22670                        deletePackageIfUnusedLPr(removedFromList.get(i));
22671                    }
22672                }
22673            }
22674        }
22675
22676        @Override
22677        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22678            synchronized (mPackages) {
22679                // If we do not support permission review, done.
22680                if (!mPermissionReviewRequired) {
22681                    return false;
22682                }
22683
22684                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22685                if (packageSetting == null) {
22686                    return false;
22687                }
22688
22689                // Permission review applies only to apps not supporting the new permission model.
22690                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22691                    return false;
22692                }
22693
22694                // Legacy apps have the permission and get user consent on launch.
22695                PermissionsState permissionsState = packageSetting.getPermissionsState();
22696                return permissionsState.isPermissionReviewRequired(userId);
22697            }
22698        }
22699
22700        @Override
22701        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22702            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22703        }
22704
22705        @Override
22706        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22707                int userId) {
22708            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22709        }
22710
22711        @Override
22712        public void setDeviceAndProfileOwnerPackages(
22713                int deviceOwnerUserId, String deviceOwnerPackage,
22714                SparseArray<String> profileOwnerPackages) {
22715            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22716                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22717        }
22718
22719        @Override
22720        public boolean isPackageDataProtected(int userId, String packageName) {
22721            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22722        }
22723
22724        @Override
22725        public boolean isPackageEphemeral(int userId, String packageName) {
22726            synchronized (mPackages) {
22727                PackageParser.Package p = mPackages.get(packageName);
22728                return p != null ? p.applicationInfo.isInstantApp() : false;
22729            }
22730        }
22731
22732        @Override
22733        public boolean wasPackageEverLaunched(String packageName, int userId) {
22734            synchronized (mPackages) {
22735                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22736            }
22737        }
22738
22739        @Override
22740        public void grantRuntimePermission(String packageName, String name, int userId,
22741                boolean overridePolicy) {
22742            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22743                    overridePolicy);
22744        }
22745
22746        @Override
22747        public void revokeRuntimePermission(String packageName, String name, int userId,
22748                boolean overridePolicy) {
22749            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22750                    overridePolicy);
22751        }
22752
22753        @Override
22754        public String getNameForUid(int uid) {
22755            return PackageManagerService.this.getNameForUid(uid);
22756        }
22757
22758        @Override
22759        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22760                Intent origIntent, String resolvedType, Intent launchIntent,
22761                String callingPackage, int userId) {
22762            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22763                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22764        }
22765
22766        @Override
22767        public void grantEphemeralAccess(int userId, Intent intent,
22768                int targetAppId, int ephemeralAppId) {
22769            synchronized (mPackages) {
22770                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22771                        targetAppId, ephemeralAppId);
22772            }
22773        }
22774
22775        @Override
22776        public void pruneInstantApps() {
22777            synchronized (mPackages) {
22778                mInstantAppRegistry.pruneInstantAppsLPw();
22779            }
22780        }
22781
22782        @Override
22783        public String getSetupWizardPackageName() {
22784            return mSetupWizardPackage;
22785        }
22786
22787        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22788            if (policy != null) {
22789                mExternalSourcesPolicy = policy;
22790            }
22791        }
22792
22793        @Override
22794        public List<PackageInfo> getOverlayPackages(int userId) {
22795            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22796            synchronized (mPackages) {
22797                for (PackageParser.Package p : mPackages.values()) {
22798                    if (p.mOverlayTarget != null) {
22799                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22800                        if (pkg != null) {
22801                            overlayPackages.add(pkg);
22802                        }
22803                    }
22804                }
22805            }
22806            return overlayPackages;
22807        }
22808
22809        @Override
22810        public List<String> getTargetPackageNames(int userId) {
22811            List<String> targetPackages = new ArrayList<>();
22812            synchronized (mPackages) {
22813                for (PackageParser.Package p : mPackages.values()) {
22814                    if (p.mOverlayTarget == null) {
22815                        targetPackages.add(p.packageName);
22816                    }
22817                }
22818            }
22819            return targetPackages;
22820        }
22821
22822
22823        @Override
22824        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22825                List<String> overlayPackageNames) {
22826            // TODO: implement when we integrate OMS properly
22827            return false;
22828        }
22829    }
22830
22831    @Override
22832    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22833        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22834        synchronized (mPackages) {
22835            final long identity = Binder.clearCallingIdentity();
22836            try {
22837                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22838                        packageNames, userId);
22839            } finally {
22840                Binder.restoreCallingIdentity(identity);
22841            }
22842        }
22843    }
22844
22845    @Override
22846    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22847        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22848        synchronized (mPackages) {
22849            final long identity = Binder.clearCallingIdentity();
22850            try {
22851                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22852                        packageNames, userId);
22853            } finally {
22854                Binder.restoreCallingIdentity(identity);
22855            }
22856        }
22857    }
22858
22859    private static void enforceSystemOrPhoneCaller(String tag) {
22860        int callingUid = Binder.getCallingUid();
22861        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22862            throw new SecurityException(
22863                    "Cannot call " + tag + " from UID " + callingUid);
22864        }
22865    }
22866
22867    boolean isHistoricalPackageUsageAvailable() {
22868        return mPackageUsage.isHistoricalPackageUsageAvailable();
22869    }
22870
22871    /**
22872     * Return a <b>copy</b> of the collection of packages known to the package manager.
22873     * @return A copy of the values of mPackages.
22874     */
22875    Collection<PackageParser.Package> getPackages() {
22876        synchronized (mPackages) {
22877            return new ArrayList<>(mPackages.values());
22878        }
22879    }
22880
22881    /**
22882     * Logs process start information (including base APK hash) to the security log.
22883     * @hide
22884     */
22885    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22886            String apkFile, int pid) {
22887        if (!SecurityLog.isLoggingEnabled()) {
22888            return;
22889        }
22890        Bundle data = new Bundle();
22891        data.putLong("startTimestamp", System.currentTimeMillis());
22892        data.putString("processName", processName);
22893        data.putInt("uid", uid);
22894        data.putString("seinfo", seinfo);
22895        data.putString("apkFile", apkFile);
22896        data.putInt("pid", pid);
22897        Message msg = mProcessLoggingHandler.obtainMessage(
22898                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22899        msg.setData(data);
22900        mProcessLoggingHandler.sendMessage(msg);
22901    }
22902
22903    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22904        return mCompilerStats.getPackageStats(pkgName);
22905    }
22906
22907    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22908        return getOrCreateCompilerPackageStats(pkg.packageName);
22909    }
22910
22911    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22912        return mCompilerStats.getOrCreatePackageStats(pkgName);
22913    }
22914
22915    public void deleteCompilerPackageStats(String pkgName) {
22916        mCompilerStats.deletePackageStats(pkgName);
22917    }
22918
22919    @Override
22920    public int getInstallReason(String packageName, int userId) {
22921        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22922                true /* requireFullPermission */, false /* checkShell */,
22923                "get install reason");
22924        synchronized (mPackages) {
22925            final PackageSetting ps = mSettings.mPackages.get(packageName);
22926            if (ps != null) {
22927                return ps.getInstallReason(userId);
22928            }
22929        }
22930        return PackageManager.INSTALL_REASON_UNKNOWN;
22931    }
22932
22933    @Override
22934    public boolean canRequestPackageInstalls(String packageName, int userId) {
22935        int callingUid = Binder.getCallingUid();
22936        int uid = getPackageUid(packageName, 0, userId);
22937        if (callingUid != uid && callingUid != Process.ROOT_UID
22938                && callingUid != Process.SYSTEM_UID) {
22939            throw new SecurityException(
22940                    "Caller uid " + callingUid + " does not own package " + packageName);
22941        }
22942        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22943        if (info == null) {
22944            return false;
22945        }
22946        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22947            throw new UnsupportedOperationException(
22948                    "Operation only supported on apps targeting Android O or higher");
22949        }
22950        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22951        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22952        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22953            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22954        }
22955        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22956            return false;
22957        }
22958        if (mExternalSourcesPolicy != null) {
22959            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22960            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22961                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22962            }
22963        }
22964        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
22965    }
22966}
22967