PackageManagerService.java revision a28071306ec86da664603ff08e74ec7acadbd427
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.EphemeralApplicationInfo;
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.EventLogTags;
259import com.android.server.FgThread;
260import com.android.server.IntentResolver;
261import com.android.server.LocalServices;
262import com.android.server.ServiceThread;
263import com.android.server.SystemConfig;
264import com.android.server.Watchdog;
265import com.android.server.net.NetworkPolicyManagerInternal;
266import com.android.server.pm.Installer.InstallerException;
267import com.android.server.pm.PermissionsState.PermissionState;
268import com.android.server.pm.Settings.DatabaseVersion;
269import com.android.server.pm.Settings.VersionInfo;
270import com.android.server.pm.dex.DexManager;
271import com.android.server.storage.DeviceStorageMonitorInternal;
272
273import dalvik.system.CloseGuard;
274import dalvik.system.DexFile;
275import dalvik.system.VMRuntime;
276
277import libcore.io.IoUtils;
278import libcore.util.EmptyArray;
279
280import org.xmlpull.v1.XmlPullParser;
281import org.xmlpull.v1.XmlPullParserException;
282import org.xmlpull.v1.XmlSerializer;
283
284import java.io.BufferedOutputStream;
285import java.io.BufferedReader;
286import java.io.ByteArrayInputStream;
287import java.io.ByteArrayOutputStream;
288import java.io.File;
289import java.io.FileDescriptor;
290import java.io.FileInputStream;
291import java.io.FileNotFoundException;
292import java.io.FileOutputStream;
293import java.io.FileReader;
294import java.io.FilenameFilter;
295import java.io.IOException;
296import java.io.PrintWriter;
297import java.nio.charset.StandardCharsets;
298import java.security.DigestInputStream;
299import java.security.MessageDigest;
300import java.security.NoSuchAlgorithmException;
301import java.security.PublicKey;
302import java.security.SecureRandom;
303import java.security.cert.Certificate;
304import java.security.cert.CertificateEncodingException;
305import java.security.cert.CertificateException;
306import java.text.SimpleDateFormat;
307import java.util.ArrayList;
308import java.util.Arrays;
309import java.util.Collection;
310import java.util.Collections;
311import java.util.Comparator;
312import java.util.Date;
313import java.util.HashSet;
314import java.util.HashMap;
315import java.util.Iterator;
316import java.util.List;
317import java.util.Map;
318import java.util.Objects;
319import java.util.Set;
320import java.util.concurrent.CountDownLatch;
321import java.util.concurrent.TimeUnit;
322import java.util.concurrent.atomic.AtomicBoolean;
323import java.util.concurrent.atomic.AtomicInteger;
324
325/**
326 * Keep track of all those APKs everywhere.
327 * <p>
328 * Internally there are two important locks:
329 * <ul>
330 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
331 * and other related state. It is a fine-grained lock that should only be held
332 * momentarily, as it's one of the most contended locks in the system.
333 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
334 * operations typically involve heavy lifting of application data on disk. Since
335 * {@code installd} is single-threaded, and it's operations can often be slow,
336 * this lock should never be acquired while already holding {@link #mPackages}.
337 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
338 * holding {@link #mInstallLock}.
339 * </ul>
340 * Many internal methods rely on the caller to hold the appropriate locks, and
341 * this contract is expressed through method name suffixes:
342 * <ul>
343 * <li>fooLI(): the caller must hold {@link #mInstallLock}
344 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
345 * being modified must be frozen
346 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
347 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
348 * </ul>
349 * <p>
350 * Because this class is very central to the platform's security; please run all
351 * CTS and unit tests whenever making modifications:
352 *
353 * <pre>
354 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
355 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
356 * </pre>
357 */
358public class PackageManagerService extends IPackageManager.Stub {
359    static final String TAG = "PackageManager";
360    static final boolean DEBUG_SETTINGS = false;
361    static final boolean DEBUG_PREFERRED = false;
362    static final boolean DEBUG_UPGRADE = false;
363    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
364    private static final boolean DEBUG_BACKUP = false;
365    private static final boolean DEBUG_INSTALL = false;
366    private static final boolean DEBUG_REMOVE = false;
367    private static final boolean DEBUG_BROADCASTS = false;
368    private static final boolean DEBUG_SHOW_INFO = false;
369    private static final boolean DEBUG_PACKAGE_INFO = false;
370    private static final boolean DEBUG_INTENT_MATCHING = false;
371    private static final boolean DEBUG_PACKAGE_SCANNING = false;
372    private static final boolean DEBUG_VERIFY = false;
373    private static final boolean DEBUG_FILTERS = false;
374
375    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
376    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
377    // user, but by default initialize to this.
378    static final boolean DEBUG_DEXOPT = false;
379
380    private static final boolean DEBUG_ABI_SELECTION = false;
381    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
382    private static final boolean DEBUG_TRIAGED_MISSING = false;
383    private static final boolean DEBUG_APP_DATA = false;
384
385    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
386    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
387
388    private static final boolean DISABLE_EPHEMERAL_APPS = false;
389    private static final boolean HIDE_EPHEMERAL_APIS = true;
390
391    private static final boolean ENABLE_QUOTA =
392            SystemProperties.getBoolean("persist.fw.quota", false);
393
394    private static final int RADIO_UID = Process.PHONE_UID;
395    private static final int LOG_UID = Process.LOG_UID;
396    private static final int NFC_UID = Process.NFC_UID;
397    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
398    private static final int SHELL_UID = Process.SHELL_UID;
399
400    // Cap the size of permission trees that 3rd party apps can define
401    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
402
403    // Suffix used during package installation when copying/moving
404    // package apks to install directory.
405    private static final String INSTALL_PACKAGE_SUFFIX = "-";
406
407    static final int SCAN_NO_DEX = 1<<1;
408    static final int SCAN_FORCE_DEX = 1<<2;
409    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
410    static final int SCAN_NEW_INSTALL = 1<<4;
411    static final int SCAN_UPDATE_TIME = 1<<5;
412    static final int SCAN_BOOTING = 1<<6;
413    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
414    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
415    static final int SCAN_REPLACING = 1<<9;
416    static final int SCAN_REQUIRE_KNOWN = 1<<10;
417    static final int SCAN_MOVE = 1<<11;
418    static final int SCAN_INITIAL = 1<<12;
419    static final int SCAN_CHECK_ONLY = 1<<13;
420    static final int SCAN_DONT_KILL_APP = 1<<14;
421    static final int SCAN_IGNORE_FROZEN = 1<<15;
422    static final int REMOVE_CHATTY = 1<<16;
423    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
424
425    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
426
427    private static final int[] EMPTY_INT_ARRAY = new int[0];
428
429    /**
430     * Timeout (in milliseconds) after which the watchdog should declare that
431     * our handler thread is wedged.  The usual default for such things is one
432     * minute but we sometimes do very lengthy I/O operations on this thread,
433     * such as installing multi-gigabyte applications, so ours needs to be longer.
434     */
435    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
436
437    /**
438     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
439     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
440     * settings entry if available, otherwise we use the hardcoded default.  If it's been
441     * more than this long since the last fstrim, we force one during the boot sequence.
442     *
443     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
444     * one gets run at the next available charging+idle time.  This final mandatory
445     * no-fstrim check kicks in only of the other scheduling criteria is never met.
446     */
447    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
448
449    /**
450     * Whether verification is enabled by default.
451     */
452    private static final boolean DEFAULT_VERIFY_ENABLE = true;
453
454    /**
455     * The default maximum time to wait for the verification agent to return in
456     * milliseconds.
457     */
458    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
459
460    /**
461     * The default response for package verification timeout.
462     *
463     * This can be either PackageManager.VERIFICATION_ALLOW or
464     * PackageManager.VERIFICATION_REJECT.
465     */
466    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
467
468    static final String PLATFORM_PACKAGE_NAME = "android";
469
470    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
471
472    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
473            DEFAULT_CONTAINER_PACKAGE,
474            "com.android.defcontainer.DefaultContainerService");
475
476    private static final String KILL_APP_REASON_GIDS_CHANGED =
477            "permission grant or revoke changed gids";
478
479    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
480            "permissions revoked";
481
482    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
483
484    private static final String PACKAGE_SCHEME = "package";
485
486    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
487    /**
488     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
489     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
490     * VENDOR_OVERLAY_DIR.
491     */
492    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
493    /**
494     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
495     * is in VENDOR_OVERLAY_THEME_PROPERTY.
496     */
497    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
498            = "persist.vendor.overlay.theme";
499
500    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
540    public static final int REASON_SHARED_APK = 6;
541    public static final int REASON_FORCED_DEXOPT = 7;
542    public static final int REASON_CORE_APP = 8;
543
544    public static final int REASON_LAST = REASON_CORE_APP;
545
546    /** Special library name that skips shared libraries check during compilation. */
547    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
548
549    /** All dangerous permission names in the same order as the events in MetricsEvent */
550    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
551            Manifest.permission.READ_CALENDAR,
552            Manifest.permission.WRITE_CALENDAR,
553            Manifest.permission.CAMERA,
554            Manifest.permission.READ_CONTACTS,
555            Manifest.permission.WRITE_CONTACTS,
556            Manifest.permission.GET_ACCOUNTS,
557            Manifest.permission.ACCESS_FINE_LOCATION,
558            Manifest.permission.ACCESS_COARSE_LOCATION,
559            Manifest.permission.RECORD_AUDIO,
560            Manifest.permission.READ_PHONE_STATE,
561            Manifest.permission.CALL_PHONE,
562            Manifest.permission.READ_CALL_LOG,
563            Manifest.permission.WRITE_CALL_LOG,
564            Manifest.permission.ADD_VOICEMAIL,
565            Manifest.permission.USE_SIP,
566            Manifest.permission.PROCESS_OUTGOING_CALLS,
567            Manifest.permission.READ_CELL_BROADCASTS,
568            Manifest.permission.BODY_SENSORS,
569            Manifest.permission.SEND_SMS,
570            Manifest.permission.RECEIVE_SMS,
571            Manifest.permission.READ_SMS,
572            Manifest.permission.RECEIVE_WAP_PUSH,
573            Manifest.permission.RECEIVE_MMS,
574            Manifest.permission.READ_EXTERNAL_STORAGE,
575            Manifest.permission.WRITE_EXTERNAL_STORAGE,
576            Manifest.permission.READ_PHONE_NUMBER);
577
578
579    /**
580     * Version number for the package parser cache. Increment this whenever the format or
581     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
582     */
583    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
584
585    /**
586     * Whether the package parser cache is enabled.
587     */
588    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
589
590    final ServiceThread mHandlerThread;
591
592    final PackageHandler mHandler;
593
594    private final ProcessLoggingHandler mProcessLoggingHandler;
595
596    /**
597     * Messages for {@link #mHandler} that need to wait for system ready before
598     * being dispatched.
599     */
600    private ArrayList<Message> mPostSystemReadyMessages;
601
602    final int mSdkVersion = Build.VERSION.SDK_INT;
603
604    final Context mContext;
605    final boolean mFactoryTest;
606    final boolean mOnlyCore;
607    final DisplayMetrics mMetrics;
608    final int mDefParseFlags;
609    final String[] mSeparateProcesses;
610    final boolean mIsUpgrade;
611    final boolean mIsPreNUpgrade;
612    final boolean mIsPreNMR1Upgrade;
613
614    @GuardedBy("mPackages")
615    private boolean mDexOptDialogShown;
616
617    /** The location for ASEC container files on internal storage. */
618    final String mAsecInternalPath;
619
620    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
621    // LOCK HELD.  Can be called with mInstallLock held.
622    @GuardedBy("mInstallLock")
623    final Installer mInstaller;
624
625    /** Directory where installed third-party apps stored */
626    final File mAppInstallDir;
627    final File mEphemeralInstallDir;
628
629    /**
630     * Directory to which applications installed internally have their
631     * 32 bit native libraries copied.
632     */
633    private File mAppLib32InstallDir;
634
635    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
636    // apps.
637    final File mDrmAppPrivateInstallDir;
638
639    // ----------------------------------------------------------------
640
641    // Lock for state used when installing and doing other long running
642    // operations.  Methods that must be called with this lock held have
643    // the suffix "LI".
644    final Object mInstallLock = new Object();
645
646    // ----------------------------------------------------------------
647
648    // Keys are String (package name), values are Package.  This also serves
649    // as the lock for the global state.  Methods that must be called with
650    // this lock held have the prefix "LP".
651    @GuardedBy("mPackages")
652    final ArrayMap<String, PackageParser.Package> mPackages =
653            new ArrayMap<String, PackageParser.Package>();
654
655    final ArrayMap<String, Set<String>> mKnownCodebase =
656            new ArrayMap<String, Set<String>>();
657
658    // Tracks available target package names -> overlay package paths.
659    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
660        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
661
662    /**
663     * Tracks new system packages [received in an OTA] that we expect to
664     * find updated user-installed versions. Keys are package name, values
665     * are package location.
666     */
667    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
668    /**
669     * Tracks high priority intent filters for protected actions. During boot, certain
670     * filter actions are protected and should never be allowed to have a high priority
671     * intent filter for them. However, there is one, and only one exception -- the
672     * setup wizard. It must be able to define a high priority intent filter for these
673     * actions to ensure there are no escapes from the wizard. We need to delay processing
674     * of these during boot as we need to look at all of the system packages in order
675     * to know which component is the setup wizard.
676     */
677    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
678    /**
679     * Whether or not processing protected filters should be deferred.
680     */
681    private boolean mDeferProtectedFilters = true;
682
683    /**
684     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
685     */
686    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
687    /**
688     * Whether or not system app permissions should be promoted from install to runtime.
689     */
690    boolean mPromoteSystemApps;
691
692    @GuardedBy("mPackages")
693    final Settings mSettings;
694
695    /**
696     * Set of package names that are currently "frozen", which means active
697     * surgery is being done on the code/data for that package. The platform
698     * will refuse to launch frozen packages to avoid race conditions.
699     *
700     * @see PackageFreezer
701     */
702    @GuardedBy("mPackages")
703    final ArraySet<String> mFrozenPackages = new ArraySet<>();
704
705    final ProtectedPackages mProtectedPackages;
706
707    boolean mFirstBoot;
708
709    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
710
711    // System configuration read by SystemConfig.
712    final int[] mGlobalGids;
713    final SparseArray<ArraySet<String>> mSystemPermissions;
714    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
715
716    // If mac_permissions.xml was found for seinfo labeling.
717    boolean mFoundPolicyFile;
718
719    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
720
721    public static final class SharedLibraryEntry {
722        public final String path;
723        public final String apk;
724        public final SharedLibraryInfo info;
725
726        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
727                String declaringPackageName, int declaringPackageVersionCode) {
728            path = _path;
729            apk = _apk;
730            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
731                    declaringPackageName, declaringPackageVersionCode), null);
732        }
733    }
734
735    // Currently known shared libraries.
736    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
737    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
738            new ArrayMap<>();
739
740    // All available activities, for your resolving pleasure.
741    final ActivityIntentResolver mActivities =
742            new ActivityIntentResolver();
743
744    // All available receivers, for your resolving pleasure.
745    final ActivityIntentResolver mReceivers =
746            new ActivityIntentResolver();
747
748    // All available services, for your resolving pleasure.
749    final ServiceIntentResolver mServices = new ServiceIntentResolver();
750
751    // All available providers, for your resolving pleasure.
752    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
753
754    // Mapping from provider base names (first directory in content URI codePath)
755    // to the provider information.
756    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
757            new ArrayMap<String, PackageParser.Provider>();
758
759    // Mapping from instrumentation class names to info about them.
760    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
761            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
762
763    // Mapping from permission names to info about them.
764    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
765            new ArrayMap<String, PackageParser.PermissionGroup>();
766
767    // Packages whose data we have transfered into another package, thus
768    // should no longer exist.
769    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
770
771    // Broadcast actions that are only available to the system.
772    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
773
774    /** List of packages waiting for verification. */
775    final SparseArray<PackageVerificationState> mPendingVerification
776            = new SparseArray<PackageVerificationState>();
777
778    /** Set of packages associated with each app op permission. */
779    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
780
781    final PackageInstallerService mInstallerService;
782
783    private final PackageDexOptimizer mPackageDexOptimizer;
784    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
785    // is used by other apps).
786    private final DexManager mDexManager;
787
788    private AtomicInteger mNextMoveId = new AtomicInteger();
789    private final MoveCallbacks mMoveCallbacks;
790
791    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
792
793    // Cache of users who need badging.
794    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
795
796    /** Token for keys in mPendingVerification. */
797    private int mPendingVerificationToken = 0;
798
799    volatile boolean mSystemReady;
800    volatile boolean mSafeMode;
801    volatile boolean mHasSystemUidErrors;
802
803    ApplicationInfo mAndroidApplication;
804    final ActivityInfo mResolveActivity = new ActivityInfo();
805    final ResolveInfo mResolveInfo = new ResolveInfo();
806    ComponentName mResolveComponentName;
807    PackageParser.Package mPlatformPackage;
808    ComponentName mCustomResolverComponentName;
809
810    boolean mResolverReplaced = false;
811
812    private final @Nullable ComponentName mIntentFilterVerifierComponent;
813    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
814
815    private int mIntentFilterVerificationToken = 0;
816
817    /** The service connection to the ephemeral resolver */
818    final EphemeralResolverConnection mEphemeralResolverConnection;
819
820    /** Component used to install ephemeral applications */
821    ComponentName mEphemeralInstallerComponent;
822    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
823    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
824
825    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
826            = new SparseArray<IntentFilterVerificationState>();
827
828    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
829
830    // List of packages names to keep cached, even if they are uninstalled for all users
831    private List<String> mKeepUninstalledPackages;
832
833    private UserManagerInternal mUserManagerInternal;
834
835    private File mCacheDir;
836
837    private static class IFVerificationParams {
838        PackageParser.Package pkg;
839        boolean replacing;
840        int userId;
841        int verifierUid;
842
843        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
844                int _userId, int _verifierUid) {
845            pkg = _pkg;
846            replacing = _replacing;
847            userId = _userId;
848            replacing = _replacing;
849            verifierUid = _verifierUid;
850        }
851    }
852
853    private interface IntentFilterVerifier<T extends IntentFilter> {
854        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
855                                               T filter, String packageName);
856        void startVerifications(int userId);
857        void receiveVerificationResponse(int verificationId);
858    }
859
860    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
861        private Context mContext;
862        private ComponentName mIntentFilterVerifierComponent;
863        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
864
865        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
866            mContext = context;
867            mIntentFilterVerifierComponent = verifierComponent;
868        }
869
870        private String getDefaultScheme() {
871            return IntentFilter.SCHEME_HTTPS;
872        }
873
874        @Override
875        public void startVerifications(int userId) {
876            // Launch verifications requests
877            int count = mCurrentIntentFilterVerifications.size();
878            for (int n=0; n<count; n++) {
879                int verificationId = mCurrentIntentFilterVerifications.get(n);
880                final IntentFilterVerificationState ivs =
881                        mIntentFilterVerificationStates.get(verificationId);
882
883                String packageName = ivs.getPackageName();
884
885                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
886                final int filterCount = filters.size();
887                ArraySet<String> domainsSet = new ArraySet<>();
888                for (int m=0; m<filterCount; m++) {
889                    PackageParser.ActivityIntentInfo filter = filters.get(m);
890                    domainsSet.addAll(filter.getHostsList());
891                }
892                synchronized (mPackages) {
893                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
894                            packageName, domainsSet) != null) {
895                        scheduleWriteSettingsLocked();
896                    }
897                }
898                sendVerificationRequest(userId, verificationId, ivs);
899            }
900            mCurrentIntentFilterVerifications.clear();
901        }
902
903        private void sendVerificationRequest(int userId, int verificationId,
904                IntentFilterVerificationState ivs) {
905
906            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
907            verificationIntent.putExtra(
908                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
909                    verificationId);
910            verificationIntent.putExtra(
911                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
912                    getDefaultScheme());
913            verificationIntent.putExtra(
914                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
915                    ivs.getHostsString());
916            verificationIntent.putExtra(
917                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
918                    ivs.getPackageName());
919            verificationIntent.setComponent(mIntentFilterVerifierComponent);
920            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
921
922            UserHandle user = new UserHandle(userId);
923            mContext.sendBroadcastAsUser(verificationIntent, user);
924            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
925                    "Sending IntentFilter verification broadcast");
926        }
927
928        public void receiveVerificationResponse(int verificationId) {
929            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
930
931            final boolean verified = ivs.isVerified();
932
933            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
934            final int count = filters.size();
935            if (DEBUG_DOMAIN_VERIFICATION) {
936                Slog.i(TAG, "Received verification response " + verificationId
937                        + " for " + count + " filters, verified=" + verified);
938            }
939            for (int n=0; n<count; n++) {
940                PackageParser.ActivityIntentInfo filter = filters.get(n);
941                filter.setVerified(verified);
942
943                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
944                        + " verified with result:" + verified + " and hosts:"
945                        + ivs.getHostsString());
946            }
947
948            mIntentFilterVerificationStates.remove(verificationId);
949
950            final String packageName = ivs.getPackageName();
951            IntentFilterVerificationInfo ivi = null;
952
953            synchronized (mPackages) {
954                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
955            }
956            if (ivi == null) {
957                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
958                        + verificationId + " packageName:" + packageName);
959                return;
960            }
961            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
962                    "Updating IntentFilterVerificationInfo for package " + packageName
963                            +" verificationId:" + verificationId);
964
965            synchronized (mPackages) {
966                if (verified) {
967                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
968                } else {
969                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
970                }
971                scheduleWriteSettingsLocked();
972
973                final int userId = ivs.getUserId();
974                if (userId != UserHandle.USER_ALL) {
975                    final int userStatus =
976                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
977
978                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
979                    boolean needUpdate = false;
980
981                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
982                    // already been set by the User thru the Disambiguation dialog
983                    switch (userStatus) {
984                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
985                            if (verified) {
986                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
987                            } else {
988                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
989                            }
990                            needUpdate = true;
991                            break;
992
993                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
994                            if (verified) {
995                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
996                                needUpdate = true;
997                            }
998                            break;
999
1000                        default:
1001                            // Nothing to do
1002                    }
1003
1004                    if (needUpdate) {
1005                        mSettings.updateIntentFilterVerificationStatusLPw(
1006                                packageName, updatedStatus, userId);
1007                        scheduleWritePackageRestrictionsLocked(userId);
1008                    }
1009                }
1010            }
1011        }
1012
1013        @Override
1014        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1015                    ActivityIntentInfo filter, String packageName) {
1016            if (!hasValidDomains(filter)) {
1017                return false;
1018            }
1019            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1020            if (ivs == null) {
1021                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1022                        packageName);
1023            }
1024            if (DEBUG_DOMAIN_VERIFICATION) {
1025                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1026            }
1027            ivs.addFilter(filter);
1028            return true;
1029        }
1030
1031        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1032                int userId, int verificationId, String packageName) {
1033            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1034                    verifierUid, userId, packageName);
1035            ivs.setPendingState();
1036            synchronized (mPackages) {
1037                mIntentFilterVerificationStates.append(verificationId, ivs);
1038                mCurrentIntentFilterVerifications.add(verificationId);
1039            }
1040            return ivs;
1041        }
1042    }
1043
1044    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1045        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1046                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1047                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1048    }
1049
1050    // Set of pending broadcasts for aggregating enable/disable of components.
1051    static class PendingPackageBroadcasts {
1052        // for each user id, a map of <package name -> components within that package>
1053        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1054
1055        public PendingPackageBroadcasts() {
1056            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1057        }
1058
1059        public ArrayList<String> get(int userId, String packageName) {
1060            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1061            return packages.get(packageName);
1062        }
1063
1064        public void put(int userId, String packageName, ArrayList<String> components) {
1065            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1066            packages.put(packageName, components);
1067        }
1068
1069        public void remove(int userId, String packageName) {
1070            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1071            if (packages != null) {
1072                packages.remove(packageName);
1073            }
1074        }
1075
1076        public void remove(int userId) {
1077            mUidMap.remove(userId);
1078        }
1079
1080        public int userIdCount() {
1081            return mUidMap.size();
1082        }
1083
1084        public int userIdAt(int n) {
1085            return mUidMap.keyAt(n);
1086        }
1087
1088        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1089            return mUidMap.get(userId);
1090        }
1091
1092        public int size() {
1093            // total number of pending broadcast entries across all userIds
1094            int num = 0;
1095            for (int i = 0; i< mUidMap.size(); i++) {
1096                num += mUidMap.valueAt(i).size();
1097            }
1098            return num;
1099        }
1100
1101        public void clear() {
1102            mUidMap.clear();
1103        }
1104
1105        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1106            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1107            if (map == null) {
1108                map = new ArrayMap<String, ArrayList<String>>();
1109                mUidMap.put(userId, map);
1110            }
1111            return map;
1112        }
1113    }
1114    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1115
1116    // Service Connection to remote media container service to copy
1117    // package uri's from external media onto secure containers
1118    // or internal storage.
1119    private IMediaContainerService mContainerService = null;
1120
1121    static final int SEND_PENDING_BROADCAST = 1;
1122    static final int MCS_BOUND = 3;
1123    static final int END_COPY = 4;
1124    static final int INIT_COPY = 5;
1125    static final int MCS_UNBIND = 6;
1126    static final int START_CLEANING_PACKAGE = 7;
1127    static final int FIND_INSTALL_LOC = 8;
1128    static final int POST_INSTALL = 9;
1129    static final int MCS_RECONNECT = 10;
1130    static final int MCS_GIVE_UP = 11;
1131    static final int UPDATED_MEDIA_STATUS = 12;
1132    static final int WRITE_SETTINGS = 13;
1133    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1134    static final int PACKAGE_VERIFIED = 15;
1135    static final int CHECK_PENDING_VERIFICATION = 16;
1136    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1137    static final int INTENT_FILTER_VERIFIED = 18;
1138    static final int WRITE_PACKAGE_LIST = 19;
1139    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1140
1141    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1142
1143    // Delay time in millisecs
1144    static final int BROADCAST_DELAY = 10 * 1000;
1145
1146    static UserManagerService sUserManager;
1147
1148    // Stores a list of users whose package restrictions file needs to be updated
1149    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1150
1151    final private DefaultContainerConnection mDefContainerConn =
1152            new DefaultContainerConnection();
1153    class DefaultContainerConnection implements ServiceConnection {
1154        public void onServiceConnected(ComponentName name, IBinder service) {
1155            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1156            final IMediaContainerService imcs = IMediaContainerService.Stub
1157                    .asInterface(Binder.allowBlocking(service));
1158            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1159        }
1160
1161        public void onServiceDisconnected(ComponentName name) {
1162            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1163        }
1164    }
1165
1166    // Recordkeeping of restore-after-install operations that are currently in flight
1167    // between the Package Manager and the Backup Manager
1168    static class PostInstallData {
1169        public InstallArgs args;
1170        public PackageInstalledInfo res;
1171
1172        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1173            args = _a;
1174            res = _r;
1175        }
1176    }
1177
1178    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1179    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1180
1181    // XML tags for backup/restore of various bits of state
1182    private static final String TAG_PREFERRED_BACKUP = "pa";
1183    private static final String TAG_DEFAULT_APPS = "da";
1184    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1185
1186    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1187    private static final String TAG_ALL_GRANTS = "rt-grants";
1188    private static final String TAG_GRANT = "grant";
1189    private static final String ATTR_PACKAGE_NAME = "pkg";
1190
1191    private static final String TAG_PERMISSION = "perm";
1192    private static final String ATTR_PERMISSION_NAME = "name";
1193    private static final String ATTR_IS_GRANTED = "g";
1194    private static final String ATTR_USER_SET = "set";
1195    private static final String ATTR_USER_FIXED = "fixed";
1196    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1197
1198    // System/policy permission grants are not backed up
1199    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1200            FLAG_PERMISSION_POLICY_FIXED
1201            | FLAG_PERMISSION_SYSTEM_FIXED
1202            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1203
1204    // And we back up these user-adjusted states
1205    private static final int USER_RUNTIME_GRANT_MASK =
1206            FLAG_PERMISSION_USER_SET
1207            | FLAG_PERMISSION_USER_FIXED
1208            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1209
1210    final @Nullable String mRequiredVerifierPackage;
1211    final @NonNull String mRequiredInstallerPackage;
1212    final @NonNull String mRequiredUninstallerPackage;
1213    final @Nullable String mSetupWizardPackage;
1214    final @Nullable String mStorageManagerPackage;
1215    final @NonNull String mServicesSystemSharedLibraryPackageName;
1216    final @NonNull String mSharedSystemSharedLibraryPackageName;
1217
1218    final boolean mPermissionReviewRequired;
1219
1220    private final PackageUsage mPackageUsage = new PackageUsage();
1221    private final CompilerStats mCompilerStats = new CompilerStats();
1222
1223    class PackageHandler extends Handler {
1224        private boolean mBound = false;
1225        final ArrayList<HandlerParams> mPendingInstalls =
1226            new ArrayList<HandlerParams>();
1227
1228        private boolean connectToService() {
1229            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1230                    " DefaultContainerService");
1231            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1232            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1233            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1234                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1235                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1236                mBound = true;
1237                return true;
1238            }
1239            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1240            return false;
1241        }
1242
1243        private void disconnectService() {
1244            mContainerService = null;
1245            mBound = false;
1246            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1247            mContext.unbindService(mDefContainerConn);
1248            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1249        }
1250
1251        PackageHandler(Looper looper) {
1252            super(looper);
1253        }
1254
1255        public void handleMessage(Message msg) {
1256            try {
1257                doHandleMessage(msg);
1258            } finally {
1259                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1260            }
1261        }
1262
1263        void doHandleMessage(Message msg) {
1264            switch (msg.what) {
1265                case INIT_COPY: {
1266                    HandlerParams params = (HandlerParams) msg.obj;
1267                    int idx = mPendingInstalls.size();
1268                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1269                    // If a bind was already initiated we dont really
1270                    // need to do anything. The pending install
1271                    // will be processed later on.
1272                    if (!mBound) {
1273                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1274                                System.identityHashCode(mHandler));
1275                        // If this is the only one pending we might
1276                        // have to bind to the service again.
1277                        if (!connectToService()) {
1278                            Slog.e(TAG, "Failed to bind to media container service");
1279                            params.serviceError();
1280                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1281                                    System.identityHashCode(mHandler));
1282                            if (params.traceMethod != null) {
1283                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1284                                        params.traceCookie);
1285                            }
1286                            return;
1287                        } else {
1288                            // Once we bind to the service, the first
1289                            // pending request will be processed.
1290                            mPendingInstalls.add(idx, params);
1291                        }
1292                    } else {
1293                        mPendingInstalls.add(idx, params);
1294                        // Already bound to the service. Just make
1295                        // sure we trigger off processing the first request.
1296                        if (idx == 0) {
1297                            mHandler.sendEmptyMessage(MCS_BOUND);
1298                        }
1299                    }
1300                    break;
1301                }
1302                case MCS_BOUND: {
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1304                    if (msg.obj != null) {
1305                        mContainerService = (IMediaContainerService) msg.obj;
1306                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1307                                System.identityHashCode(mHandler));
1308                    }
1309                    if (mContainerService == null) {
1310                        if (!mBound) {
1311                            // Something seriously wrong since we are not bound and we are not
1312                            // waiting for connection. Bail out.
1313                            Slog.e(TAG, "Cannot bind to media container service");
1314                            for (HandlerParams params : mPendingInstalls) {
1315                                // Indicate service bind error
1316                                params.serviceError();
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1318                                        System.identityHashCode(params));
1319                                if (params.traceMethod != null) {
1320                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1321                                            params.traceMethod, params.traceCookie);
1322                                }
1323                                return;
1324                            }
1325                            mPendingInstalls.clear();
1326                        } else {
1327                            Slog.w(TAG, "Waiting to connect to media container service");
1328                        }
1329                    } else if (mPendingInstalls.size() > 0) {
1330                        HandlerParams params = mPendingInstalls.get(0);
1331                        if (params != null) {
1332                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1333                                    System.identityHashCode(params));
1334                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1335                            if (params.startCopy()) {
1336                                // We are done...  look for more work or to
1337                                // go idle.
1338                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1339                                        "Checking for more work or unbind...");
1340                                // Delete pending install
1341                                if (mPendingInstalls.size() > 0) {
1342                                    mPendingInstalls.remove(0);
1343                                }
1344                                if (mPendingInstalls.size() == 0) {
1345                                    if (mBound) {
1346                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1347                                                "Posting delayed MCS_UNBIND");
1348                                        removeMessages(MCS_UNBIND);
1349                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1350                                        // Unbind after a little delay, to avoid
1351                                        // continual thrashing.
1352                                        sendMessageDelayed(ubmsg, 10000);
1353                                    }
1354                                } else {
1355                                    // There are more pending requests in queue.
1356                                    // Just post MCS_BOUND message to trigger processing
1357                                    // of next pending install.
1358                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1359                                            "Posting MCS_BOUND for next work");
1360                                    mHandler.sendEmptyMessage(MCS_BOUND);
1361                                }
1362                            }
1363                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1364                        }
1365                    } else {
1366                        // Should never happen ideally.
1367                        Slog.w(TAG, "Empty queue");
1368                    }
1369                    break;
1370                }
1371                case MCS_RECONNECT: {
1372                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1373                    if (mPendingInstalls.size() > 0) {
1374                        if (mBound) {
1375                            disconnectService();
1376                        }
1377                        if (!connectToService()) {
1378                            Slog.e(TAG, "Failed to bind to media container service");
1379                            for (HandlerParams params : mPendingInstalls) {
1380                                // Indicate service bind error
1381                                params.serviceError();
1382                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1383                                        System.identityHashCode(params));
1384                            }
1385                            mPendingInstalls.clear();
1386                        }
1387                    }
1388                    break;
1389                }
1390                case MCS_UNBIND: {
1391                    // If there is no actual work left, then time to unbind.
1392                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1393
1394                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1395                        if (mBound) {
1396                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1397
1398                            disconnectService();
1399                        }
1400                    } else if (mPendingInstalls.size() > 0) {
1401                        // There are more pending requests in queue.
1402                        // Just post MCS_BOUND message to trigger processing
1403                        // of next pending install.
1404                        mHandler.sendEmptyMessage(MCS_BOUND);
1405                    }
1406
1407                    break;
1408                }
1409                case MCS_GIVE_UP: {
1410                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1411                    HandlerParams params = mPendingInstalls.remove(0);
1412                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1413                            System.identityHashCode(params));
1414                    break;
1415                }
1416                case SEND_PENDING_BROADCAST: {
1417                    String packages[];
1418                    ArrayList<String> components[];
1419                    int size = 0;
1420                    int uids[];
1421                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422                    synchronized (mPackages) {
1423                        if (mPendingBroadcasts == null) {
1424                            return;
1425                        }
1426                        size = mPendingBroadcasts.size();
1427                        if (size <= 0) {
1428                            // Nothing to be done. Just return
1429                            return;
1430                        }
1431                        packages = new String[size];
1432                        components = new ArrayList[size];
1433                        uids = new int[size];
1434                        int i = 0;  // filling out the above arrays
1435
1436                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1437                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1438                            Iterator<Map.Entry<String, ArrayList<String>>> it
1439                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1440                                            .entrySet().iterator();
1441                            while (it.hasNext() && i < size) {
1442                                Map.Entry<String, ArrayList<String>> ent = it.next();
1443                                packages[i] = ent.getKey();
1444                                components[i] = ent.getValue();
1445                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1446                                uids[i] = (ps != null)
1447                                        ? UserHandle.getUid(packageUserId, ps.appId)
1448                                        : -1;
1449                                i++;
1450                            }
1451                        }
1452                        size = i;
1453                        mPendingBroadcasts.clear();
1454                    }
1455                    // Send broadcasts
1456                    for (int i = 0; i < size; i++) {
1457                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1458                    }
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1460                    break;
1461                }
1462                case START_CLEANING_PACKAGE: {
1463                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1464                    final String packageName = (String)msg.obj;
1465                    final int userId = msg.arg1;
1466                    final boolean andCode = msg.arg2 != 0;
1467                    synchronized (mPackages) {
1468                        if (userId == UserHandle.USER_ALL) {
1469                            int[] users = sUserManager.getUserIds();
1470                            for (int user : users) {
1471                                mSettings.addPackageToCleanLPw(
1472                                        new PackageCleanItem(user, packageName, andCode));
1473                            }
1474                        } else {
1475                            mSettings.addPackageToCleanLPw(
1476                                    new PackageCleanItem(userId, packageName, andCode));
1477                        }
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                    startCleaningPackages();
1481                } break;
1482                case POST_INSTALL: {
1483                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1484
1485                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1486                    final boolean didRestore = (msg.arg2 != 0);
1487                    mRunningInstalls.delete(msg.arg1);
1488
1489                    if (data != null) {
1490                        InstallArgs args = data.args;
1491                        PackageInstalledInfo parentRes = data.res;
1492
1493                        final boolean grantPermissions = (args.installFlags
1494                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1495                        final boolean killApp = (args.installFlags
1496                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1497                        final String[] grantedPermissions = args.installGrantPermissions;
1498
1499                        // Handle the parent package
1500                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1501                                grantedPermissions, didRestore, args.installerPackageName,
1502                                args.observer);
1503
1504                        // Handle the child packages
1505                        final int childCount = (parentRes.addedChildPackages != null)
1506                                ? parentRes.addedChildPackages.size() : 0;
1507                        for (int i = 0; i < childCount; i++) {
1508                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1509                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1510                                    grantedPermissions, false, args.installerPackageName,
1511                                    args.observer);
1512                        }
1513
1514                        // Log tracing if needed
1515                        if (args.traceMethod != null) {
1516                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1517                                    args.traceCookie);
1518                        }
1519                    } else {
1520                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1521                    }
1522
1523                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1524                } break;
1525                case UPDATED_MEDIA_STATUS: {
1526                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1527                    boolean reportStatus = msg.arg1 == 1;
1528                    boolean doGc = msg.arg2 == 1;
1529                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1530                    if (doGc) {
1531                        // Force a gc to clear up stale containers.
1532                        Runtime.getRuntime().gc();
1533                    }
1534                    if (msg.obj != null) {
1535                        @SuppressWarnings("unchecked")
1536                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1537                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1538                        // Unload containers
1539                        unloadAllContainers(args);
1540                    }
1541                    if (reportStatus) {
1542                        try {
1543                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                    "Invoking StorageManagerService call back");
1545                            PackageHelper.getStorageManager().finishMediaUpdate();
1546                        } catch (RemoteException e) {
1547                            Log.e(TAG, "StorageManagerService not running?");
1548                        }
1549                    }
1550                } break;
1551                case WRITE_SETTINGS: {
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1553                    synchronized (mPackages) {
1554                        removeMessages(WRITE_SETTINGS);
1555                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1556                        mSettings.writeLPr();
1557                        mDirtyUsers.clear();
1558                    }
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1560                } break;
1561                case WRITE_PACKAGE_RESTRICTIONS: {
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1563                    synchronized (mPackages) {
1564                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1565                        for (int userId : mDirtyUsers) {
1566                            mSettings.writePackageRestrictionsLPr(userId);
1567                        }
1568                        mDirtyUsers.clear();
1569                    }
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1571                } break;
1572                case WRITE_PACKAGE_LIST: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        removeMessages(WRITE_PACKAGE_LIST);
1576                        mSettings.writePackageListLPr(msg.arg1);
1577                    }
1578                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1579                } break;
1580                case CHECK_PENDING_VERIFICATION: {
1581                    final int verificationId = msg.arg1;
1582                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1583
1584                    if ((state != null) && !state.timeoutExtended()) {
1585                        final InstallArgs args = state.getInstallArgs();
1586                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1587
1588                        Slog.i(TAG, "Verification timed out for " + originUri);
1589                        mPendingVerification.remove(verificationId);
1590
1591                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1592
1593                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1594                            Slog.i(TAG, "Continuing with installation of " + originUri);
1595                            state.setVerifierResponse(Binder.getCallingUid(),
1596                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1597                            broadcastPackageVerified(verificationId, originUri,
1598                                    PackageManager.VERIFICATION_ALLOW,
1599                                    state.getInstallArgs().getUser());
1600                            try {
1601                                ret = args.copyApk(mContainerService, true);
1602                            } catch (RemoteException e) {
1603                                Slog.e(TAG, "Could not contact the ContainerService");
1604                            }
1605                        } else {
1606                            broadcastPackageVerified(verificationId, originUri,
1607                                    PackageManager.VERIFICATION_REJECT,
1608                                    state.getInstallArgs().getUser());
1609                        }
1610
1611                        Trace.asyncTraceEnd(
1612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613
1614                        processPendingInstall(args, ret);
1615                        mHandler.sendEmptyMessage(MCS_UNBIND);
1616                    }
1617                    break;
1618                }
1619                case PACKAGE_VERIFIED: {
1620                    final int verificationId = msg.arg1;
1621
1622                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1623                    if (state == null) {
1624                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1625                        break;
1626                    }
1627
1628                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1629
1630                    state.setVerifierResponse(response.callerUid, response.code);
1631
1632                    if (state.isVerificationComplete()) {
1633                        mPendingVerification.remove(verificationId);
1634
1635                        final InstallArgs args = state.getInstallArgs();
1636                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1637
1638                        int ret;
1639                        if (state.isInstallAllowed()) {
1640                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1641                            broadcastPackageVerified(verificationId, originUri,
1642                                    response.code, state.getInstallArgs().getUser());
1643                            try {
1644                                ret = args.copyApk(mContainerService, true);
1645                            } catch (RemoteException e) {
1646                                Slog.e(TAG, "Could not contact the ContainerService");
1647                            }
1648                        } else {
1649                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1650                        }
1651
1652                        Trace.asyncTraceEnd(
1653                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1654
1655                        processPendingInstall(args, ret);
1656                        mHandler.sendEmptyMessage(MCS_UNBIND);
1657                    }
1658
1659                    break;
1660                }
1661                case START_INTENT_FILTER_VERIFICATIONS: {
1662                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1663                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1664                            params.replacing, params.pkg);
1665                    break;
1666                }
1667                case INTENT_FILTER_VERIFIED: {
1668                    final int verificationId = msg.arg1;
1669
1670                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1671                            verificationId);
1672                    if (state == null) {
1673                        Slog.w(TAG, "Invalid IntentFilter verification token "
1674                                + verificationId + " received");
1675                        break;
1676                    }
1677
1678                    final int userId = state.getUserId();
1679
1680                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1681                            "Processing IntentFilter verification with token:"
1682                            + verificationId + " and userId:" + userId);
1683
1684                    final IntentFilterVerificationResponse response =
1685                            (IntentFilterVerificationResponse) msg.obj;
1686
1687                    state.setVerifierResponse(response.callerUid, response.code);
1688
1689                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1690                            "IntentFilter verification with token:" + verificationId
1691                            + " and userId:" + userId
1692                            + " is settings verifier response with response code:"
1693                            + response.code);
1694
1695                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1696                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1697                                + response.getFailedDomainsString());
1698                    }
1699
1700                    if (state.isVerificationComplete()) {
1701                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1702                    } else {
1703                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1704                                "IntentFilter verification with token:" + verificationId
1705                                + " was not said to be complete");
1706                    }
1707
1708                    break;
1709                }
1710                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1711                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1712                            mEphemeralResolverConnection,
1713                            (EphemeralRequest) msg.obj,
1714                            mEphemeralInstallerActivity,
1715                            mHandler);
1716                }
1717            }
1718        }
1719    }
1720
1721    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1722            boolean killApp, String[] grantedPermissions,
1723            boolean launchedForRestore, String installerPackage,
1724            IPackageInstallObserver2 installObserver) {
1725        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1726            // Send the removed broadcasts
1727            if (res.removedInfo != null) {
1728                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1729            }
1730
1731            // Now that we successfully installed the package, grant runtime
1732            // permissions if requested before broadcasting the install. Also
1733            // for legacy apps in permission review mode we clear the permission
1734            // review flag which is used to emulate runtime permissions for
1735            // legacy apps.
1736            if (grantPermissions) {
1737                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1738            }
1739
1740            final boolean update = res.removedInfo != null
1741                    && res.removedInfo.removedPackage != null;
1742
1743            // If this is the first time we have child packages for a disabled privileged
1744            // app that had no children, we grant requested runtime permissions to the new
1745            // children if the parent on the system image had them already granted.
1746            if (res.pkg.parentPackage != null) {
1747                synchronized (mPackages) {
1748                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1749                }
1750            }
1751
1752            synchronized (mPackages) {
1753                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1754            }
1755
1756            final String packageName = res.pkg.applicationInfo.packageName;
1757
1758            // Determine the set of users who are adding this package for
1759            // the first time vs. those who are seeing an update.
1760            int[] firstUsers = EMPTY_INT_ARRAY;
1761            int[] updateUsers = EMPTY_INT_ARRAY;
1762            if (res.origUsers == null || res.origUsers.length == 0) {
1763                firstUsers = res.newUsers;
1764            } else {
1765                for (int newUser : res.newUsers) {
1766                    boolean isNew = true;
1767                    for (int origUser : res.origUsers) {
1768                        if (origUser == newUser) {
1769                            isNew = false;
1770                            break;
1771                        }
1772                    }
1773                    if (isNew) {
1774                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1775                    } else {
1776                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1777                    }
1778                }
1779            }
1780
1781            // Send installed broadcasts if the install/update is not ephemeral
1782            // and the package is not a static shared lib.
1783            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1784                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1785
1786                // Send added for users that see the package for the first time
1787                // sendPackageAddedForNewUsers also deals with system apps
1788                int appId = UserHandle.getAppId(res.uid);
1789                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1790                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1791
1792                // Send added for users that don't see the package for the first time
1793                Bundle extras = new Bundle(1);
1794                extras.putInt(Intent.EXTRA_UID, res.uid);
1795                if (update) {
1796                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1797                }
1798                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1799                        extras, 0 /*flags*/, null /*targetPackage*/,
1800                        null /*finishedReceiver*/, updateUsers);
1801
1802                // Send replaced for users that don't see the package for the first time
1803                if (update) {
1804                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1805                            packageName, extras, 0 /*flags*/,
1806                            null /*targetPackage*/, null /*finishedReceiver*/,
1807                            updateUsers);
1808                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1809                            null /*package*/, null /*extras*/, 0 /*flags*/,
1810                            packageName /*targetPackage*/,
1811                            null /*finishedReceiver*/, updateUsers);
1812                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1813                    // First-install and we did a restore, so we're responsible for the
1814                    // first-launch broadcast.
1815                    if (DEBUG_BACKUP) {
1816                        Slog.i(TAG, "Post-restore of " + packageName
1817                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1818                    }
1819                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1820                }
1821
1822                // Send broadcast package appeared if forward locked/external for all users
1823                // treat asec-hosted packages like removable media on upgrade
1824                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1825                    if (DEBUG_INSTALL) {
1826                        Slog.i(TAG, "upgrading pkg " + res.pkg
1827                                + " is ASEC-hosted -> AVAILABLE");
1828                    }
1829                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1830                    ArrayList<String> pkgList = new ArrayList<>(1);
1831                    pkgList.add(packageName);
1832                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1833                }
1834            }
1835
1836            // Work that needs to happen on first install within each user
1837            if (firstUsers != null && firstUsers.length > 0) {
1838                synchronized (mPackages) {
1839                    for (int userId : firstUsers) {
1840                        // If this app is a browser and it's newly-installed for some
1841                        // users, clear any default-browser state in those users. The
1842                        // app's nature doesn't depend on the user, so we can just check
1843                        // its browser nature in any user and generalize.
1844                        if (packageIsBrowser(packageName, userId)) {
1845                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1846                        }
1847
1848                        // We may also need to apply pending (restored) runtime
1849                        // permission grants within these users.
1850                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1851                    }
1852                }
1853            }
1854
1855            // Log current value of "unknown sources" setting
1856            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1857                    getUnknownSourcesSettings());
1858
1859            // Force a gc to clear up things
1860            Runtime.getRuntime().gc();
1861
1862            // Remove the replaced package's older resources safely now
1863            // We delete after a gc for applications  on sdcard.
1864            if (res.removedInfo != null && res.removedInfo.args != null) {
1865                synchronized (mInstallLock) {
1866                    res.removedInfo.args.doPostDeleteLI(true);
1867                }
1868            }
1869
1870            if (!isEphemeral(res.pkg)) {
1871                // Notify DexManager that the package was installed for new users.
1872                // The updated users should already be indexed and the package code paths
1873                // should not change.
1874                // Don't notify the manager for ephemeral apps as they are not expected to
1875                // survive long enough to benefit of background optimizations.
1876                for (int userId : firstUsers) {
1877                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1878                    mDexManager.notifyPackageInstalled(info, userId);
1879                }
1880            }
1881        }
1882
1883        // If someone is watching installs - notify them
1884        if (installObserver != null) {
1885            try {
1886                Bundle extras = extrasForInstallResult(res);
1887                installObserver.onPackageInstalled(res.name, res.returnCode,
1888                        res.returnMsg, extras);
1889            } catch (RemoteException e) {
1890                Slog.i(TAG, "Observer no longer exists.");
1891            }
1892        }
1893    }
1894
1895    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1896            PackageParser.Package pkg) {
1897        if (pkg.parentPackage == null) {
1898            return;
1899        }
1900        if (pkg.requestedPermissions == null) {
1901            return;
1902        }
1903        final PackageSetting disabledSysParentPs = mSettings
1904                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1905        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1906                || !disabledSysParentPs.isPrivileged()
1907                || (disabledSysParentPs.childPackageNames != null
1908                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1909            return;
1910        }
1911        final int[] allUserIds = sUserManager.getUserIds();
1912        final int permCount = pkg.requestedPermissions.size();
1913        for (int i = 0; i < permCount; i++) {
1914            String permission = pkg.requestedPermissions.get(i);
1915            BasePermission bp = mSettings.mPermissions.get(permission);
1916            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1917                continue;
1918            }
1919            for (int userId : allUserIds) {
1920                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1921                        permission, userId)) {
1922                    grantRuntimePermission(pkg.packageName, permission, userId);
1923                }
1924            }
1925        }
1926    }
1927
1928    private StorageEventListener mStorageListener = new StorageEventListener() {
1929        @Override
1930        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1931            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1932                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1933                    final String volumeUuid = vol.getFsUuid();
1934
1935                    // Clean up any users or apps that were removed or recreated
1936                    // while this volume was missing
1937                    reconcileUsers(volumeUuid);
1938                    reconcileApps(volumeUuid);
1939
1940                    // Clean up any install sessions that expired or were
1941                    // cancelled while this volume was missing
1942                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1943
1944                    loadPrivatePackages(vol);
1945
1946                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1947                    unloadPrivatePackages(vol);
1948                }
1949            }
1950
1951            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1952                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1953                    updateExternalMediaStatus(true, false);
1954                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1955                    updateExternalMediaStatus(false, false);
1956                }
1957            }
1958        }
1959
1960        @Override
1961        public void onVolumeForgotten(String fsUuid) {
1962            if (TextUtils.isEmpty(fsUuid)) {
1963                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1964                return;
1965            }
1966
1967            // Remove any apps installed on the forgotten volume
1968            synchronized (mPackages) {
1969                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1970                for (PackageSetting ps : packages) {
1971                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1972                    deletePackageVersioned(new VersionedPackage(ps.name,
1973                            PackageManager.VERSION_CODE_HIGHEST),
1974                            new LegacyPackageDeleteObserver(null).getBinder(),
1975                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1976                    // Try very hard to release any references to this package
1977                    // so we don't risk the system server being killed due to
1978                    // open FDs
1979                    AttributeCache.instance().removePackage(ps.name);
1980                }
1981
1982                mSettings.onVolumeForgotten(fsUuid);
1983                mSettings.writeLPr();
1984            }
1985        }
1986    };
1987
1988    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1989            String[] grantedPermissions) {
1990        for (int userId : userIds) {
1991            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1992        }
1993    }
1994
1995    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1996            String[] grantedPermissions) {
1997        SettingBase sb = (SettingBase) pkg.mExtras;
1998        if (sb == null) {
1999            return;
2000        }
2001
2002        PermissionsState permissionsState = sb.getPermissionsState();
2003
2004        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2005                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2006
2007        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2008                >= Build.VERSION_CODES.M;
2009
2010        for (String permission : pkg.requestedPermissions) {
2011            final BasePermission bp;
2012            synchronized (mPackages) {
2013                bp = mSettings.mPermissions.get(permission);
2014            }
2015            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2016                    && (grantedPermissions == null
2017                           || ArrayUtils.contains(grantedPermissions, permission))) {
2018                final int flags = permissionsState.getPermissionFlags(permission, userId);
2019                if (supportsRuntimePermissions) {
2020                    // Installer cannot change immutable permissions.
2021                    if ((flags & immutableFlags) == 0) {
2022                        grantRuntimePermission(pkg.packageName, permission, userId);
2023                    }
2024                } else if (mPermissionReviewRequired) {
2025                    // In permission review mode we clear the review flag when we
2026                    // are asked to install the app with all permissions granted.
2027                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2028                        updatePermissionFlags(permission, pkg.packageName,
2029                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2030                    }
2031                }
2032            }
2033        }
2034    }
2035
2036    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2037        Bundle extras = null;
2038        switch (res.returnCode) {
2039            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2040                extras = new Bundle();
2041                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2042                        res.origPermission);
2043                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2044                        res.origPackage);
2045                break;
2046            }
2047            case PackageManager.INSTALL_SUCCEEDED: {
2048                extras = new Bundle();
2049                extras.putBoolean(Intent.EXTRA_REPLACING,
2050                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2051                break;
2052            }
2053        }
2054        return extras;
2055    }
2056
2057    void scheduleWriteSettingsLocked() {
2058        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2059            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2060        }
2061    }
2062
2063    void scheduleWritePackageListLocked(int userId) {
2064        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2065            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2066            msg.arg1 = userId;
2067            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2068        }
2069    }
2070
2071    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2072        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2073        scheduleWritePackageRestrictionsLocked(userId);
2074    }
2075
2076    void scheduleWritePackageRestrictionsLocked(int userId) {
2077        final int[] userIds = (userId == UserHandle.USER_ALL)
2078                ? sUserManager.getUserIds() : new int[]{userId};
2079        for (int nextUserId : userIds) {
2080            if (!sUserManager.exists(nextUserId)) return;
2081            mDirtyUsers.add(nextUserId);
2082            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2083                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2084            }
2085        }
2086    }
2087
2088    public static PackageManagerService main(Context context, Installer installer,
2089            boolean factoryTest, boolean onlyCore) {
2090        // Self-check for initial settings.
2091        PackageManagerServiceCompilerMapping.checkProperties();
2092
2093        PackageManagerService m = new PackageManagerService(context, installer,
2094                factoryTest, onlyCore);
2095        m.enableSystemUserPackages();
2096        ServiceManager.addService("package", m);
2097        return m;
2098    }
2099
2100    private void enableSystemUserPackages() {
2101        if (!UserManager.isSplitSystemUser()) {
2102            return;
2103        }
2104        // For system user, enable apps based on the following conditions:
2105        // - app is whitelisted or belong to one of these groups:
2106        //   -- system app which has no launcher icons
2107        //   -- system app which has INTERACT_ACROSS_USERS permission
2108        //   -- system IME app
2109        // - app is not in the blacklist
2110        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2111        Set<String> enableApps = new ArraySet<>();
2112        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2113                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2114                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2115        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2116        enableApps.addAll(wlApps);
2117        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2118                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2119        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2120        enableApps.removeAll(blApps);
2121        Log.i(TAG, "Applications installed for system user: " + enableApps);
2122        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2123                UserHandle.SYSTEM);
2124        final int allAppsSize = allAps.size();
2125        synchronized (mPackages) {
2126            for (int i = 0; i < allAppsSize; i++) {
2127                String pName = allAps.get(i);
2128                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2129                // Should not happen, but we shouldn't be failing if it does
2130                if (pkgSetting == null) {
2131                    continue;
2132                }
2133                boolean install = enableApps.contains(pName);
2134                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2135                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2136                            + " for system user");
2137                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2138                }
2139            }
2140        }
2141    }
2142
2143    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2144        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2145                Context.DISPLAY_SERVICE);
2146        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2147    }
2148
2149    /**
2150     * Requests that files preopted on a secondary system partition be copied to the data partition
2151     * if possible.  Note that the actual copying of the files is accomplished by init for security
2152     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2153     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2154     */
2155    private static void requestCopyPreoptedFiles() {
2156        final int WAIT_TIME_MS = 100;
2157        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2158        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2159            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2160            // We will wait for up to 100 seconds.
2161            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2162            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2163                try {
2164                    Thread.sleep(WAIT_TIME_MS);
2165                } catch (InterruptedException e) {
2166                    // Do nothing
2167                }
2168                if (SystemClock.uptimeMillis() > timeEnd) {
2169                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2170                    Slog.wtf(TAG, "cppreopt did not finish!");
2171                    break;
2172                }
2173            }
2174        }
2175    }
2176
2177    public PackageManagerService(Context context, Installer installer,
2178            boolean factoryTest, boolean onlyCore) {
2179        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2180        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2181                SystemClock.uptimeMillis());
2182
2183        if (mSdkVersion <= 0) {
2184            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2185        }
2186
2187        mContext = context;
2188
2189        mPermissionReviewRequired = context.getResources().getBoolean(
2190                R.bool.config_permissionReviewRequired);
2191
2192        mFactoryTest = factoryTest;
2193        mOnlyCore = onlyCore;
2194        mMetrics = new DisplayMetrics();
2195        mSettings = new Settings(mPackages);
2196        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2197                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2198        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2199                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2200        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2201                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2202        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2203                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2204        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2205                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2206        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2207                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2208
2209        String separateProcesses = SystemProperties.get("debug.separate_processes");
2210        if (separateProcesses != null && separateProcesses.length() > 0) {
2211            if ("*".equals(separateProcesses)) {
2212                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2213                mSeparateProcesses = null;
2214                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2215            } else {
2216                mDefParseFlags = 0;
2217                mSeparateProcesses = separateProcesses.split(",");
2218                Slog.w(TAG, "Running with debug.separate_processes: "
2219                        + separateProcesses);
2220            }
2221        } else {
2222            mDefParseFlags = 0;
2223            mSeparateProcesses = null;
2224        }
2225
2226        mInstaller = installer;
2227        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2228                "*dexopt*");
2229        mDexManager = new DexManager();
2230        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2231
2232        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2233                FgThread.get().getLooper());
2234
2235        getDefaultDisplayMetrics(context, mMetrics);
2236
2237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2238        SystemConfig systemConfig = SystemConfig.getInstance();
2239        mGlobalGids = systemConfig.getGlobalGids();
2240        mSystemPermissions = systemConfig.getSystemPermissions();
2241        mAvailableFeatures = systemConfig.getAvailableFeatures();
2242        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2243
2244        mProtectedPackages = new ProtectedPackages(mContext);
2245
2246        synchronized (mInstallLock) {
2247        // writer
2248        synchronized (mPackages) {
2249            mHandlerThread = new ServiceThread(TAG,
2250                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2251            mHandlerThread.start();
2252            mHandler = new PackageHandler(mHandlerThread.getLooper());
2253            mProcessLoggingHandler = new ProcessLoggingHandler();
2254            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2255
2256            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2257            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2258
2259            File dataDir = Environment.getDataDirectory();
2260            mAppInstallDir = new File(dataDir, "app");
2261            mAppLib32InstallDir = new File(dataDir, "app-lib");
2262            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2263            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2264            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2265
2266            sUserManager = new UserManagerService(context, this, mPackages);
2267
2268            // Propagate permission configuration in to package manager.
2269            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2270                    = systemConfig.getPermissions();
2271            for (int i=0; i<permConfig.size(); i++) {
2272                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2273                BasePermission bp = mSettings.mPermissions.get(perm.name);
2274                if (bp == null) {
2275                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2276                    mSettings.mPermissions.put(perm.name, bp);
2277                }
2278                if (perm.gids != null) {
2279                    bp.setGids(perm.gids, perm.perUser);
2280                }
2281            }
2282
2283            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2284            final int builtInLibCount = libConfig.size();
2285            for (int i = 0; i < builtInLibCount; i++) {
2286                String name = libConfig.keyAt(i);
2287                String path = libConfig.valueAt(i);
2288                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2289                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2290            }
2291
2292            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2293
2294            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2295            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2296            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2297
2298            // Clean up orphaned packages for which the code path doesn't exist
2299            // and they are an update to a system app - caused by bug/32321269
2300            final int packageSettingCount = mSettings.mPackages.size();
2301            for (int i = packageSettingCount - 1; i >= 0; i--) {
2302                PackageSetting ps = mSettings.mPackages.valueAt(i);
2303                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2304                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2305                    mSettings.mPackages.removeAt(i);
2306                    mSettings.enableSystemPackageLPw(ps.name);
2307                }
2308            }
2309
2310            if (mFirstBoot) {
2311                requestCopyPreoptedFiles();
2312            }
2313
2314            String customResolverActivity = Resources.getSystem().getString(
2315                    R.string.config_customResolverActivity);
2316            if (TextUtils.isEmpty(customResolverActivity)) {
2317                customResolverActivity = null;
2318            } else {
2319                mCustomResolverComponentName = ComponentName.unflattenFromString(
2320                        customResolverActivity);
2321            }
2322
2323            long startTime = SystemClock.uptimeMillis();
2324
2325            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2326                    startTime);
2327
2328            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2329            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2330
2331            if (bootClassPath == null) {
2332                Slog.w(TAG, "No BOOTCLASSPATH found!");
2333            }
2334
2335            if (systemServerClassPath == null) {
2336                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2337            }
2338
2339            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2340            final String[] dexCodeInstructionSets =
2341                    getDexCodeInstructionSets(
2342                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2343
2344            /**
2345             * Ensure all external libraries have had dexopt run on them.
2346             */
2347            if (mSharedLibraries.size() > 0) {
2348                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2349                // NOTE: For now, we're compiling these system "shared libraries"
2350                // (and framework jars) into all available architectures. It's possible
2351                // to compile them only when we come across an app that uses them (there's
2352                // already logic for that in scanPackageLI) but that adds some complexity.
2353                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2354                    final int libCount = mSharedLibraries.size();
2355                    for (int i = 0; i < libCount; i++) {
2356                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2357                        final int versionCount = versionedLib.size();
2358                        for (int j = 0; j < versionCount; j++) {
2359                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2360                            final String libPath = libEntry.path != null
2361                                    ? libEntry.path : libEntry.apk;
2362                            if (libPath == null) {
2363                                continue;
2364                            }
2365                            try {
2366                                // Shared libraries do not have profiles so we perform a full
2367                                // AOT compilation (if needed).
2368                                int dexoptNeeded = DexFile.getDexOptNeeded(
2369                                        libPath, dexCodeInstructionSet,
2370                                        getCompilerFilterForReason(REASON_SHARED_APK),
2371                                        false /* newProfile */);
2372                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2373                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2374                                            dexCodeInstructionSet, dexoptNeeded, null,
2375                                            DEXOPT_PUBLIC,
2376                                            getCompilerFilterForReason(REASON_SHARED_APK),
2377                                            StorageManager.UUID_PRIVATE_INTERNAL,
2378                                            SKIP_SHARED_LIBRARY_CHECK);
2379                                }
2380                            } catch (FileNotFoundException e) {
2381                                Slog.w(TAG, "Library not found: " + libPath);
2382                            } catch (IOException | InstallerException e) {
2383                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2384                                        + e.getMessage());
2385                            }
2386                        }
2387                    }
2388                }
2389                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2390            }
2391
2392            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2393
2394            final VersionInfo ver = mSettings.getInternalVersion();
2395            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2396
2397            // when upgrading from pre-M, promote system app permissions from install to runtime
2398            mPromoteSystemApps =
2399                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2400
2401            // When upgrading from pre-N, we need to handle package extraction like first boot,
2402            // as there is no profiling data available.
2403            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2404
2405            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2406
2407            // save off the names of pre-existing system packages prior to scanning; we don't
2408            // want to automatically grant runtime permissions for new system apps
2409            if (mPromoteSystemApps) {
2410                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2411                while (pkgSettingIter.hasNext()) {
2412                    PackageSetting ps = pkgSettingIter.next();
2413                    if (isSystemApp(ps)) {
2414                        mExistingSystemPackages.add(ps.name);
2415                    }
2416                }
2417            }
2418
2419            mCacheDir = preparePackageParserCache(mIsUpgrade);
2420
2421            // Set flag to monitor and not change apk file paths when
2422            // scanning install directories.
2423            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2424
2425            if (mIsUpgrade || mFirstBoot) {
2426                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2427            }
2428
2429            // Collect vendor overlay packages. (Do this before scanning any apps.)
2430            // For security and version matching reason, only consider
2431            // overlay packages if they reside in the right directory.
2432            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2433            if (overlayThemeDir.isEmpty()) {
2434                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2435            }
2436            if (!overlayThemeDir.isEmpty()) {
2437                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2438                        | PackageParser.PARSE_IS_SYSTEM
2439                        | PackageParser.PARSE_IS_SYSTEM_DIR
2440                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2441            }
2442            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2443                    | PackageParser.PARSE_IS_SYSTEM
2444                    | PackageParser.PARSE_IS_SYSTEM_DIR
2445                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2446
2447            // Find base frameworks (resource packages without code).
2448            scanDirTracedLI(frameworkDir, mDefParseFlags
2449                    | PackageParser.PARSE_IS_SYSTEM
2450                    | PackageParser.PARSE_IS_SYSTEM_DIR
2451                    | PackageParser.PARSE_IS_PRIVILEGED,
2452                    scanFlags | SCAN_NO_DEX, 0);
2453
2454            // Collected privileged system packages.
2455            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2456            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2457                    | PackageParser.PARSE_IS_SYSTEM
2458                    | PackageParser.PARSE_IS_SYSTEM_DIR
2459                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2460
2461            // Collect ordinary system packages.
2462            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2463            scanDirTracedLI(systemAppDir, mDefParseFlags
2464                    | PackageParser.PARSE_IS_SYSTEM
2465                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2466
2467            // Collect all vendor packages.
2468            File vendorAppDir = new File("/vendor/app");
2469            try {
2470                vendorAppDir = vendorAppDir.getCanonicalFile();
2471            } catch (IOException e) {
2472                // failed to look up canonical path, continue with original one
2473            }
2474            scanDirTracedLI(vendorAppDir, mDefParseFlags
2475                    | PackageParser.PARSE_IS_SYSTEM
2476                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2477
2478            // Collect all OEM packages.
2479            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2480            scanDirTracedLI(oemAppDir, mDefParseFlags
2481                    | PackageParser.PARSE_IS_SYSTEM
2482                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2483
2484            // Prune any system packages that no longer exist.
2485            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2486            if (!mOnlyCore) {
2487                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2488                while (psit.hasNext()) {
2489                    PackageSetting ps = psit.next();
2490
2491                    /*
2492                     * If this is not a system app, it can't be a
2493                     * disable system app.
2494                     */
2495                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2496                        continue;
2497                    }
2498
2499                    /*
2500                     * If the package is scanned, it's not erased.
2501                     */
2502                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2503                    if (scannedPkg != null) {
2504                        /*
2505                         * If the system app is both scanned and in the
2506                         * disabled packages list, then it must have been
2507                         * added via OTA. Remove it from the currently
2508                         * scanned package so the previously user-installed
2509                         * application can be scanned.
2510                         */
2511                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2512                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2513                                    + ps.name + "; removing system app.  Last known codePath="
2514                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2515                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2516                                    + scannedPkg.mVersionCode);
2517                            removePackageLI(scannedPkg, true);
2518                            mExpectingBetter.put(ps.name, ps.codePath);
2519                        }
2520
2521                        continue;
2522                    }
2523
2524                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2525                        psit.remove();
2526                        logCriticalInfo(Log.WARN, "System package " + ps.name
2527                                + " no longer exists; it's data will be wiped");
2528                        // Actual deletion of code and data will be handled by later
2529                        // reconciliation step
2530                    } else {
2531                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2532                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2533                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2534                        }
2535                    }
2536                }
2537            }
2538
2539            //look for any incomplete package installations
2540            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2541            for (int i = 0; i < deletePkgsList.size(); i++) {
2542                // Actual deletion of code and data will be handled by later
2543                // reconciliation step
2544                final String packageName = deletePkgsList.get(i).name;
2545                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2546                synchronized (mPackages) {
2547                    mSettings.removePackageLPw(packageName);
2548                }
2549            }
2550
2551            //delete tmp files
2552            deleteTempPackageFiles();
2553
2554            // Remove any shared userIDs that have no associated packages
2555            mSettings.pruneSharedUsersLPw();
2556
2557            if (!mOnlyCore) {
2558                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2559                        SystemClock.uptimeMillis());
2560                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2561
2562                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2563                        | PackageParser.PARSE_FORWARD_LOCK,
2564                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2565
2566                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2567                        | PackageParser.PARSE_IS_EPHEMERAL,
2568                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2569
2570                /**
2571                 * Remove disable package settings for any updated system
2572                 * apps that were removed via an OTA. If they're not a
2573                 * previously-updated app, remove them completely.
2574                 * Otherwise, just revoke their system-level permissions.
2575                 */
2576                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2577                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2578                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2579
2580                    String msg;
2581                    if (deletedPkg == null) {
2582                        msg = "Updated system package " + deletedAppName
2583                                + " no longer exists; it's data will be wiped";
2584                        // Actual deletion of code and data will be handled by later
2585                        // reconciliation step
2586                    } else {
2587                        msg = "Updated system app + " + deletedAppName
2588                                + " no longer present; removing system privileges for "
2589                                + deletedAppName;
2590
2591                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2592
2593                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2594                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2595                    }
2596                    logCriticalInfo(Log.WARN, msg);
2597                }
2598
2599                /**
2600                 * Make sure all system apps that we expected to appear on
2601                 * the userdata partition actually showed up. If they never
2602                 * appeared, crawl back and revive the system version.
2603                 */
2604                for (int i = 0; i < mExpectingBetter.size(); i++) {
2605                    final String packageName = mExpectingBetter.keyAt(i);
2606                    if (!mPackages.containsKey(packageName)) {
2607                        final File scanFile = mExpectingBetter.valueAt(i);
2608
2609                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2610                                + " but never showed up; reverting to system");
2611
2612                        int reparseFlags = mDefParseFlags;
2613                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2614                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2615                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                                    | PackageParser.PARSE_IS_PRIVILEGED;
2617                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2618                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2619                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2620                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2621                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2622                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2623                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2624                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2625                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2626                        } else {
2627                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2628                            continue;
2629                        }
2630
2631                        mSettings.enableSystemPackageLPw(packageName);
2632
2633                        try {
2634                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2635                        } catch (PackageManagerException e) {
2636                            Slog.e(TAG, "Failed to parse original system package: "
2637                                    + e.getMessage());
2638                        }
2639                    }
2640                }
2641            }
2642            mExpectingBetter.clear();
2643
2644            // Resolve the storage manager.
2645            mStorageManagerPackage = getStorageManagerPackageName();
2646
2647            // Resolve protected action filters. Only the setup wizard is allowed to
2648            // have a high priority filter for these actions.
2649            mSetupWizardPackage = getSetupWizardPackageName();
2650            if (mProtectedFilters.size() > 0) {
2651                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2652                    Slog.i(TAG, "No setup wizard;"
2653                        + " All protected intents capped to priority 0");
2654                }
2655                for (ActivityIntentInfo filter : mProtectedFilters) {
2656                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2657                        if (DEBUG_FILTERS) {
2658                            Slog.i(TAG, "Found setup wizard;"
2659                                + " allow priority " + filter.getPriority() + ";"
2660                                + " package: " + filter.activity.info.packageName
2661                                + " activity: " + filter.activity.className
2662                                + " priority: " + filter.getPriority());
2663                        }
2664                        // skip setup wizard; allow it to keep the high priority filter
2665                        continue;
2666                    }
2667                    Slog.w(TAG, "Protected action; cap priority to 0;"
2668                            + " package: " + filter.activity.info.packageName
2669                            + " activity: " + filter.activity.className
2670                            + " origPrio: " + filter.getPriority());
2671                    filter.setPriority(0);
2672                }
2673            }
2674            mDeferProtectedFilters = false;
2675            mProtectedFilters.clear();
2676
2677            // Now that we know all of the shared libraries, update all clients to have
2678            // the correct library paths.
2679            updateAllSharedLibrariesLPw(null);
2680
2681            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2682                // NOTE: We ignore potential failures here during a system scan (like
2683                // the rest of the commands above) because there's precious little we
2684                // can do about it. A settings error is reported, though.
2685                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2686            }
2687
2688            // Now that we know all the packages we are keeping,
2689            // read and update their last usage times.
2690            mPackageUsage.read(mPackages);
2691            mCompilerStats.read();
2692
2693            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2694                    SystemClock.uptimeMillis());
2695            Slog.i(TAG, "Time to scan packages: "
2696                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2697                    + " seconds");
2698
2699            // If the platform SDK has changed since the last time we booted,
2700            // we need to re-grant app permission to catch any new ones that
2701            // appear.  This is really a hack, and means that apps can in some
2702            // cases get permissions that the user didn't initially explicitly
2703            // allow...  it would be nice to have some better way to handle
2704            // this situation.
2705            int updateFlags = UPDATE_PERMISSIONS_ALL;
2706            if (ver.sdkVersion != mSdkVersion) {
2707                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2708                        + mSdkVersion + "; regranting permissions for internal storage");
2709                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2710            }
2711            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2712            ver.sdkVersion = mSdkVersion;
2713
2714            // If this is the first boot or an update from pre-M, and it is a normal
2715            // boot, then we need to initialize the default preferred apps across
2716            // all defined users.
2717            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2718                for (UserInfo user : sUserManager.getUsers(true)) {
2719                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2720                    applyFactoryDefaultBrowserLPw(user.id);
2721                    primeDomainVerificationsLPw(user.id);
2722                }
2723            }
2724
2725            // Prepare storage for system user really early during boot,
2726            // since core system apps like SettingsProvider and SystemUI
2727            // can't wait for user to start
2728            final int storageFlags;
2729            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2730                storageFlags = StorageManager.FLAG_STORAGE_DE;
2731            } else {
2732                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2733            }
2734            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2735                    storageFlags, true /* migrateAppData */);
2736
2737            // If this is first boot after an OTA, and a normal boot, then
2738            // we need to clear code cache directories.
2739            // Note that we do *not* clear the application profiles. These remain valid
2740            // across OTAs and are used to drive profile verification (post OTA) and
2741            // profile compilation (without waiting to collect a fresh set of profiles).
2742            if (mIsUpgrade && !onlyCore) {
2743                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2744                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2745                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2746                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2747                        // No apps are running this early, so no need to freeze
2748                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2749                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2750                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2751                    }
2752                }
2753                ver.fingerprint = Build.FINGERPRINT;
2754            }
2755
2756            checkDefaultBrowser();
2757
2758            // clear only after permissions and other defaults have been updated
2759            mExistingSystemPackages.clear();
2760            mPromoteSystemApps = false;
2761
2762            // All the changes are done during package scanning.
2763            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2764
2765            // can downgrade to reader
2766            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2767            mSettings.writeLPr();
2768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2769
2770            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2771            // early on (before the package manager declares itself as early) because other
2772            // components in the system server might ask for package contexts for these apps.
2773            //
2774            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2775            // (i.e, that the data partition is unavailable).
2776            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2777                long start = System.nanoTime();
2778                List<PackageParser.Package> coreApps = new ArrayList<>();
2779                for (PackageParser.Package pkg : mPackages.values()) {
2780                    if (pkg.coreApp) {
2781                        coreApps.add(pkg);
2782                    }
2783                }
2784
2785                int[] stats = performDexOptUpgrade(coreApps, false,
2786                        getCompilerFilterForReason(REASON_CORE_APP));
2787
2788                final int elapsedTimeSeconds =
2789                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2790                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2791
2792                if (DEBUG_DEXOPT) {
2793                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2794                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2795                }
2796
2797
2798                // TODO: Should we log these stats to tron too ?
2799                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2800                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2801                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2802                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2803            }
2804
2805            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2806                    SystemClock.uptimeMillis());
2807
2808            if (!mOnlyCore) {
2809                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2810                mRequiredInstallerPackage = getRequiredInstallerLPr();
2811                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2812                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2813                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2814                        mIntentFilterVerifierComponent);
2815                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2816                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2817                        SharedLibraryInfo.VERSION_UNDEFINED);
2818                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2819                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2820                        SharedLibraryInfo.VERSION_UNDEFINED);
2821            } else {
2822                mRequiredVerifierPackage = null;
2823                mRequiredInstallerPackage = null;
2824                mRequiredUninstallerPackage = null;
2825                mIntentFilterVerifierComponent = null;
2826                mIntentFilterVerifier = null;
2827                mServicesSystemSharedLibraryPackageName = null;
2828                mSharedSystemSharedLibraryPackageName = null;
2829            }
2830
2831            mInstallerService = new PackageInstallerService(context, this);
2832
2833            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2834            if (ephemeralResolverComponent != null) {
2835                if (DEBUG_EPHEMERAL) {
2836                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2837                }
2838                mEphemeralResolverConnection =
2839                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2840            } else {
2841                mEphemeralResolverConnection = null;
2842            }
2843            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2844            if (mEphemeralInstallerComponent != null) {
2845                if (DEBUG_EPHEMERAL) {
2846                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2847                }
2848                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2849            }
2850
2851            // Read and update the usage of dex files.
2852            // Do this at the end of PM init so that all the packages have their
2853            // data directory reconciled.
2854            // At this point we know the code paths of the packages, so we can validate
2855            // the disk file and build the internal cache.
2856            // The usage file is expected to be small so loading and verifying it
2857            // should take a fairly small time compare to the other activities (e.g. package
2858            // scanning).
2859            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2860            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2861            for (int userId : currentUserIds) {
2862                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2863            }
2864            mDexManager.load(userPackages);
2865        } // synchronized (mPackages)
2866        } // synchronized (mInstallLock)
2867
2868        // Now after opening every single application zip, make sure they
2869        // are all flushed.  Not really needed, but keeps things nice and
2870        // tidy.
2871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2872        Runtime.getRuntime().gc();
2873        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2874
2875        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2876        FallbackCategoryProvider.loadFallbacks();
2877        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2878
2879        // The initial scanning above does many calls into installd while
2880        // holding the mPackages lock, but we're mostly interested in yelling
2881        // once we have a booted system.
2882        mInstaller.setWarnIfHeld(mPackages);
2883
2884        // Expose private service for system components to use.
2885        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2886        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2887    }
2888
2889    private static File preparePackageParserCache(boolean isUpgrade) {
2890        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2891            return null;
2892        }
2893
2894        // Disable package parsing on eng builds to allow for faster incremental development.
2895        if ("eng".equals(Build.TYPE)) {
2896            return null;
2897        }
2898
2899        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2900            Slog.i(TAG, "Disabling package parser cache due to system property.");
2901            return null;
2902        }
2903
2904        // The base directory for the package parser cache lives under /data/system/.
2905        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2906                "package_cache");
2907        if (cacheBaseDir == null) {
2908            return null;
2909        }
2910
2911        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2912        // This also serves to "GC" unused entries when the package cache version changes (which
2913        // can only happen during upgrades).
2914        if (isUpgrade) {
2915            FileUtils.deleteContents(cacheBaseDir);
2916        }
2917
2918
2919        // Return the versioned package cache directory. This is something like
2920        // "/data/system/package_cache/1"
2921        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2922
2923        // The following is a workaround to aid development on non-numbered userdebug
2924        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2925        // the system partition is newer.
2926        //
2927        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2928        // that starts with "eng." to signify that this is an engineering build and not
2929        // destined for release.
2930        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2931            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2932
2933            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2934            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2935            // in general and should not be used for production changes. In this specific case,
2936            // we know that they will work.
2937            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2938            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2939                FileUtils.deleteContents(cacheBaseDir);
2940                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2941            }
2942        }
2943
2944        return cacheDir;
2945    }
2946
2947    @Override
2948    public boolean isFirstBoot() {
2949        return mFirstBoot;
2950    }
2951
2952    @Override
2953    public boolean isOnlyCoreApps() {
2954        return mOnlyCore;
2955    }
2956
2957    @Override
2958    public boolean isUpgrade() {
2959        return mIsUpgrade;
2960    }
2961
2962    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2963        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2964
2965        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2966                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2967                UserHandle.USER_SYSTEM);
2968        if (matches.size() == 1) {
2969            return matches.get(0).getComponentInfo().packageName;
2970        } else if (matches.size() == 0) {
2971            Log.e(TAG, "There should probably be a verifier, but, none were found");
2972            return null;
2973        }
2974        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2975    }
2976
2977    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2978        synchronized (mPackages) {
2979            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2980            if (libraryEntry == null) {
2981                throw new IllegalStateException("Missing required shared library:" + name);
2982            }
2983            return libraryEntry.apk;
2984        }
2985    }
2986
2987    private @NonNull String getRequiredInstallerLPr() {
2988        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2989        intent.addCategory(Intent.CATEGORY_DEFAULT);
2990        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2991
2992        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2993                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2994                UserHandle.USER_SYSTEM);
2995        if (matches.size() == 1) {
2996            ResolveInfo resolveInfo = matches.get(0);
2997            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2998                throw new RuntimeException("The installer must be a privileged app");
2999            }
3000            return matches.get(0).getComponentInfo().packageName;
3001        } else {
3002            throw new RuntimeException("There must be exactly one installer; found " + matches);
3003        }
3004    }
3005
3006    private @NonNull String getRequiredUninstallerLPr() {
3007        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3008        intent.addCategory(Intent.CATEGORY_DEFAULT);
3009        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3010
3011        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3012                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3013                UserHandle.USER_SYSTEM);
3014        if (resolveInfo == null ||
3015                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3016            throw new RuntimeException("There must be exactly one uninstaller; found "
3017                    + resolveInfo);
3018        }
3019        return resolveInfo.getComponentInfo().packageName;
3020    }
3021
3022    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3023        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3024
3025        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3026                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3027                UserHandle.USER_SYSTEM);
3028        ResolveInfo best = null;
3029        final int N = matches.size();
3030        for (int i = 0; i < N; i++) {
3031            final ResolveInfo cur = matches.get(i);
3032            final String packageName = cur.getComponentInfo().packageName;
3033            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3034                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3035                continue;
3036            }
3037
3038            if (best == null || cur.priority > best.priority) {
3039                best = cur;
3040            }
3041        }
3042
3043        if (best != null) {
3044            return best.getComponentInfo().getComponentName();
3045        } else {
3046            throw new RuntimeException("There must be at least one intent filter verifier");
3047        }
3048    }
3049
3050    private @Nullable ComponentName getEphemeralResolverLPr() {
3051        final String[] packageArray =
3052                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3053        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3054            if (DEBUG_EPHEMERAL) {
3055                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3056            }
3057            return null;
3058        }
3059
3060        final int resolveFlags =
3061                MATCH_DIRECT_BOOT_AWARE
3062                | MATCH_DIRECT_BOOT_UNAWARE
3063                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3064        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3065        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3066                resolveFlags, UserHandle.USER_SYSTEM);
3067
3068        final int N = resolvers.size();
3069        if (N == 0) {
3070            if (DEBUG_EPHEMERAL) {
3071                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3072            }
3073            return null;
3074        }
3075
3076        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3077        for (int i = 0; i < N; i++) {
3078            final ResolveInfo info = resolvers.get(i);
3079
3080            if (info.serviceInfo == null) {
3081                continue;
3082            }
3083
3084            final String packageName = info.serviceInfo.packageName;
3085            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3086                if (DEBUG_EPHEMERAL) {
3087                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3088                            + " pkg: " + packageName + ", info:" + info);
3089                }
3090                continue;
3091            }
3092
3093            if (DEBUG_EPHEMERAL) {
3094                Slog.v(TAG, "Ephemeral resolver found;"
3095                        + " pkg: " + packageName + ", info:" + info);
3096            }
3097            return new ComponentName(packageName, info.serviceInfo.name);
3098        }
3099        if (DEBUG_EPHEMERAL) {
3100            Slog.v(TAG, "Ephemeral resolver NOT found");
3101        }
3102        return null;
3103    }
3104
3105    private @Nullable ComponentName getEphemeralInstallerLPr() {
3106        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3107        intent.addCategory(Intent.CATEGORY_DEFAULT);
3108        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3109
3110        final int resolveFlags =
3111                MATCH_DIRECT_BOOT_AWARE
3112                | MATCH_DIRECT_BOOT_UNAWARE
3113                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3114        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3115                resolveFlags, UserHandle.USER_SYSTEM);
3116        Iterator<ResolveInfo> iter = matches.iterator();
3117        while (iter.hasNext()) {
3118            final ResolveInfo rInfo = iter.next();
3119            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3120            if (ps != null) {
3121                final PermissionsState permissionsState = ps.getPermissionsState();
3122                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3123                    continue;
3124                }
3125            }
3126            iter.remove();
3127        }
3128        if (matches.size() == 0) {
3129            return null;
3130        } else if (matches.size() == 1) {
3131            return matches.get(0).getComponentInfo().getComponentName();
3132        } else {
3133            throw new RuntimeException(
3134                    "There must be at most one ephemeral installer; found " + matches);
3135        }
3136    }
3137
3138    private void primeDomainVerificationsLPw(int userId) {
3139        if (DEBUG_DOMAIN_VERIFICATION) {
3140            Slog.d(TAG, "Priming domain verifications in user " + userId);
3141        }
3142
3143        SystemConfig systemConfig = SystemConfig.getInstance();
3144        ArraySet<String> packages = systemConfig.getLinkedApps();
3145
3146        for (String packageName : packages) {
3147            PackageParser.Package pkg = mPackages.get(packageName);
3148            if (pkg != null) {
3149                if (!pkg.isSystemApp()) {
3150                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3151                    continue;
3152                }
3153
3154                ArraySet<String> domains = null;
3155                for (PackageParser.Activity a : pkg.activities) {
3156                    for (ActivityIntentInfo filter : a.intents) {
3157                        if (hasValidDomains(filter)) {
3158                            if (domains == null) {
3159                                domains = new ArraySet<String>();
3160                            }
3161                            domains.addAll(filter.getHostsList());
3162                        }
3163                    }
3164                }
3165
3166                if (domains != null && domains.size() > 0) {
3167                    if (DEBUG_DOMAIN_VERIFICATION) {
3168                        Slog.v(TAG, "      + " + packageName);
3169                    }
3170                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3171                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3172                    // and then 'always' in the per-user state actually used for intent resolution.
3173                    final IntentFilterVerificationInfo ivi;
3174                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3175                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3176                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3177                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3178                } else {
3179                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3180                            + "' does not handle web links");
3181                }
3182            } else {
3183                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3184            }
3185        }
3186
3187        scheduleWritePackageRestrictionsLocked(userId);
3188        scheduleWriteSettingsLocked();
3189    }
3190
3191    private void applyFactoryDefaultBrowserLPw(int userId) {
3192        // The default browser app's package name is stored in a string resource,
3193        // with a product-specific overlay used for vendor customization.
3194        String browserPkg = mContext.getResources().getString(
3195                com.android.internal.R.string.default_browser);
3196        if (!TextUtils.isEmpty(browserPkg)) {
3197            // non-empty string => required to be a known package
3198            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3199            if (ps == null) {
3200                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3201                browserPkg = null;
3202            } else {
3203                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3204            }
3205        }
3206
3207        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3208        // default.  If there's more than one, just leave everything alone.
3209        if (browserPkg == null) {
3210            calculateDefaultBrowserLPw(userId);
3211        }
3212    }
3213
3214    private void calculateDefaultBrowserLPw(int userId) {
3215        List<String> allBrowsers = resolveAllBrowserApps(userId);
3216        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3217        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3218    }
3219
3220    private List<String> resolveAllBrowserApps(int userId) {
3221        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3222        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3223                PackageManager.MATCH_ALL, userId);
3224
3225        final int count = list.size();
3226        List<String> result = new ArrayList<String>(count);
3227        for (int i=0; i<count; i++) {
3228            ResolveInfo info = list.get(i);
3229            if (info.activityInfo == null
3230                    || !info.handleAllWebDataURI
3231                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3232                    || result.contains(info.activityInfo.packageName)) {
3233                continue;
3234            }
3235            result.add(info.activityInfo.packageName);
3236        }
3237
3238        return result;
3239    }
3240
3241    private boolean packageIsBrowser(String packageName, int userId) {
3242        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3243                PackageManager.MATCH_ALL, userId);
3244        final int N = list.size();
3245        for (int i = 0; i < N; i++) {
3246            ResolveInfo info = list.get(i);
3247            if (packageName.equals(info.activityInfo.packageName)) {
3248                return true;
3249            }
3250        }
3251        return false;
3252    }
3253
3254    private void checkDefaultBrowser() {
3255        final int myUserId = UserHandle.myUserId();
3256        final String packageName = getDefaultBrowserPackageName(myUserId);
3257        if (packageName != null) {
3258            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3259            if (info == null) {
3260                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3261                synchronized (mPackages) {
3262                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3263                }
3264            }
3265        }
3266    }
3267
3268    @Override
3269    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3270            throws RemoteException {
3271        try {
3272            return super.onTransact(code, data, reply, flags);
3273        } catch (RuntimeException e) {
3274            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3275                Slog.wtf(TAG, "Package Manager Crash", e);
3276            }
3277            throw e;
3278        }
3279    }
3280
3281    static int[] appendInts(int[] cur, int[] add) {
3282        if (add == null) return cur;
3283        if (cur == null) return add;
3284        final int N = add.length;
3285        for (int i=0; i<N; i++) {
3286            cur = appendInt(cur, add[i]);
3287        }
3288        return cur;
3289    }
3290
3291    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3292        if (!sUserManager.exists(userId)) return null;
3293        if (ps == null) {
3294            return null;
3295        }
3296        final PackageParser.Package p = ps.pkg;
3297        if (p == null) {
3298            return null;
3299        }
3300        // Filter out ephemeral app metadata:
3301        //   * The system/shell/root can see metadata for any app
3302        //   * An installed app can see metadata for 1) other installed apps
3303        //     and 2) ephemeral apps that have explicitly interacted with it
3304        //   * Ephemeral apps can only see their own metadata
3305        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3306        if (callingAppId != Process.SYSTEM_UID
3307                && callingAppId != Process.SHELL_UID
3308                && callingAppId != Process.ROOT_UID) {
3309            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3310            if (ephemeralPackageName != null) {
3311                // ephemeral apps can only get information on themselves
3312                if (!ephemeralPackageName.equals(p.packageName)) {
3313                    return null;
3314                }
3315            } else {
3316                if (p.applicationInfo.isEphemeralApp()) {
3317                    // only get access to the ephemeral app if we've been granted access
3318                    if (!mEphemeralApplicationRegistry.isEphemeralAccessGranted(
3319                            userId, callingAppId, ps.appId)) {
3320                        return null;
3321                    }
3322                }
3323            }
3324        }
3325
3326        final PermissionsState permissionsState = ps.getPermissionsState();
3327
3328        // Compute GIDs only if requested
3329        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3330                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3331        // Compute granted permissions only if package has requested permissions
3332        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3333                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3334        final PackageUserState state = ps.readUserState(userId);
3335
3336        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3337                && ps.isSystem()) {
3338            flags |= MATCH_ANY_USER;
3339        }
3340
3341        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3342                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3343
3344        if (packageInfo == null) {
3345            return null;
3346        }
3347
3348        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3349                resolveExternalPackageNameLPr(p);
3350
3351        return packageInfo;
3352    }
3353
3354    @Override
3355    public void checkPackageStartable(String packageName, int userId) {
3356        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3357
3358        synchronized (mPackages) {
3359            final PackageSetting ps = mSettings.mPackages.get(packageName);
3360            if (ps == null) {
3361                throw new SecurityException("Package " + packageName + " was not found!");
3362            }
3363
3364            if (!ps.getInstalled(userId)) {
3365                throw new SecurityException(
3366                        "Package " + packageName + " was not installed for user " + userId + "!");
3367            }
3368
3369            if (mSafeMode && !ps.isSystem()) {
3370                throw new SecurityException("Package " + packageName + " not a system app!");
3371            }
3372
3373            if (mFrozenPackages.contains(packageName)) {
3374                throw new SecurityException("Package " + packageName + " is currently frozen!");
3375            }
3376
3377            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3378                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3379                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3380            }
3381        }
3382    }
3383
3384    @Override
3385    public boolean isPackageAvailable(String packageName, int userId) {
3386        if (!sUserManager.exists(userId)) return false;
3387        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3388                false /* requireFullPermission */, false /* checkShell */, "is package available");
3389        synchronized (mPackages) {
3390            PackageParser.Package p = mPackages.get(packageName);
3391            if (p != null) {
3392                final PackageSetting ps = (PackageSetting) p.mExtras;
3393                if (ps != null) {
3394                    final PackageUserState state = ps.readUserState(userId);
3395                    if (state != null) {
3396                        return PackageParser.isAvailable(state);
3397                    }
3398                }
3399            }
3400        }
3401        return false;
3402    }
3403
3404    @Override
3405    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3406        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3407                flags, userId);
3408    }
3409
3410    @Override
3411    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3412            int flags, int userId) {
3413        return getPackageInfoInternal(versionedPackage.getPackageName(),
3414                // TODO: We will change version code to long, so in the new API it is long
3415                (int) versionedPackage.getVersionCode(), flags, userId);
3416    }
3417
3418    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3419            int flags, int userId) {
3420        if (!sUserManager.exists(userId)) return null;
3421        flags = updateFlagsForPackage(flags, userId, packageName);
3422        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3423                false /* requireFullPermission */, false /* checkShell */, "get package info");
3424
3425        // reader
3426        synchronized (mPackages) {
3427            // Normalize package name to handle renamed packages and static libs
3428            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3429
3430            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3431            if (matchFactoryOnly) {
3432                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3433                if (ps != null) {
3434                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3435                        return null;
3436                    }
3437                    return generatePackageInfo(ps, flags, userId);
3438                }
3439            }
3440
3441            PackageParser.Package p = mPackages.get(packageName);
3442            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3443                return null;
3444            }
3445            if (DEBUG_PACKAGE_INFO)
3446                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3447            if (p != null) {
3448                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3449                        Binder.getCallingUid(), userId)) {
3450                    return null;
3451                }
3452                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3453            }
3454            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3455                final PackageSetting ps = mSettings.mPackages.get(packageName);
3456                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3457                    return null;
3458                }
3459                return generatePackageInfo(ps, flags, userId);
3460            }
3461        }
3462        return null;
3463    }
3464
3465
3466    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3467        // System/shell/root get to see all static libs
3468        final int appId = UserHandle.getAppId(uid);
3469        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3470                || appId == Process.ROOT_UID) {
3471            return false;
3472        }
3473
3474        // No package means no static lib as it is always on internal storage
3475        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3476            return false;
3477        }
3478
3479        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3480                ps.pkg.staticSharedLibVersion);
3481        if (libEntry == null) {
3482            return false;
3483        }
3484
3485        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3486        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3487        if (uidPackageNames == null) {
3488            return true;
3489        }
3490
3491        for (String uidPackageName : uidPackageNames) {
3492            if (ps.name.equals(uidPackageName)) {
3493                return false;
3494            }
3495            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3496            if (uidPs != null) {
3497                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3498                        libEntry.info.getName());
3499                if (index < 0) {
3500                    continue;
3501                }
3502                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3503                    return false;
3504                }
3505            }
3506        }
3507        return true;
3508    }
3509
3510    @Override
3511    public String[] currentToCanonicalPackageNames(String[] names) {
3512        String[] out = new String[names.length];
3513        // reader
3514        synchronized (mPackages) {
3515            for (int i=names.length-1; i>=0; i--) {
3516                PackageSetting ps = mSettings.mPackages.get(names[i]);
3517                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3518            }
3519        }
3520        return out;
3521    }
3522
3523    @Override
3524    public String[] canonicalToCurrentPackageNames(String[] names) {
3525        String[] out = new String[names.length];
3526        // reader
3527        synchronized (mPackages) {
3528            for (int i=names.length-1; i>=0; i--) {
3529                String cur = mSettings.getRenamedPackageLPr(names[i]);
3530                out[i] = cur != null ? cur : names[i];
3531            }
3532        }
3533        return out;
3534    }
3535
3536    @Override
3537    public int getPackageUid(String packageName, int flags, int userId) {
3538        if (!sUserManager.exists(userId)) return -1;
3539        flags = updateFlagsForPackage(flags, userId, packageName);
3540        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3541                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3542
3543        // reader
3544        synchronized (mPackages) {
3545            final PackageParser.Package p = mPackages.get(packageName);
3546            if (p != null && p.isMatch(flags)) {
3547                return UserHandle.getUid(userId, p.applicationInfo.uid);
3548            }
3549            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3550                final PackageSetting ps = mSettings.mPackages.get(packageName);
3551                if (ps != null && ps.isMatch(flags)) {
3552                    return UserHandle.getUid(userId, ps.appId);
3553                }
3554            }
3555        }
3556
3557        return -1;
3558    }
3559
3560    @Override
3561    public int[] getPackageGids(String packageName, int flags, int userId) {
3562        if (!sUserManager.exists(userId)) return null;
3563        flags = updateFlagsForPackage(flags, userId, packageName);
3564        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3565                false /* requireFullPermission */, false /* checkShell */,
3566                "getPackageGids");
3567
3568        // reader
3569        synchronized (mPackages) {
3570            final PackageParser.Package p = mPackages.get(packageName);
3571            if (p != null && p.isMatch(flags)) {
3572                PackageSetting ps = (PackageSetting) p.mExtras;
3573                // TODO: Shouldn't this be checking for package installed state for userId and
3574                // return null?
3575                return ps.getPermissionsState().computeGids(userId);
3576            }
3577            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3578                final PackageSetting ps = mSettings.mPackages.get(packageName);
3579                if (ps != null && ps.isMatch(flags)) {
3580                    return ps.getPermissionsState().computeGids(userId);
3581                }
3582            }
3583        }
3584
3585        return null;
3586    }
3587
3588    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3589        if (bp.perm != null) {
3590            return PackageParser.generatePermissionInfo(bp.perm, flags);
3591        }
3592        PermissionInfo pi = new PermissionInfo();
3593        pi.name = bp.name;
3594        pi.packageName = bp.sourcePackage;
3595        pi.nonLocalizedLabel = bp.name;
3596        pi.protectionLevel = bp.protectionLevel;
3597        return pi;
3598    }
3599
3600    @Override
3601    public PermissionInfo getPermissionInfo(String name, int flags) {
3602        // reader
3603        synchronized (mPackages) {
3604            final BasePermission p = mSettings.mPermissions.get(name);
3605            if (p != null) {
3606                return generatePermissionInfo(p, flags);
3607            }
3608            return null;
3609        }
3610    }
3611
3612    @Override
3613    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3614            int flags) {
3615        // reader
3616        synchronized (mPackages) {
3617            if (group != null && !mPermissionGroups.containsKey(group)) {
3618                // This is thrown as NameNotFoundException
3619                return null;
3620            }
3621
3622            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3623            for (BasePermission p : mSettings.mPermissions.values()) {
3624                if (group == null) {
3625                    if (p.perm == null || p.perm.info.group == null) {
3626                        out.add(generatePermissionInfo(p, flags));
3627                    }
3628                } else {
3629                    if (p.perm != null && group.equals(p.perm.info.group)) {
3630                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3631                    }
3632                }
3633            }
3634            return new ParceledListSlice<>(out);
3635        }
3636    }
3637
3638    @Override
3639    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3640        // reader
3641        synchronized (mPackages) {
3642            return PackageParser.generatePermissionGroupInfo(
3643                    mPermissionGroups.get(name), flags);
3644        }
3645    }
3646
3647    @Override
3648    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3649        // reader
3650        synchronized (mPackages) {
3651            final int N = mPermissionGroups.size();
3652            ArrayList<PermissionGroupInfo> out
3653                    = new ArrayList<PermissionGroupInfo>(N);
3654            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3655                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3656            }
3657            return new ParceledListSlice<>(out);
3658        }
3659    }
3660
3661    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3662            int uid, int userId) {
3663        if (!sUserManager.exists(userId)) return null;
3664        PackageSetting ps = mSettings.mPackages.get(packageName);
3665        if (ps != null) {
3666            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3667                return null;
3668            }
3669            if (ps.pkg == null) {
3670                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3671                if (pInfo != null) {
3672                    return pInfo.applicationInfo;
3673                }
3674                return null;
3675            }
3676            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3677                    ps.readUserState(userId), userId);
3678            if (ai != null) {
3679                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3680            }
3681            return ai;
3682        }
3683        return null;
3684    }
3685
3686    @Override
3687    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3688        if (!sUserManager.exists(userId)) return null;
3689        flags = updateFlagsForApplication(flags, userId, packageName);
3690        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3691                false /* requireFullPermission */, false /* checkShell */, "get application info");
3692
3693        // writer
3694        synchronized (mPackages) {
3695            // Normalize package name to handle renamed packages and static libs
3696            packageName = resolveInternalPackageNameLPr(packageName,
3697                    PackageManager.VERSION_CODE_HIGHEST);
3698
3699            PackageParser.Package p = mPackages.get(packageName);
3700            if (DEBUG_PACKAGE_INFO) Log.v(
3701                    TAG, "getApplicationInfo " + packageName
3702                    + ": " + p);
3703            if (p != null) {
3704                PackageSetting ps = mSettings.mPackages.get(packageName);
3705                if (ps == null) return null;
3706                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3707                    return null;
3708                }
3709                // Note: isEnabledLP() does not apply here - always return info
3710                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3711                        p, flags, ps.readUserState(userId), userId);
3712                if (ai != null) {
3713                    ai.packageName = resolveExternalPackageNameLPr(p);
3714                }
3715                return ai;
3716            }
3717            if ("android".equals(packageName)||"system".equals(packageName)) {
3718                return mAndroidApplication;
3719            }
3720            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3721                // Already generates the external package name
3722                return generateApplicationInfoFromSettingsLPw(packageName,
3723                        Binder.getCallingUid(), flags, userId);
3724            }
3725        }
3726        return null;
3727    }
3728
3729    private String normalizePackageNameLPr(String packageName) {
3730        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3731        return normalizedPackageName != null ? normalizedPackageName : packageName;
3732    }
3733
3734    @Override
3735    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3736            final IPackageDataObserver observer) {
3737        mContext.enforceCallingOrSelfPermission(
3738                android.Manifest.permission.CLEAR_APP_CACHE, null);
3739        // Queue up an async operation since clearing cache may take a little while.
3740        mHandler.post(new Runnable() {
3741            public void run() {
3742                mHandler.removeCallbacks(this);
3743                boolean success = true;
3744                synchronized (mInstallLock) {
3745                    try {
3746                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3747                    } catch (InstallerException e) {
3748                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3749                        success = false;
3750                    }
3751                }
3752                if (observer != null) {
3753                    try {
3754                        observer.onRemoveCompleted(null, success);
3755                    } catch (RemoteException e) {
3756                        Slog.w(TAG, "RemoveException when invoking call back");
3757                    }
3758                }
3759            }
3760        });
3761    }
3762
3763    @Override
3764    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3765            final IntentSender pi) {
3766        mContext.enforceCallingOrSelfPermission(
3767                android.Manifest.permission.CLEAR_APP_CACHE, null);
3768        // Queue up an async operation since clearing cache may take a little while.
3769        mHandler.post(new Runnable() {
3770            public void run() {
3771                mHandler.removeCallbacks(this);
3772                boolean success = true;
3773                synchronized (mInstallLock) {
3774                    try {
3775                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3776                    } catch (InstallerException e) {
3777                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3778                        success = false;
3779                    }
3780                }
3781                if(pi != null) {
3782                    try {
3783                        // Callback via pending intent
3784                        int code = success ? 1 : 0;
3785                        pi.sendIntent(null, code, null,
3786                                null, null);
3787                    } catch (SendIntentException e1) {
3788                        Slog.i(TAG, "Failed to send pending intent");
3789                    }
3790                }
3791            }
3792        });
3793    }
3794
3795    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3796        synchronized (mInstallLock) {
3797            try {
3798                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3799            } catch (InstallerException e) {
3800                throw new IOException("Failed to free enough space", e);
3801            }
3802        }
3803    }
3804
3805    /**
3806     * Update given flags based on encryption status of current user.
3807     */
3808    private int updateFlags(int flags, int userId) {
3809        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3810                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3811            // Caller expressed an explicit opinion about what encryption
3812            // aware/unaware components they want to see, so fall through and
3813            // give them what they want
3814        } else {
3815            // Caller expressed no opinion, so match based on user state
3816            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3817                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3818            } else {
3819                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3820            }
3821        }
3822        return flags;
3823    }
3824
3825    private UserManagerInternal getUserManagerInternal() {
3826        if (mUserManagerInternal == null) {
3827            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3828        }
3829        return mUserManagerInternal;
3830    }
3831
3832    /**
3833     * Update given flags when being used to request {@link PackageInfo}.
3834     */
3835    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3836        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3837        boolean triaged = true;
3838        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3839                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3840            // Caller is asking for component details, so they'd better be
3841            // asking for specific encryption matching behavior, or be triaged
3842            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3843                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3844                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3845                triaged = false;
3846            }
3847        }
3848        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3849                | PackageManager.MATCH_SYSTEM_ONLY
3850                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3851            triaged = false;
3852        }
3853        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3854            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3855                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3856                    + Debug.getCallers(5));
3857        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3858                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3859            // If the caller wants all packages and has a restricted profile associated with it,
3860            // then match all users. This is to make sure that launchers that need to access work
3861            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3862            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3863            flags |= PackageManager.MATCH_ANY_USER;
3864        }
3865        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3866            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3867                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3868        }
3869        return updateFlags(flags, userId);
3870    }
3871
3872    /**
3873     * Update given flags when being used to request {@link ApplicationInfo}.
3874     */
3875    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3876        return updateFlagsForPackage(flags, userId, cookie);
3877    }
3878
3879    /**
3880     * Update given flags when being used to request {@link ComponentInfo}.
3881     */
3882    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3883        if (cookie instanceof Intent) {
3884            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3885                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3886            }
3887        }
3888
3889        boolean triaged = true;
3890        // Caller is asking for component details, so they'd better be
3891        // asking for specific encryption matching behavior, or be triaged
3892        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3893                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3894                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3895            triaged = false;
3896        }
3897        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3898            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3899                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3900        }
3901
3902        return updateFlags(flags, userId);
3903    }
3904
3905    /**
3906     * Update given intent when being used to request {@link ResolveInfo}.
3907     */
3908    private Intent updateIntentForResolve(Intent intent) {
3909        if (intent.getSelector() != null) {
3910            intent = intent.getSelector();
3911        }
3912        if (DEBUG_PREFERRED) {
3913            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3914        }
3915        return intent;
3916    }
3917
3918    /**
3919     * Update given flags when being used to request {@link ResolveInfo}.
3920     */
3921    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3922        // Safe mode means we shouldn't match any third-party components
3923        if (mSafeMode) {
3924            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3925        }
3926        final int callingUid = Binder.getCallingUid();
3927        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3928            // The system sees all components
3929            flags |= PackageManager.MATCH_EPHEMERAL;
3930        } else if (getEphemeralPackageName(callingUid) != null) {
3931            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3932            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3933            flags |= PackageManager.MATCH_EPHEMERAL;
3934        } else {
3935            // Otherwise, prevent leaking ephemeral components
3936            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3937            flags &= ~PackageManager.MATCH_EPHEMERAL;
3938        }
3939        return updateFlagsForComponent(flags, userId, cookie);
3940    }
3941
3942    @Override
3943    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3944        if (!sUserManager.exists(userId)) return null;
3945        flags = updateFlagsForComponent(flags, userId, component);
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3947                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3948        synchronized (mPackages) {
3949            PackageParser.Activity a = mActivities.mActivities.get(component);
3950
3951            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3952            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3953                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3954                if (ps == null) return null;
3955                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3956                        userId);
3957            }
3958            if (mResolveComponentName.equals(component)) {
3959                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3960                        new PackageUserState(), userId);
3961            }
3962        }
3963        return null;
3964    }
3965
3966    @Override
3967    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3968            String resolvedType) {
3969        synchronized (mPackages) {
3970            if (component.equals(mResolveComponentName)) {
3971                // The resolver supports EVERYTHING!
3972                return true;
3973            }
3974            PackageParser.Activity a = mActivities.mActivities.get(component);
3975            if (a == null) {
3976                return false;
3977            }
3978            for (int i=0; i<a.intents.size(); i++) {
3979                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3980                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3981                    return true;
3982                }
3983            }
3984            return false;
3985        }
3986    }
3987
3988    @Override
3989    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3990        if (!sUserManager.exists(userId)) return null;
3991        flags = updateFlagsForComponent(flags, userId, component);
3992        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3993                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3994        synchronized (mPackages) {
3995            PackageParser.Activity a = mReceivers.mActivities.get(component);
3996            if (DEBUG_PACKAGE_INFO) Log.v(
3997                TAG, "getReceiverInfo " + component + ": " + a);
3998            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3999                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4000                if (ps == null) return null;
4001                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4002                        userId);
4003            }
4004        }
4005        return null;
4006    }
4007
4008    @Override
4009    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4010        if (!sUserManager.exists(userId)) return null;
4011        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4012
4013        flags = updateFlagsForPackage(flags, userId, null);
4014
4015        final boolean canSeeStaticLibraries =
4016                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4017                        == PERMISSION_GRANTED
4018                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4019                        == PERMISSION_GRANTED
4020                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4021                        == PERMISSION_GRANTED
4022                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4023                        == PERMISSION_GRANTED;
4024
4025        synchronized (mPackages) {
4026            List<SharedLibraryInfo> result = null;
4027
4028            final int libCount = mSharedLibraries.size();
4029            for (int i = 0; i < libCount; i++) {
4030                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4031                if (versionedLib == null) {
4032                    continue;
4033                }
4034
4035                final int versionCount = versionedLib.size();
4036                for (int j = 0; j < versionCount; j++) {
4037                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4038                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4039                        break;
4040                    }
4041                    final long identity = Binder.clearCallingIdentity();
4042                    try {
4043                        // TODO: We will change version code to long, so in the new API it is long
4044                        PackageInfo packageInfo = getPackageInfoVersioned(
4045                                libInfo.getDeclaringPackage(), flags, userId);
4046                        if (packageInfo == null) {
4047                            continue;
4048                        }
4049                    } finally {
4050                        Binder.restoreCallingIdentity(identity);
4051                    }
4052
4053                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4054                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4055                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4056
4057                    if (result == null) {
4058                        result = new ArrayList<>();
4059                    }
4060                    result.add(resLibInfo);
4061                }
4062            }
4063
4064            return result != null ? new ParceledListSlice<>(result) : null;
4065        }
4066    }
4067
4068    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4069            SharedLibraryInfo libInfo, int flags, int userId) {
4070        List<VersionedPackage> versionedPackages = null;
4071        final int packageCount = mSettings.mPackages.size();
4072        for (int i = 0; i < packageCount; i++) {
4073            PackageSetting ps = mSettings.mPackages.valueAt(i);
4074
4075            if (ps == null) {
4076                continue;
4077            }
4078
4079            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4080                continue;
4081            }
4082
4083            final String libName = libInfo.getName();
4084            if (libInfo.isStatic()) {
4085                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4086                if (libIdx < 0) {
4087                    continue;
4088                }
4089                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4090                    continue;
4091                }
4092                if (versionedPackages == null) {
4093                    versionedPackages = new ArrayList<>();
4094                }
4095                // If the dependent is a static shared lib, use the public package name
4096                String dependentPackageName = ps.name;
4097                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4098                    dependentPackageName = ps.pkg.manifestPackageName;
4099                }
4100                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4101            } else if (ps.pkg != null) {
4102                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4103                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4104                    if (versionedPackages == null) {
4105                        versionedPackages = new ArrayList<>();
4106                    }
4107                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4108                }
4109            }
4110        }
4111
4112        return versionedPackages;
4113    }
4114
4115    @Override
4116    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4117        if (!sUserManager.exists(userId)) return null;
4118        flags = updateFlagsForComponent(flags, userId, component);
4119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4120                false /* requireFullPermission */, false /* checkShell */, "get service info");
4121        synchronized (mPackages) {
4122            PackageParser.Service s = mServices.mServices.get(component);
4123            if (DEBUG_PACKAGE_INFO) Log.v(
4124                TAG, "getServiceInfo " + component + ": " + s);
4125            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4126                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4127                if (ps == null) return null;
4128                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4129                        userId);
4130            }
4131        }
4132        return null;
4133    }
4134
4135    @Override
4136    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4137        if (!sUserManager.exists(userId)) return null;
4138        flags = updateFlagsForComponent(flags, userId, component);
4139        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4140                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4141        synchronized (mPackages) {
4142            PackageParser.Provider p = mProviders.mProviders.get(component);
4143            if (DEBUG_PACKAGE_INFO) Log.v(
4144                TAG, "getProviderInfo " + component + ": " + p);
4145            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4146                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4147                if (ps == null) return null;
4148                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4149                        userId);
4150            }
4151        }
4152        return null;
4153    }
4154
4155    @Override
4156    public String[] getSystemSharedLibraryNames() {
4157        synchronized (mPackages) {
4158            Set<String> libs = null;
4159            final int libCount = mSharedLibraries.size();
4160            for (int i = 0; i < libCount; i++) {
4161                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4162                if (versionedLib == null) {
4163                    continue;
4164                }
4165                final int versionCount = versionedLib.size();
4166                for (int j = 0; j < versionCount; j++) {
4167                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4168                    if (!libEntry.info.isStatic()) {
4169                        if (libs == null) {
4170                            libs = new ArraySet<>();
4171                        }
4172                        libs.add(libEntry.info.getName());
4173                        break;
4174                    }
4175                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4176                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4177                            UserHandle.getUserId(Binder.getCallingUid()))) {
4178                        if (libs == null) {
4179                            libs = new ArraySet<>();
4180                        }
4181                        libs.add(libEntry.info.getName());
4182                        break;
4183                    }
4184                }
4185            }
4186
4187            if (libs != null) {
4188                String[] libsArray = new String[libs.size()];
4189                libs.toArray(libsArray);
4190                return libsArray;
4191            }
4192
4193            return null;
4194        }
4195    }
4196
4197    @Override
4198    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4199        synchronized (mPackages) {
4200            return mServicesSystemSharedLibraryPackageName;
4201        }
4202    }
4203
4204    @Override
4205    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4206        synchronized (mPackages) {
4207            return mSharedSystemSharedLibraryPackageName;
4208        }
4209    }
4210
4211    @Override
4212    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4213        synchronized (mPackages) {
4214            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
4215
4216            final FeatureInfo fi = new FeatureInfo();
4217            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4218                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
4219            res.add(fi);
4220
4221            return new ParceledListSlice<>(res);
4222        }
4223    }
4224
4225    @Override
4226    public boolean hasSystemFeature(String name, int version) {
4227        synchronized (mPackages) {
4228            final FeatureInfo feat = mAvailableFeatures.get(name);
4229            if (feat == null) {
4230                return false;
4231            } else {
4232                return feat.version >= version;
4233            }
4234        }
4235    }
4236
4237    @Override
4238    public int checkPermission(String permName, String pkgName, int userId) {
4239        if (!sUserManager.exists(userId)) {
4240            return PackageManager.PERMISSION_DENIED;
4241        }
4242
4243        synchronized (mPackages) {
4244            final PackageParser.Package p = mPackages.get(pkgName);
4245            if (p != null && p.mExtras != null) {
4246                final PackageSetting ps = (PackageSetting) p.mExtras;
4247                final PermissionsState permissionsState = ps.getPermissionsState();
4248                if (permissionsState.hasPermission(permName, userId)) {
4249                    return PackageManager.PERMISSION_GRANTED;
4250                }
4251                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4252                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4253                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4254                    return PackageManager.PERMISSION_GRANTED;
4255                }
4256            }
4257        }
4258
4259        return PackageManager.PERMISSION_DENIED;
4260    }
4261
4262    @Override
4263    public int checkUidPermission(String permName, int uid) {
4264        final int userId = UserHandle.getUserId(uid);
4265
4266        if (!sUserManager.exists(userId)) {
4267            return PackageManager.PERMISSION_DENIED;
4268        }
4269
4270        synchronized (mPackages) {
4271            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4272            if (obj != null) {
4273                final SettingBase ps = (SettingBase) obj;
4274                final PermissionsState permissionsState = ps.getPermissionsState();
4275                if (permissionsState.hasPermission(permName, userId)) {
4276                    return PackageManager.PERMISSION_GRANTED;
4277                }
4278                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4279                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4280                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4281                    return PackageManager.PERMISSION_GRANTED;
4282                }
4283            } else {
4284                ArraySet<String> perms = mSystemPermissions.get(uid);
4285                if (perms != null) {
4286                    if (perms.contains(permName)) {
4287                        return PackageManager.PERMISSION_GRANTED;
4288                    }
4289                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4290                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4291                        return PackageManager.PERMISSION_GRANTED;
4292                    }
4293                }
4294            }
4295        }
4296
4297        return PackageManager.PERMISSION_DENIED;
4298    }
4299
4300    @Override
4301    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4302        if (UserHandle.getCallingUserId() != userId) {
4303            mContext.enforceCallingPermission(
4304                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4305                    "isPermissionRevokedByPolicy for user " + userId);
4306        }
4307
4308        if (checkPermission(permission, packageName, userId)
4309                == PackageManager.PERMISSION_GRANTED) {
4310            return false;
4311        }
4312
4313        final long identity = Binder.clearCallingIdentity();
4314        try {
4315            final int flags = getPermissionFlags(permission, packageName, userId);
4316            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4317        } finally {
4318            Binder.restoreCallingIdentity(identity);
4319        }
4320    }
4321
4322    @Override
4323    public String getPermissionControllerPackageName() {
4324        synchronized (mPackages) {
4325            return mRequiredInstallerPackage;
4326        }
4327    }
4328
4329    /**
4330     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4331     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4332     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4333     * @param message the message to log on security exception
4334     */
4335    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4336            boolean checkShell, String message) {
4337        if (userId < 0) {
4338            throw new IllegalArgumentException("Invalid userId " + userId);
4339        }
4340        if (checkShell) {
4341            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4342        }
4343        if (userId == UserHandle.getUserId(callingUid)) return;
4344        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4345            if (requireFullPermission) {
4346                mContext.enforceCallingOrSelfPermission(
4347                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4348            } else {
4349                try {
4350                    mContext.enforceCallingOrSelfPermission(
4351                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4352                } catch (SecurityException se) {
4353                    mContext.enforceCallingOrSelfPermission(
4354                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4355                }
4356            }
4357        }
4358    }
4359
4360    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4361        if (callingUid == Process.SHELL_UID) {
4362            if (userHandle >= 0
4363                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4364                throw new SecurityException("Shell does not have permission to access user "
4365                        + userHandle);
4366            } else if (userHandle < 0) {
4367                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4368                        + Debug.getCallers(3));
4369            }
4370        }
4371    }
4372
4373    private BasePermission findPermissionTreeLP(String permName) {
4374        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4375            if (permName.startsWith(bp.name) &&
4376                    permName.length() > bp.name.length() &&
4377                    permName.charAt(bp.name.length()) == '.') {
4378                return bp;
4379            }
4380        }
4381        return null;
4382    }
4383
4384    private BasePermission checkPermissionTreeLP(String permName) {
4385        if (permName != null) {
4386            BasePermission bp = findPermissionTreeLP(permName);
4387            if (bp != null) {
4388                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4389                    return bp;
4390                }
4391                throw new SecurityException("Calling uid "
4392                        + Binder.getCallingUid()
4393                        + " is not allowed to add to permission tree "
4394                        + bp.name + " owned by uid " + bp.uid);
4395            }
4396        }
4397        throw new SecurityException("No permission tree found for " + permName);
4398    }
4399
4400    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4401        if (s1 == null) {
4402            return s2 == null;
4403        }
4404        if (s2 == null) {
4405            return false;
4406        }
4407        if (s1.getClass() != s2.getClass()) {
4408            return false;
4409        }
4410        return s1.equals(s2);
4411    }
4412
4413    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4414        if (pi1.icon != pi2.icon) return false;
4415        if (pi1.logo != pi2.logo) return false;
4416        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4417        if (!compareStrings(pi1.name, pi2.name)) return false;
4418        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4419        // We'll take care of setting this one.
4420        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4421        // These are not currently stored in settings.
4422        //if (!compareStrings(pi1.group, pi2.group)) return false;
4423        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4424        //if (pi1.labelRes != pi2.labelRes) return false;
4425        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4426        return true;
4427    }
4428
4429    int permissionInfoFootprint(PermissionInfo info) {
4430        int size = info.name.length();
4431        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4432        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4433        return size;
4434    }
4435
4436    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4437        int size = 0;
4438        for (BasePermission perm : mSettings.mPermissions.values()) {
4439            if (perm.uid == tree.uid) {
4440                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4441            }
4442        }
4443        return size;
4444    }
4445
4446    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4447        // We calculate the max size of permissions defined by this uid and throw
4448        // if that plus the size of 'info' would exceed our stated maximum.
4449        if (tree.uid != Process.SYSTEM_UID) {
4450            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4451            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4452                throw new SecurityException("Permission tree size cap exceeded");
4453            }
4454        }
4455    }
4456
4457    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4458        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4459            throw new SecurityException("Label must be specified in permission");
4460        }
4461        BasePermission tree = checkPermissionTreeLP(info.name);
4462        BasePermission bp = mSettings.mPermissions.get(info.name);
4463        boolean added = bp == null;
4464        boolean changed = true;
4465        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4466        if (added) {
4467            enforcePermissionCapLocked(info, tree);
4468            bp = new BasePermission(info.name, tree.sourcePackage,
4469                    BasePermission.TYPE_DYNAMIC);
4470        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4471            throw new SecurityException(
4472                    "Not allowed to modify non-dynamic permission "
4473                    + info.name);
4474        } else {
4475            if (bp.protectionLevel == fixedLevel
4476                    && bp.perm.owner.equals(tree.perm.owner)
4477                    && bp.uid == tree.uid
4478                    && comparePermissionInfos(bp.perm.info, info)) {
4479                changed = false;
4480            }
4481        }
4482        bp.protectionLevel = fixedLevel;
4483        info = new PermissionInfo(info);
4484        info.protectionLevel = fixedLevel;
4485        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4486        bp.perm.info.packageName = tree.perm.info.packageName;
4487        bp.uid = tree.uid;
4488        if (added) {
4489            mSettings.mPermissions.put(info.name, bp);
4490        }
4491        if (changed) {
4492            if (!async) {
4493                mSettings.writeLPr();
4494            } else {
4495                scheduleWriteSettingsLocked();
4496            }
4497        }
4498        return added;
4499    }
4500
4501    @Override
4502    public boolean addPermission(PermissionInfo info) {
4503        synchronized (mPackages) {
4504            return addPermissionLocked(info, false);
4505        }
4506    }
4507
4508    @Override
4509    public boolean addPermissionAsync(PermissionInfo info) {
4510        synchronized (mPackages) {
4511            return addPermissionLocked(info, true);
4512        }
4513    }
4514
4515    @Override
4516    public void removePermission(String name) {
4517        synchronized (mPackages) {
4518            checkPermissionTreeLP(name);
4519            BasePermission bp = mSettings.mPermissions.get(name);
4520            if (bp != null) {
4521                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4522                    throw new SecurityException(
4523                            "Not allowed to modify non-dynamic permission "
4524                            + name);
4525                }
4526                mSettings.mPermissions.remove(name);
4527                mSettings.writeLPr();
4528            }
4529        }
4530    }
4531
4532    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4533            BasePermission bp) {
4534        int index = pkg.requestedPermissions.indexOf(bp.name);
4535        if (index == -1) {
4536            throw new SecurityException("Package " + pkg.packageName
4537                    + " has not requested permission " + bp.name);
4538        }
4539        if (!bp.isRuntime() && !bp.isDevelopment()) {
4540            throw new SecurityException("Permission " + bp.name
4541                    + " is not a changeable permission type");
4542        }
4543    }
4544
4545    @Override
4546    public void grantRuntimePermission(String packageName, String name, final int userId) {
4547        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4548    }
4549
4550    private void grantRuntimePermission(String packageName, String name, final int userId,
4551            boolean overridePolicy) {
4552        if (!sUserManager.exists(userId)) {
4553            Log.e(TAG, "No such user:" + userId);
4554            return;
4555        }
4556
4557        mContext.enforceCallingOrSelfPermission(
4558                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4559                "grantRuntimePermission");
4560
4561        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4562                true /* requireFullPermission */, true /* checkShell */,
4563                "grantRuntimePermission");
4564
4565        final int uid;
4566        final SettingBase sb;
4567
4568        synchronized (mPackages) {
4569            final PackageParser.Package pkg = mPackages.get(packageName);
4570            if (pkg == null) {
4571                throw new IllegalArgumentException("Unknown package: " + packageName);
4572            }
4573
4574            final BasePermission bp = mSettings.mPermissions.get(name);
4575            if (bp == null) {
4576                throw new IllegalArgumentException("Unknown permission: " + name);
4577            }
4578
4579            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4580
4581            // If a permission review is required for legacy apps we represent
4582            // their permissions as always granted runtime ones since we need
4583            // to keep the review required permission flag per user while an
4584            // install permission's state is shared across all users.
4585            if (mPermissionReviewRequired
4586                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4587                    && bp.isRuntime()) {
4588                return;
4589            }
4590
4591            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4592            sb = (SettingBase) pkg.mExtras;
4593            if (sb == null) {
4594                throw new IllegalArgumentException("Unknown package: " + packageName);
4595            }
4596
4597            final PermissionsState permissionsState = sb.getPermissionsState();
4598
4599            final int flags = permissionsState.getPermissionFlags(name, userId);
4600            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4601                throw new SecurityException("Cannot grant system fixed permission "
4602                        + name + " for package " + packageName);
4603            }
4604            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4605                throw new SecurityException("Cannot grant policy fixed permission "
4606                        + name + " for package " + packageName);
4607            }
4608
4609            if (bp.isDevelopment()) {
4610                // Development permissions must be handled specially, since they are not
4611                // normal runtime permissions.  For now they apply to all users.
4612                if (permissionsState.grantInstallPermission(bp) !=
4613                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4614                    scheduleWriteSettingsLocked();
4615                }
4616                return;
4617            }
4618
4619            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4620                throw new SecurityException("Cannot grant non-ephemeral permission"
4621                        + name + " for package " + packageName);
4622            }
4623
4624            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4625                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4626                return;
4627            }
4628
4629            final int result = permissionsState.grantRuntimePermission(bp, userId);
4630            switch (result) {
4631                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4632                    return;
4633                }
4634
4635                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4636                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4637                    mHandler.post(new Runnable() {
4638                        @Override
4639                        public void run() {
4640                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4641                        }
4642                    });
4643                }
4644                break;
4645            }
4646
4647            if (bp.isRuntime()) {
4648                logPermissionGranted(mContext, name, packageName);
4649            }
4650
4651            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4652
4653            // Not critical if that is lost - app has to request again.
4654            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4655        }
4656
4657        // Only need to do this if user is initialized. Otherwise it's a new user
4658        // and there are no processes running as the user yet and there's no need
4659        // to make an expensive call to remount processes for the changed permissions.
4660        if (READ_EXTERNAL_STORAGE.equals(name)
4661                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4662            final long token = Binder.clearCallingIdentity();
4663            try {
4664                if (sUserManager.isInitialized(userId)) {
4665                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4666                            StorageManagerInternal.class);
4667                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4668                }
4669            } finally {
4670                Binder.restoreCallingIdentity(token);
4671            }
4672        }
4673    }
4674
4675    @Override
4676    public void revokeRuntimePermission(String packageName, String name, int userId) {
4677        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4678    }
4679
4680    private void revokeRuntimePermission(String packageName, String name, int userId,
4681            boolean overridePolicy) {
4682        if (!sUserManager.exists(userId)) {
4683            Log.e(TAG, "No such user:" + userId);
4684            return;
4685        }
4686
4687        mContext.enforceCallingOrSelfPermission(
4688                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4689                "revokeRuntimePermission");
4690
4691        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4692                true /* requireFullPermission */, true /* checkShell */,
4693                "revokeRuntimePermission");
4694
4695        final int appId;
4696
4697        synchronized (mPackages) {
4698            final PackageParser.Package pkg = mPackages.get(packageName);
4699            if (pkg == null) {
4700                throw new IllegalArgumentException("Unknown package: " + packageName);
4701            }
4702
4703            final BasePermission bp = mSettings.mPermissions.get(name);
4704            if (bp == null) {
4705                throw new IllegalArgumentException("Unknown permission: " + name);
4706            }
4707
4708            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4709
4710            // If a permission review is required for legacy apps we represent
4711            // their permissions as always granted runtime ones since we need
4712            // to keep the review required permission flag per user while an
4713            // install permission's state is shared across all users.
4714            if (mPermissionReviewRequired
4715                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4716                    && bp.isRuntime()) {
4717                return;
4718            }
4719
4720            SettingBase sb = (SettingBase) pkg.mExtras;
4721            if (sb == null) {
4722                throw new IllegalArgumentException("Unknown package: " + packageName);
4723            }
4724
4725            final PermissionsState permissionsState = sb.getPermissionsState();
4726
4727            final int flags = permissionsState.getPermissionFlags(name, userId);
4728            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4729                throw new SecurityException("Cannot revoke system fixed permission "
4730                        + name + " for package " + packageName);
4731            }
4732            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4733                throw new SecurityException("Cannot revoke policy fixed permission "
4734                        + name + " for package " + packageName);
4735            }
4736
4737            if (bp.isDevelopment()) {
4738                // Development permissions must be handled specially, since they are not
4739                // normal runtime permissions.  For now they apply to all users.
4740                if (permissionsState.revokeInstallPermission(bp) !=
4741                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4742                    scheduleWriteSettingsLocked();
4743                }
4744                return;
4745            }
4746
4747            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4748                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4749                return;
4750            }
4751
4752            if (bp.isRuntime()) {
4753                logPermissionRevoked(mContext, name, packageName);
4754            }
4755
4756            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4757
4758            // Critical, after this call app should never have the permission.
4759            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4760
4761            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4762        }
4763
4764        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4765    }
4766
4767    /**
4768     * Get the first event id for the permission.
4769     *
4770     * <p>There are four events for each permission: <ul>
4771     *     <li>Request permission: first id + 0</li>
4772     *     <li>Grant permission: first id + 1</li>
4773     *     <li>Request for permission denied: first id + 2</li>
4774     *     <li>Revoke permission: first id + 3</li>
4775     * </ul></p>
4776     *
4777     * @param name name of the permission
4778     *
4779     * @return The first event id for the permission
4780     */
4781    private static int getBaseEventId(@NonNull String name) {
4782        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4783
4784        if (eventIdIndex == -1) {
4785            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4786                    || "user".equals(Build.TYPE)) {
4787                Log.i(TAG, "Unknown permission " + name);
4788
4789                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4790            } else {
4791                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4792                //
4793                // Also update
4794                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4795                // - metrics_constants.proto
4796                throw new IllegalStateException("Unknown permission " + name);
4797            }
4798        }
4799
4800        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4801    }
4802
4803    /**
4804     * Log that a permission was revoked.
4805     *
4806     * @param context Context of the caller
4807     * @param name name of the permission
4808     * @param packageName package permission if for
4809     */
4810    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4811            @NonNull String packageName) {
4812        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4813    }
4814
4815    /**
4816     * Log that a permission request was granted.
4817     *
4818     * @param context Context of the caller
4819     * @param name name of the permission
4820     * @param packageName package permission if for
4821     */
4822    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4823            @NonNull String packageName) {
4824        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4825    }
4826
4827    @Override
4828    public void resetRuntimePermissions() {
4829        mContext.enforceCallingOrSelfPermission(
4830                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4831                "revokeRuntimePermission");
4832
4833        int callingUid = Binder.getCallingUid();
4834        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4835            mContext.enforceCallingOrSelfPermission(
4836                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4837                    "resetRuntimePermissions");
4838        }
4839
4840        synchronized (mPackages) {
4841            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4842            for (int userId : UserManagerService.getInstance().getUserIds()) {
4843                final int packageCount = mPackages.size();
4844                for (int i = 0; i < packageCount; i++) {
4845                    PackageParser.Package pkg = mPackages.valueAt(i);
4846                    if (!(pkg.mExtras instanceof PackageSetting)) {
4847                        continue;
4848                    }
4849                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4850                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4851                }
4852            }
4853        }
4854    }
4855
4856    @Override
4857    public int getPermissionFlags(String name, String packageName, int userId) {
4858        if (!sUserManager.exists(userId)) {
4859            return 0;
4860        }
4861
4862        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4863
4864        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4865                true /* requireFullPermission */, false /* checkShell */,
4866                "getPermissionFlags");
4867
4868        synchronized (mPackages) {
4869            final PackageParser.Package pkg = mPackages.get(packageName);
4870            if (pkg == null) {
4871                return 0;
4872            }
4873
4874            final BasePermission bp = mSettings.mPermissions.get(name);
4875            if (bp == null) {
4876                return 0;
4877            }
4878
4879            SettingBase sb = (SettingBase) pkg.mExtras;
4880            if (sb == null) {
4881                return 0;
4882            }
4883
4884            PermissionsState permissionsState = sb.getPermissionsState();
4885            return permissionsState.getPermissionFlags(name, userId);
4886        }
4887    }
4888
4889    @Override
4890    public void updatePermissionFlags(String name, String packageName, int flagMask,
4891            int flagValues, int userId) {
4892        if (!sUserManager.exists(userId)) {
4893            return;
4894        }
4895
4896        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4897
4898        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4899                true /* requireFullPermission */, true /* checkShell */,
4900                "updatePermissionFlags");
4901
4902        // Only the system can change these flags and nothing else.
4903        if (getCallingUid() != Process.SYSTEM_UID) {
4904            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4905            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4906            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4907            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4908            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4909        }
4910
4911        synchronized (mPackages) {
4912            final PackageParser.Package pkg = mPackages.get(packageName);
4913            if (pkg == null) {
4914                throw new IllegalArgumentException("Unknown package: " + packageName);
4915            }
4916
4917            final BasePermission bp = mSettings.mPermissions.get(name);
4918            if (bp == null) {
4919                throw new IllegalArgumentException("Unknown permission: " + name);
4920            }
4921
4922            SettingBase sb = (SettingBase) pkg.mExtras;
4923            if (sb == null) {
4924                throw new IllegalArgumentException("Unknown package: " + packageName);
4925            }
4926
4927            PermissionsState permissionsState = sb.getPermissionsState();
4928
4929            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4930
4931            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4932                // Install and runtime permissions are stored in different places,
4933                // so figure out what permission changed and persist the change.
4934                if (permissionsState.getInstallPermissionState(name) != null) {
4935                    scheduleWriteSettingsLocked();
4936                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4937                        || hadState) {
4938                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4939                }
4940            }
4941        }
4942    }
4943
4944    /**
4945     * Update the permission flags for all packages and runtime permissions of a user in order
4946     * to allow device or profile owner to remove POLICY_FIXED.
4947     */
4948    @Override
4949    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4950        if (!sUserManager.exists(userId)) {
4951            return;
4952        }
4953
4954        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4955
4956        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4957                true /* requireFullPermission */, true /* checkShell */,
4958                "updatePermissionFlagsForAllApps");
4959
4960        // Only the system can change system fixed flags.
4961        if (getCallingUid() != Process.SYSTEM_UID) {
4962            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4963            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4964        }
4965
4966        synchronized (mPackages) {
4967            boolean changed = false;
4968            final int packageCount = mPackages.size();
4969            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4970                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4971                SettingBase sb = (SettingBase) pkg.mExtras;
4972                if (sb == null) {
4973                    continue;
4974                }
4975                PermissionsState permissionsState = sb.getPermissionsState();
4976                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4977                        userId, flagMask, flagValues);
4978            }
4979            if (changed) {
4980                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4981            }
4982        }
4983    }
4984
4985    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4986        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4987                != PackageManager.PERMISSION_GRANTED
4988            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4989                != PackageManager.PERMISSION_GRANTED) {
4990            throw new SecurityException(message + " requires "
4991                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4992                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4993        }
4994    }
4995
4996    @Override
4997    public boolean shouldShowRequestPermissionRationale(String permissionName,
4998            String packageName, int userId) {
4999        if (UserHandle.getCallingUserId() != userId) {
5000            mContext.enforceCallingPermission(
5001                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5002                    "canShowRequestPermissionRationale for user " + userId);
5003        }
5004
5005        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5006        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5007            return false;
5008        }
5009
5010        if (checkPermission(permissionName, packageName, userId)
5011                == PackageManager.PERMISSION_GRANTED) {
5012            return false;
5013        }
5014
5015        final int flags;
5016
5017        final long identity = Binder.clearCallingIdentity();
5018        try {
5019            flags = getPermissionFlags(permissionName,
5020                    packageName, userId);
5021        } finally {
5022            Binder.restoreCallingIdentity(identity);
5023        }
5024
5025        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5026                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5027                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5028
5029        if ((flags & fixedFlags) != 0) {
5030            return false;
5031        }
5032
5033        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5034    }
5035
5036    @Override
5037    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5038        mContext.enforceCallingOrSelfPermission(
5039                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5040                "addOnPermissionsChangeListener");
5041
5042        synchronized (mPackages) {
5043            mOnPermissionChangeListeners.addListenerLocked(listener);
5044        }
5045    }
5046
5047    @Override
5048    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5049        synchronized (mPackages) {
5050            mOnPermissionChangeListeners.removeListenerLocked(listener);
5051        }
5052    }
5053
5054    @Override
5055    public boolean isProtectedBroadcast(String actionName) {
5056        synchronized (mPackages) {
5057            if (mProtectedBroadcasts.contains(actionName)) {
5058                return true;
5059            } else if (actionName != null) {
5060                // TODO: remove these terrible hacks
5061                if (actionName.startsWith("android.net.netmon.lingerExpired")
5062                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5063                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5064                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5065                    return true;
5066                }
5067            }
5068        }
5069        return false;
5070    }
5071
5072    @Override
5073    public int checkSignatures(String pkg1, String pkg2) {
5074        synchronized (mPackages) {
5075            final PackageParser.Package p1 = mPackages.get(pkg1);
5076            final PackageParser.Package p2 = mPackages.get(pkg2);
5077            if (p1 == null || p1.mExtras == null
5078                    || p2 == null || p2.mExtras == null) {
5079                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5080            }
5081            return compareSignatures(p1.mSignatures, p2.mSignatures);
5082        }
5083    }
5084
5085    @Override
5086    public int checkUidSignatures(int uid1, int uid2) {
5087        // Map to base uids.
5088        uid1 = UserHandle.getAppId(uid1);
5089        uid2 = UserHandle.getAppId(uid2);
5090        // reader
5091        synchronized (mPackages) {
5092            Signature[] s1;
5093            Signature[] s2;
5094            Object obj = mSettings.getUserIdLPr(uid1);
5095            if (obj != null) {
5096                if (obj instanceof SharedUserSetting) {
5097                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5098                } else if (obj instanceof PackageSetting) {
5099                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5100                } else {
5101                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5102                }
5103            } else {
5104                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5105            }
5106            obj = mSettings.getUserIdLPr(uid2);
5107            if (obj != null) {
5108                if (obj instanceof SharedUserSetting) {
5109                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5110                } else if (obj instanceof PackageSetting) {
5111                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5112                } else {
5113                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5114                }
5115            } else {
5116                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5117            }
5118            return compareSignatures(s1, s2);
5119        }
5120    }
5121
5122    /**
5123     * This method should typically only be used when granting or revoking
5124     * permissions, since the app may immediately restart after this call.
5125     * <p>
5126     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5127     * guard your work against the app being relaunched.
5128     */
5129    private void killUid(int appId, int userId, String reason) {
5130        final long identity = Binder.clearCallingIdentity();
5131        try {
5132            IActivityManager am = ActivityManager.getService();
5133            if (am != null) {
5134                try {
5135                    am.killUid(appId, userId, reason);
5136                } catch (RemoteException e) {
5137                    /* ignore - same process */
5138                }
5139            }
5140        } finally {
5141            Binder.restoreCallingIdentity(identity);
5142        }
5143    }
5144
5145    /**
5146     * Compares two sets of signatures. Returns:
5147     * <br />
5148     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5149     * <br />
5150     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5151     * <br />
5152     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5153     * <br />
5154     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5155     * <br />
5156     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5157     */
5158    static int compareSignatures(Signature[] s1, Signature[] s2) {
5159        if (s1 == null) {
5160            return s2 == null
5161                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5162                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5163        }
5164
5165        if (s2 == null) {
5166            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5167        }
5168
5169        if (s1.length != s2.length) {
5170            return PackageManager.SIGNATURE_NO_MATCH;
5171        }
5172
5173        // Since both signature sets are of size 1, we can compare without HashSets.
5174        if (s1.length == 1) {
5175            return s1[0].equals(s2[0]) ?
5176                    PackageManager.SIGNATURE_MATCH :
5177                    PackageManager.SIGNATURE_NO_MATCH;
5178        }
5179
5180        ArraySet<Signature> set1 = new ArraySet<Signature>();
5181        for (Signature sig : s1) {
5182            set1.add(sig);
5183        }
5184        ArraySet<Signature> set2 = new ArraySet<Signature>();
5185        for (Signature sig : s2) {
5186            set2.add(sig);
5187        }
5188        // Make sure s2 contains all signatures in s1.
5189        if (set1.equals(set2)) {
5190            return PackageManager.SIGNATURE_MATCH;
5191        }
5192        return PackageManager.SIGNATURE_NO_MATCH;
5193    }
5194
5195    /**
5196     * If the database version for this type of package (internal storage or
5197     * external storage) is less than the version where package signatures
5198     * were updated, return true.
5199     */
5200    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5201        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5202        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5203    }
5204
5205    /**
5206     * Used for backward compatibility to make sure any packages with
5207     * certificate chains get upgraded to the new style. {@code existingSigs}
5208     * will be in the old format (since they were stored on disk from before the
5209     * system upgrade) and {@code scannedSigs} will be in the newer format.
5210     */
5211    private int compareSignaturesCompat(PackageSignatures existingSigs,
5212            PackageParser.Package scannedPkg) {
5213        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5214            return PackageManager.SIGNATURE_NO_MATCH;
5215        }
5216
5217        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5218        for (Signature sig : existingSigs.mSignatures) {
5219            existingSet.add(sig);
5220        }
5221        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5222        for (Signature sig : scannedPkg.mSignatures) {
5223            try {
5224                Signature[] chainSignatures = sig.getChainSignatures();
5225                for (Signature chainSig : chainSignatures) {
5226                    scannedCompatSet.add(chainSig);
5227                }
5228            } catch (CertificateEncodingException e) {
5229                scannedCompatSet.add(sig);
5230            }
5231        }
5232        /*
5233         * Make sure the expanded scanned set contains all signatures in the
5234         * existing one.
5235         */
5236        if (scannedCompatSet.equals(existingSet)) {
5237            // Migrate the old signatures to the new scheme.
5238            existingSigs.assignSignatures(scannedPkg.mSignatures);
5239            // The new KeySets will be re-added later in the scanning process.
5240            synchronized (mPackages) {
5241                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5242            }
5243            return PackageManager.SIGNATURE_MATCH;
5244        }
5245        return PackageManager.SIGNATURE_NO_MATCH;
5246    }
5247
5248    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5249        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5250        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5251    }
5252
5253    private int compareSignaturesRecover(PackageSignatures existingSigs,
5254            PackageParser.Package scannedPkg) {
5255        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5256            return PackageManager.SIGNATURE_NO_MATCH;
5257        }
5258
5259        String msg = null;
5260        try {
5261            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5262                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5263                        + scannedPkg.packageName);
5264                return PackageManager.SIGNATURE_MATCH;
5265            }
5266        } catch (CertificateException e) {
5267            msg = e.getMessage();
5268        }
5269
5270        logCriticalInfo(Log.INFO,
5271                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5272        return PackageManager.SIGNATURE_NO_MATCH;
5273    }
5274
5275    @Override
5276    public List<String> getAllPackages() {
5277        synchronized (mPackages) {
5278            return new ArrayList<String>(mPackages.keySet());
5279        }
5280    }
5281
5282    @Override
5283    public String[] getPackagesForUid(int uid) {
5284        final int userId = UserHandle.getUserId(uid);
5285        uid = UserHandle.getAppId(uid);
5286        // reader
5287        synchronized (mPackages) {
5288            Object obj = mSettings.getUserIdLPr(uid);
5289            if (obj instanceof SharedUserSetting) {
5290                final SharedUserSetting sus = (SharedUserSetting) obj;
5291                final int N = sus.packages.size();
5292                String[] res = new String[N];
5293                final Iterator<PackageSetting> it = sus.packages.iterator();
5294                int i = 0;
5295                while (it.hasNext()) {
5296                    PackageSetting ps = it.next();
5297                    if (ps.getInstalled(userId)) {
5298                        res[i++] = ps.name;
5299                    } else {
5300                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5301                    }
5302                }
5303                return res;
5304            } else if (obj instanceof PackageSetting) {
5305                final PackageSetting ps = (PackageSetting) obj;
5306                if (ps.getInstalled(userId)) {
5307                    return new String[]{ps.name};
5308                }
5309            }
5310        }
5311        return null;
5312    }
5313
5314    @Override
5315    public String getNameForUid(int uid) {
5316        // reader
5317        synchronized (mPackages) {
5318            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5319            if (obj instanceof SharedUserSetting) {
5320                final SharedUserSetting sus = (SharedUserSetting) obj;
5321                return sus.name + ":" + sus.userId;
5322            } else if (obj instanceof PackageSetting) {
5323                final PackageSetting ps = (PackageSetting) obj;
5324                return ps.name;
5325            }
5326        }
5327        return null;
5328    }
5329
5330    @Override
5331    public int getUidForSharedUser(String sharedUserName) {
5332        if(sharedUserName == null) {
5333            return -1;
5334        }
5335        // reader
5336        synchronized (mPackages) {
5337            SharedUserSetting suid;
5338            try {
5339                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5340                if (suid != null) {
5341                    return suid.userId;
5342                }
5343            } catch (PackageManagerException ignore) {
5344                // can't happen, but, still need to catch it
5345            }
5346            return -1;
5347        }
5348    }
5349
5350    @Override
5351    public int getFlagsForUid(int uid) {
5352        synchronized (mPackages) {
5353            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5354            if (obj instanceof SharedUserSetting) {
5355                final SharedUserSetting sus = (SharedUserSetting) obj;
5356                return sus.pkgFlags;
5357            } else if (obj instanceof PackageSetting) {
5358                final PackageSetting ps = (PackageSetting) obj;
5359                return ps.pkgFlags;
5360            }
5361        }
5362        return 0;
5363    }
5364
5365    @Override
5366    public int getPrivateFlagsForUid(int uid) {
5367        synchronized (mPackages) {
5368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5369            if (obj instanceof SharedUserSetting) {
5370                final SharedUserSetting sus = (SharedUserSetting) obj;
5371                return sus.pkgPrivateFlags;
5372            } else if (obj instanceof PackageSetting) {
5373                final PackageSetting ps = (PackageSetting) obj;
5374                return ps.pkgPrivateFlags;
5375            }
5376        }
5377        return 0;
5378    }
5379
5380    @Override
5381    public boolean isUidPrivileged(int uid) {
5382        uid = UserHandle.getAppId(uid);
5383        // reader
5384        synchronized (mPackages) {
5385            Object obj = mSettings.getUserIdLPr(uid);
5386            if (obj instanceof SharedUserSetting) {
5387                final SharedUserSetting sus = (SharedUserSetting) obj;
5388                final Iterator<PackageSetting> it = sus.packages.iterator();
5389                while (it.hasNext()) {
5390                    if (it.next().isPrivileged()) {
5391                        return true;
5392                    }
5393                }
5394            } else if (obj instanceof PackageSetting) {
5395                final PackageSetting ps = (PackageSetting) obj;
5396                return ps.isPrivileged();
5397            }
5398        }
5399        return false;
5400    }
5401
5402    @Override
5403    public String[] getAppOpPermissionPackages(String permissionName) {
5404        synchronized (mPackages) {
5405            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5406            if (pkgs == null) {
5407                return null;
5408            }
5409            return pkgs.toArray(new String[pkgs.size()]);
5410        }
5411    }
5412
5413    @Override
5414    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5415            int flags, int userId) {
5416        try {
5417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5418
5419            if (!sUserManager.exists(userId)) return null;
5420            flags = updateFlagsForResolve(flags, userId, intent);
5421            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5422                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5423
5424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5425            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5426                    flags, userId);
5427            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5428
5429            final ResolveInfo bestChoice =
5430                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5431            return bestChoice;
5432        } finally {
5433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5434        }
5435    }
5436
5437    @Override
5438    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5439        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5440            throw new SecurityException(
5441                    "findPersistentPreferredActivity can only be run by the system");
5442        }
5443        if (!sUserManager.exists(userId)) {
5444            return null;
5445        }
5446        intent = updateIntentForResolve(intent);
5447        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5448        final int flags = updateFlagsForResolve(0, userId, intent);
5449        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5450                userId);
5451        synchronized (mPackages) {
5452            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5453                    userId);
5454        }
5455    }
5456
5457    @Override
5458    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5459            IntentFilter filter, int match, ComponentName activity) {
5460        final int userId = UserHandle.getCallingUserId();
5461        if (DEBUG_PREFERRED) {
5462            Log.v(TAG, "setLastChosenActivity intent=" + intent
5463                + " resolvedType=" + resolvedType
5464                + " flags=" + flags
5465                + " filter=" + filter
5466                + " match=" + match
5467                + " activity=" + activity);
5468            filter.dump(new PrintStreamPrinter(System.out), "    ");
5469        }
5470        intent.setComponent(null);
5471        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5472                userId);
5473        // Find any earlier preferred or last chosen entries and nuke them
5474        findPreferredActivity(intent, resolvedType,
5475                flags, query, 0, false, true, false, userId);
5476        // Add the new activity as the last chosen for this filter
5477        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5478                "Setting last chosen");
5479    }
5480
5481    @Override
5482    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5483        final int userId = UserHandle.getCallingUserId();
5484        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5485        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5486                userId);
5487        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5488                false, false, false, userId);
5489    }
5490
5491    private boolean isEphemeralDisabled() {
5492        // ephemeral apps have been disabled across the board
5493        if (DISABLE_EPHEMERAL_APPS) {
5494            return true;
5495        }
5496        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5497        if (!mSystemReady) {
5498            return true;
5499        }
5500        // we can't get a content resolver until the system is ready; these checks must happen last
5501        final ContentResolver resolver = mContext.getContentResolver();
5502        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5503            return true;
5504        }
5505        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5506    }
5507
5508    private boolean isEphemeralAllowed(
5509            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5510            boolean skipPackageCheck) {
5511        // Short circuit and return early if possible.
5512        if (isEphemeralDisabled()) {
5513            return false;
5514        }
5515        final int callingUser = UserHandle.getCallingUserId();
5516        if (callingUser != UserHandle.USER_SYSTEM) {
5517            return false;
5518        }
5519        if (mEphemeralResolverConnection == null) {
5520            return false;
5521        }
5522        if (mEphemeralInstallerComponent == null) {
5523            return false;
5524        }
5525        if (intent.getComponent() != null) {
5526            return false;
5527        }
5528        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5529            return false;
5530        }
5531        if (!skipPackageCheck && intent.getPackage() != null) {
5532            return false;
5533        }
5534        final boolean isWebUri = hasWebURI(intent);
5535        if (!isWebUri || intent.getData().getHost() == null) {
5536            return false;
5537        }
5538        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5539        synchronized (mPackages) {
5540            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5541            for (int n = 0; n < count; n++) {
5542                ResolveInfo info = resolvedActivities.get(n);
5543                String packageName = info.activityInfo.packageName;
5544                PackageSetting ps = mSettings.mPackages.get(packageName);
5545                if (ps != null) {
5546                    // Try to get the status from User settings first
5547                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5548                    int status = (int) (packedStatus >> 32);
5549                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5550                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5551                        if (DEBUG_EPHEMERAL) {
5552                            Slog.v(TAG, "DENY ephemeral apps;"
5553                                + " pkg: " + packageName + ", status: " + status);
5554                        }
5555                        return false;
5556                    }
5557                }
5558            }
5559        }
5560        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5561        return true;
5562    }
5563
5564    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5565            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5566            int userId) {
5567        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5568                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5569                        callingPackage, userId));
5570        mHandler.sendMessage(msg);
5571    }
5572
5573    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5574            int flags, List<ResolveInfo> query, int userId) {
5575        if (query != null) {
5576            final int N = query.size();
5577            if (N == 1) {
5578                return query.get(0);
5579            } else if (N > 1) {
5580                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5581                // If there is more than one activity with the same priority,
5582                // then let the user decide between them.
5583                ResolveInfo r0 = query.get(0);
5584                ResolveInfo r1 = query.get(1);
5585                if (DEBUG_INTENT_MATCHING || debug) {
5586                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5587                            + r1.activityInfo.name + "=" + r1.priority);
5588                }
5589                // If the first activity has a higher priority, or a different
5590                // default, then it is always desirable to pick it.
5591                if (r0.priority != r1.priority
5592                        || r0.preferredOrder != r1.preferredOrder
5593                        || r0.isDefault != r1.isDefault) {
5594                    return query.get(0);
5595                }
5596                // If we have saved a preference for a preferred activity for
5597                // this Intent, use that.
5598                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5599                        flags, query, r0.priority, true, false, debug, userId);
5600                if (ri != null) {
5601                    return ri;
5602                }
5603                ri = new ResolveInfo(mResolveInfo);
5604                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5605                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5606                // If all of the options come from the same package, show the application's
5607                // label and icon instead of the generic resolver's.
5608                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5609                // and then throw away the ResolveInfo itself, meaning that the caller loses
5610                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5611                // a fallback for this case; we only set the target package's resources on
5612                // the ResolveInfo, not the ActivityInfo.
5613                final String intentPackage = intent.getPackage();
5614                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5615                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5616                    ri.resolvePackageName = intentPackage;
5617                    if (userNeedsBadging(userId)) {
5618                        ri.noResourceId = true;
5619                    } else {
5620                        ri.icon = appi.icon;
5621                    }
5622                    ri.iconResourceId = appi.icon;
5623                    ri.labelRes = appi.labelRes;
5624                }
5625                ri.activityInfo.applicationInfo = new ApplicationInfo(
5626                        ri.activityInfo.applicationInfo);
5627                if (userId != 0) {
5628                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5629                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5630                }
5631                // Make sure that the resolver is displayable in car mode
5632                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5633                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5634                return ri;
5635            }
5636        }
5637        return null;
5638    }
5639
5640    /**
5641     * Return true if the given list is not empty and all of its contents have
5642     * an activityInfo with the given package name.
5643     */
5644    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5645        if (ArrayUtils.isEmpty(list)) {
5646            return false;
5647        }
5648        for (int i = 0, N = list.size(); i < N; i++) {
5649            final ResolveInfo ri = list.get(i);
5650            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5651            if (ai == null || !packageName.equals(ai.packageName)) {
5652                return false;
5653            }
5654        }
5655        return true;
5656    }
5657
5658    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5659            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5660        final int N = query.size();
5661        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5662                .get(userId);
5663        // Get the list of persistent preferred activities that handle the intent
5664        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5665        List<PersistentPreferredActivity> pprefs = ppir != null
5666                ? ppir.queryIntent(intent, resolvedType,
5667                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5668                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5669                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5670                : null;
5671        if (pprefs != null && pprefs.size() > 0) {
5672            final int M = pprefs.size();
5673            for (int i=0; i<M; i++) {
5674                final PersistentPreferredActivity ppa = pprefs.get(i);
5675                if (DEBUG_PREFERRED || debug) {
5676                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5677                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5678                            + "\n  component=" + ppa.mComponent);
5679                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5680                }
5681                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5682                        flags | MATCH_DISABLED_COMPONENTS, userId);
5683                if (DEBUG_PREFERRED || debug) {
5684                    Slog.v(TAG, "Found persistent preferred activity:");
5685                    if (ai != null) {
5686                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5687                    } else {
5688                        Slog.v(TAG, "  null");
5689                    }
5690                }
5691                if (ai == null) {
5692                    // This previously registered persistent preferred activity
5693                    // component is no longer known. Ignore it and do NOT remove it.
5694                    continue;
5695                }
5696                for (int j=0; j<N; j++) {
5697                    final ResolveInfo ri = query.get(j);
5698                    if (!ri.activityInfo.applicationInfo.packageName
5699                            .equals(ai.applicationInfo.packageName)) {
5700                        continue;
5701                    }
5702                    if (!ri.activityInfo.name.equals(ai.name)) {
5703                        continue;
5704                    }
5705                    //  Found a persistent preference that can handle the intent.
5706                    if (DEBUG_PREFERRED || debug) {
5707                        Slog.v(TAG, "Returning persistent preferred activity: " +
5708                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5709                    }
5710                    return ri;
5711                }
5712            }
5713        }
5714        return null;
5715    }
5716
5717    // TODO: handle preferred activities missing while user has amnesia
5718    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5719            List<ResolveInfo> query, int priority, boolean always,
5720            boolean removeMatches, boolean debug, int userId) {
5721        if (!sUserManager.exists(userId)) return null;
5722        flags = updateFlagsForResolve(flags, userId, intent);
5723        intent = updateIntentForResolve(intent);
5724        // writer
5725        synchronized (mPackages) {
5726            // Try to find a matching persistent preferred activity.
5727            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5728                    debug, userId);
5729
5730            // If a persistent preferred activity matched, use it.
5731            if (pri != null) {
5732                return pri;
5733            }
5734
5735            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5736            // Get the list of preferred activities that handle the intent
5737            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5738            List<PreferredActivity> prefs = pir != null
5739                    ? pir.queryIntent(intent, resolvedType,
5740                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5741                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5742                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5743                    : null;
5744            if (prefs != null && prefs.size() > 0) {
5745                boolean changed = false;
5746                try {
5747                    // First figure out how good the original match set is.
5748                    // We will only allow preferred activities that came
5749                    // from the same match quality.
5750                    int match = 0;
5751
5752                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5753
5754                    final int N = query.size();
5755                    for (int j=0; j<N; j++) {
5756                        final ResolveInfo ri = query.get(j);
5757                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5758                                + ": 0x" + Integer.toHexString(match));
5759                        if (ri.match > match) {
5760                            match = ri.match;
5761                        }
5762                    }
5763
5764                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5765                            + Integer.toHexString(match));
5766
5767                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5768                    final int M = prefs.size();
5769                    for (int i=0; i<M; i++) {
5770                        final PreferredActivity pa = prefs.get(i);
5771                        if (DEBUG_PREFERRED || debug) {
5772                            Slog.v(TAG, "Checking PreferredActivity ds="
5773                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5774                                    + "\n  component=" + pa.mPref.mComponent);
5775                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5776                        }
5777                        if (pa.mPref.mMatch != match) {
5778                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5779                                    + Integer.toHexString(pa.mPref.mMatch));
5780                            continue;
5781                        }
5782                        // If it's not an "always" type preferred activity and that's what we're
5783                        // looking for, skip it.
5784                        if (always && !pa.mPref.mAlways) {
5785                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5786                            continue;
5787                        }
5788                        final ActivityInfo ai = getActivityInfo(
5789                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5790                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5791                                userId);
5792                        if (DEBUG_PREFERRED || debug) {
5793                            Slog.v(TAG, "Found preferred activity:");
5794                            if (ai != null) {
5795                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5796                            } else {
5797                                Slog.v(TAG, "  null");
5798                            }
5799                        }
5800                        if (ai == null) {
5801                            // This previously registered preferred activity
5802                            // component is no longer known.  Most likely an update
5803                            // to the app was installed and in the new version this
5804                            // component no longer exists.  Clean it up by removing
5805                            // it from the preferred activities list, and skip it.
5806                            Slog.w(TAG, "Removing dangling preferred activity: "
5807                                    + pa.mPref.mComponent);
5808                            pir.removeFilter(pa);
5809                            changed = true;
5810                            continue;
5811                        }
5812                        for (int j=0; j<N; j++) {
5813                            final ResolveInfo ri = query.get(j);
5814                            if (!ri.activityInfo.applicationInfo.packageName
5815                                    .equals(ai.applicationInfo.packageName)) {
5816                                continue;
5817                            }
5818                            if (!ri.activityInfo.name.equals(ai.name)) {
5819                                continue;
5820                            }
5821
5822                            if (removeMatches) {
5823                                pir.removeFilter(pa);
5824                                changed = true;
5825                                if (DEBUG_PREFERRED) {
5826                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5827                                }
5828                                break;
5829                            }
5830
5831                            // Okay we found a previously set preferred or last chosen app.
5832                            // If the result set is different from when this
5833                            // was created, we need to clear it and re-ask the
5834                            // user their preference, if we're looking for an "always" type entry.
5835                            if (always && !pa.mPref.sameSet(query)) {
5836                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5837                                        + intent + " type " + resolvedType);
5838                                if (DEBUG_PREFERRED) {
5839                                    Slog.v(TAG, "Removing preferred activity since set changed "
5840                                            + pa.mPref.mComponent);
5841                                }
5842                                pir.removeFilter(pa);
5843                                // Re-add the filter as a "last chosen" entry (!always)
5844                                PreferredActivity lastChosen = new PreferredActivity(
5845                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5846                                pir.addFilter(lastChosen);
5847                                changed = true;
5848                                return null;
5849                            }
5850
5851                            // Yay! Either the set matched or we're looking for the last chosen
5852                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5853                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5854                            return ri;
5855                        }
5856                    }
5857                } finally {
5858                    if (changed) {
5859                        if (DEBUG_PREFERRED) {
5860                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5861                        }
5862                        scheduleWritePackageRestrictionsLocked(userId);
5863                    }
5864                }
5865            }
5866        }
5867        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5868        return null;
5869    }
5870
5871    /*
5872     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5873     */
5874    @Override
5875    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5876            int targetUserId) {
5877        mContext.enforceCallingOrSelfPermission(
5878                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5879        List<CrossProfileIntentFilter> matches =
5880                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5881        if (matches != null) {
5882            int size = matches.size();
5883            for (int i = 0; i < size; i++) {
5884                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5885            }
5886        }
5887        if (hasWebURI(intent)) {
5888            // cross-profile app linking works only towards the parent.
5889            final UserInfo parent = getProfileParent(sourceUserId);
5890            synchronized(mPackages) {
5891                int flags = updateFlagsForResolve(0, parent.id, intent);
5892                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5893                        intent, resolvedType, flags, sourceUserId, parent.id);
5894                return xpDomainInfo != null;
5895            }
5896        }
5897        return false;
5898    }
5899
5900    private UserInfo getProfileParent(int userId) {
5901        final long identity = Binder.clearCallingIdentity();
5902        try {
5903            return sUserManager.getProfileParent(userId);
5904        } finally {
5905            Binder.restoreCallingIdentity(identity);
5906        }
5907    }
5908
5909    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5910            String resolvedType, int userId) {
5911        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5912        if (resolver != null) {
5913            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5914                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5915        }
5916        return null;
5917    }
5918
5919    @Override
5920    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5921            String resolvedType, int flags, int userId) {
5922        try {
5923            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5924
5925            return new ParceledListSlice<>(
5926                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5927        } finally {
5928            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5929        }
5930    }
5931
5932    /**
5933     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5934     * ephemeral, returns {@code null}.
5935     */
5936    private String getEphemeralPackageName(int callingUid) {
5937        final int appId = UserHandle.getAppId(callingUid);
5938        synchronized (mPackages) {
5939            final Object obj = mSettings.getUserIdLPr(appId);
5940            if (obj instanceof PackageSetting) {
5941                final PackageSetting ps = (PackageSetting) obj;
5942                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5943            }
5944        }
5945        return null;
5946    }
5947
5948    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5949            String resolvedType, int flags, int userId) {
5950        if (!sUserManager.exists(userId)) return Collections.emptyList();
5951        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5952        flags = updateFlagsForResolve(flags, userId, intent);
5953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5954                false /* requireFullPermission */, false /* checkShell */,
5955                "query intent activities");
5956        ComponentName comp = intent.getComponent();
5957        if (comp == null) {
5958            if (intent.getSelector() != null) {
5959                intent = intent.getSelector();
5960                comp = intent.getComponent();
5961            }
5962        }
5963
5964        if (comp != null) {
5965            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5966            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5967            if (ai != null) {
5968                // When specifying an explicit component, we prevent the activity from being
5969                // used when either 1) the calling package is normal and the activity is within
5970                // an ephemeral application or 2) the calling package is ephemeral and the
5971                // activity is not visible to ephemeral applications.
5972                boolean matchEphemeral =
5973                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5974                boolean ephemeralVisibleOnly =
5975                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5976                boolean blockResolution =
5977                        (!matchEphemeral && ephemeralPkgName == null
5978                                && (ai.applicationInfo.privateFlags
5979                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5980                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5981                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5982                if (!blockResolution) {
5983                    final ResolveInfo ri = new ResolveInfo();
5984                    ri.activityInfo = ai;
5985                    list.add(ri);
5986                }
5987            }
5988            return list;
5989        }
5990
5991        // reader
5992        boolean sortResult = false;
5993        boolean addEphemeral = false;
5994        List<ResolveInfo> result;
5995        final String pkgName = intent.getPackage();
5996        synchronized (mPackages) {
5997            if (pkgName == null) {
5998                List<CrossProfileIntentFilter> matchingFilters =
5999                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6000                // Check for results that need to skip the current profile.
6001                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6002                        resolvedType, flags, userId);
6003                if (xpResolveInfo != null) {
6004                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6005                    xpResult.add(xpResolveInfo);
6006                    return filterForEphemeral(
6007                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6008                }
6009
6010                // Check for results in the current profile.
6011                result = filterIfNotSystemUser(mActivities.queryIntent(
6012                        intent, resolvedType, flags, userId), userId);
6013                addEphemeral =
6014                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6015
6016                // Check for cross profile results.
6017                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6018                xpResolveInfo = queryCrossProfileIntents(
6019                        matchingFilters, intent, resolvedType, flags, userId,
6020                        hasNonNegativePriorityResult);
6021                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6022                    boolean isVisibleToUser = filterIfNotSystemUser(
6023                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6024                    if (isVisibleToUser) {
6025                        result.add(xpResolveInfo);
6026                        sortResult = true;
6027                    }
6028                }
6029                if (hasWebURI(intent)) {
6030                    CrossProfileDomainInfo xpDomainInfo = null;
6031                    final UserInfo parent = getProfileParent(userId);
6032                    if (parent != null) {
6033                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6034                                flags, userId, parent.id);
6035                    }
6036                    if (xpDomainInfo != null) {
6037                        if (xpResolveInfo != null) {
6038                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6039                            // in the result.
6040                            result.remove(xpResolveInfo);
6041                        }
6042                        if (result.size() == 0 && !addEphemeral) {
6043                            // No result in current profile, but found candidate in parent user.
6044                            // And we are not going to add emphemeral app, so we can return the
6045                            // result straight away.
6046                            result.add(xpDomainInfo.resolveInfo);
6047                            return filterForEphemeral(result, ephemeralPkgName);
6048                        }
6049                    } else if (result.size() <= 1 && !addEphemeral) {
6050                        // No result in parent user and <= 1 result in current profile, and we
6051                        // are not going to add emphemeral app, so we can return the result without
6052                        // further processing.
6053                        return filterForEphemeral(result, ephemeralPkgName);
6054                    }
6055                    // We have more than one candidate (combining results from current and parent
6056                    // profile), so we need filtering and sorting.
6057                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6058                            intent, flags, result, xpDomainInfo, userId);
6059                    sortResult = true;
6060                }
6061            } else {
6062                final PackageParser.Package pkg = mPackages.get(pkgName);
6063                if (pkg != null) {
6064                    result = filterForEphemeral(filterIfNotSystemUser(
6065                            mActivities.queryIntentForPackage(
6066                                    intent, resolvedType, flags, pkg.activities, userId),
6067                            userId), ephemeralPkgName);
6068                } else {
6069                    // the caller wants to resolve for a particular package; however, there
6070                    // were no installed results, so, try to find an ephemeral result
6071                    addEphemeral = isEphemeralAllowed(
6072                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6073                    result = new ArrayList<ResolveInfo>();
6074                }
6075            }
6076        }
6077        if (addEphemeral) {
6078            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6079            final EphemeralRequest requestObject = new EphemeralRequest(
6080                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6081                    null /*launchIntent*/, null /*callingPackage*/, userId);
6082            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6083                    mContext, mEphemeralResolverConnection, requestObject);
6084            if (intentInfo != null) {
6085                if (DEBUG_EPHEMERAL) {
6086                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6087                }
6088                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6089                ephemeralInstaller.ephemeralResponse = intentInfo;
6090                // make sure this resolver is the default
6091                ephemeralInstaller.isDefault = true;
6092                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6093                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6094                // add a non-generic filter
6095                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6096                ephemeralInstaller.filter.addDataPath(
6097                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6098                result.add(ephemeralInstaller);
6099            }
6100            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6101        }
6102        if (sortResult) {
6103            Collections.sort(result, mResolvePrioritySorter);
6104        }
6105        return filterForEphemeral(result, ephemeralPkgName);
6106    }
6107
6108    private static class CrossProfileDomainInfo {
6109        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6110        ResolveInfo resolveInfo;
6111        /* Best domain verification status of the activities found in the other profile */
6112        int bestDomainVerificationStatus;
6113    }
6114
6115    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6116            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6117        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6118                sourceUserId)) {
6119            return null;
6120        }
6121        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6122                resolvedType, flags, parentUserId);
6123
6124        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6125            return null;
6126        }
6127        CrossProfileDomainInfo result = null;
6128        int size = resultTargetUser.size();
6129        for (int i = 0; i < size; i++) {
6130            ResolveInfo riTargetUser = resultTargetUser.get(i);
6131            // Intent filter verification is only for filters that specify a host. So don't return
6132            // those that handle all web uris.
6133            if (riTargetUser.handleAllWebDataURI) {
6134                continue;
6135            }
6136            String packageName = riTargetUser.activityInfo.packageName;
6137            PackageSetting ps = mSettings.mPackages.get(packageName);
6138            if (ps == null) {
6139                continue;
6140            }
6141            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6142            int status = (int)(verificationState >> 32);
6143            if (result == null) {
6144                result = new CrossProfileDomainInfo();
6145                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6146                        sourceUserId, parentUserId);
6147                result.bestDomainVerificationStatus = status;
6148            } else {
6149                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6150                        result.bestDomainVerificationStatus);
6151            }
6152        }
6153        // Don't consider matches with status NEVER across profiles.
6154        if (result != null && result.bestDomainVerificationStatus
6155                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6156            return null;
6157        }
6158        return result;
6159    }
6160
6161    /**
6162     * Verification statuses are ordered from the worse to the best, except for
6163     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6164     */
6165    private int bestDomainVerificationStatus(int status1, int status2) {
6166        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6167            return status2;
6168        }
6169        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6170            return status1;
6171        }
6172        return (int) MathUtils.max(status1, status2);
6173    }
6174
6175    private boolean isUserEnabled(int userId) {
6176        long callingId = Binder.clearCallingIdentity();
6177        try {
6178            UserInfo userInfo = sUserManager.getUserInfo(userId);
6179            return userInfo != null && userInfo.isEnabled();
6180        } finally {
6181            Binder.restoreCallingIdentity(callingId);
6182        }
6183    }
6184
6185    /**
6186     * Filter out activities with systemUserOnly flag set, when current user is not System.
6187     *
6188     * @return filtered list
6189     */
6190    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6191        if (userId == UserHandle.USER_SYSTEM) {
6192            return resolveInfos;
6193        }
6194        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6195            ResolveInfo info = resolveInfos.get(i);
6196            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6197                resolveInfos.remove(i);
6198            }
6199        }
6200        return resolveInfos;
6201    }
6202
6203    /**
6204     * Filters out ephemeral activities.
6205     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6206     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6207     *
6208     * @param resolveInfos The pre-filtered list of resolved activities
6209     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6210     *          is performed.
6211     * @return A filtered list of resolved activities.
6212     */
6213    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6214            String ephemeralPkgName) {
6215        if (ephemeralPkgName == null) {
6216            return resolveInfos;
6217        }
6218        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6219            ResolveInfo info = resolveInfos.get(i);
6220            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
6221            // allow activities that are defined in the provided package
6222            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6223                continue;
6224            }
6225            // allow activities that have been explicitly exposed to ephemeral apps
6226            if (!isEphemeralApp
6227                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6228                continue;
6229            }
6230            resolveInfos.remove(i);
6231        }
6232        return resolveInfos;
6233    }
6234
6235    /**
6236     * @param resolveInfos list of resolve infos in descending priority order
6237     * @return if the list contains a resolve info with non-negative priority
6238     */
6239    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6240        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6241    }
6242
6243    private static boolean hasWebURI(Intent intent) {
6244        if (intent.getData() == null) {
6245            return false;
6246        }
6247        final String scheme = intent.getScheme();
6248        if (TextUtils.isEmpty(scheme)) {
6249            return false;
6250        }
6251        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6252    }
6253
6254    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6255            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6256            int userId) {
6257        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6258
6259        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6260            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6261                    candidates.size());
6262        }
6263
6264        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6265        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6266        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6267        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6268        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6269        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6270
6271        synchronized (mPackages) {
6272            final int count = candidates.size();
6273            // First, try to use linked apps. Partition the candidates into four lists:
6274            // one for the final results, one for the "do not use ever", one for "undefined status"
6275            // and finally one for "browser app type".
6276            for (int n=0; n<count; n++) {
6277                ResolveInfo info = candidates.get(n);
6278                String packageName = info.activityInfo.packageName;
6279                PackageSetting ps = mSettings.mPackages.get(packageName);
6280                if (ps != null) {
6281                    // Add to the special match all list (Browser use case)
6282                    if (info.handleAllWebDataURI) {
6283                        matchAllList.add(info);
6284                        continue;
6285                    }
6286                    // Try to get the status from User settings first
6287                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6288                    int status = (int)(packedStatus >> 32);
6289                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6290                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6291                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6292                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6293                                    + " : linkgen=" + linkGeneration);
6294                        }
6295                        // Use link-enabled generation as preferredOrder, i.e.
6296                        // prefer newly-enabled over earlier-enabled.
6297                        info.preferredOrder = linkGeneration;
6298                        alwaysList.add(info);
6299                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6300                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6301                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6302                        }
6303                        neverList.add(info);
6304                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6305                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6306                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6307                        }
6308                        alwaysAskList.add(info);
6309                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6310                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6311                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6312                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6313                        }
6314                        undefinedList.add(info);
6315                    }
6316                }
6317            }
6318
6319            // We'll want to include browser possibilities in a few cases
6320            boolean includeBrowser = false;
6321
6322            // First try to add the "always" resolution(s) for the current user, if any
6323            if (alwaysList.size() > 0) {
6324                result.addAll(alwaysList);
6325            } else {
6326                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6327                result.addAll(undefinedList);
6328                // Maybe add one for the other profile.
6329                if (xpDomainInfo != null && (
6330                        xpDomainInfo.bestDomainVerificationStatus
6331                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6332                    result.add(xpDomainInfo.resolveInfo);
6333                }
6334                includeBrowser = true;
6335            }
6336
6337            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6338            // If there were 'always' entries their preferred order has been set, so we also
6339            // back that off to make the alternatives equivalent
6340            if (alwaysAskList.size() > 0) {
6341                for (ResolveInfo i : result) {
6342                    i.preferredOrder = 0;
6343                }
6344                result.addAll(alwaysAskList);
6345                includeBrowser = true;
6346            }
6347
6348            if (includeBrowser) {
6349                // Also add browsers (all of them or only the default one)
6350                if (DEBUG_DOMAIN_VERIFICATION) {
6351                    Slog.v(TAG, "   ...including browsers in candidate set");
6352                }
6353                if ((matchFlags & MATCH_ALL) != 0) {
6354                    result.addAll(matchAllList);
6355                } else {
6356                    // Browser/generic handling case.  If there's a default browser, go straight
6357                    // to that (but only if there is no other higher-priority match).
6358                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6359                    int maxMatchPrio = 0;
6360                    ResolveInfo defaultBrowserMatch = null;
6361                    final int numCandidates = matchAllList.size();
6362                    for (int n = 0; n < numCandidates; n++) {
6363                        ResolveInfo info = matchAllList.get(n);
6364                        // track the highest overall match priority...
6365                        if (info.priority > maxMatchPrio) {
6366                            maxMatchPrio = info.priority;
6367                        }
6368                        // ...and the highest-priority default browser match
6369                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6370                            if (defaultBrowserMatch == null
6371                                    || (defaultBrowserMatch.priority < info.priority)) {
6372                                if (debug) {
6373                                    Slog.v(TAG, "Considering default browser match " + info);
6374                                }
6375                                defaultBrowserMatch = info;
6376                            }
6377                        }
6378                    }
6379                    if (defaultBrowserMatch != null
6380                            && defaultBrowserMatch.priority >= maxMatchPrio
6381                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6382                    {
6383                        if (debug) {
6384                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6385                        }
6386                        result.add(defaultBrowserMatch);
6387                    } else {
6388                        result.addAll(matchAllList);
6389                    }
6390                }
6391
6392                // If there is nothing selected, add all candidates and remove the ones that the user
6393                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6394                if (result.size() == 0) {
6395                    result.addAll(candidates);
6396                    result.removeAll(neverList);
6397                }
6398            }
6399        }
6400        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6401            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6402                    result.size());
6403            for (ResolveInfo info : result) {
6404                Slog.v(TAG, "  + " + info.activityInfo);
6405            }
6406        }
6407        return result;
6408    }
6409
6410    // Returns a packed value as a long:
6411    //
6412    // high 'int'-sized word: link status: undefined/ask/never/always.
6413    // low 'int'-sized word: relative priority among 'always' results.
6414    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6415        long result = ps.getDomainVerificationStatusForUser(userId);
6416        // if none available, get the master status
6417        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6418            if (ps.getIntentFilterVerificationInfo() != null) {
6419                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6420            }
6421        }
6422        return result;
6423    }
6424
6425    private ResolveInfo querySkipCurrentProfileIntents(
6426            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6427            int flags, int sourceUserId) {
6428        if (matchingFilters != null) {
6429            int size = matchingFilters.size();
6430            for (int i = 0; i < size; i ++) {
6431                CrossProfileIntentFilter filter = matchingFilters.get(i);
6432                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6433                    // Checking if there are activities in the target user that can handle the
6434                    // intent.
6435                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6436                            resolvedType, flags, sourceUserId);
6437                    if (resolveInfo != null) {
6438                        return resolveInfo;
6439                    }
6440                }
6441            }
6442        }
6443        return null;
6444    }
6445
6446    // Return matching ResolveInfo in target user if any.
6447    private ResolveInfo queryCrossProfileIntents(
6448            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6449            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6450        if (matchingFilters != null) {
6451            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6452            // match the same intent. For performance reasons, it is better not to
6453            // run queryIntent twice for the same userId
6454            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6455            int size = matchingFilters.size();
6456            for (int i = 0; i < size; i++) {
6457                CrossProfileIntentFilter filter = matchingFilters.get(i);
6458                int targetUserId = filter.getTargetUserId();
6459                boolean skipCurrentProfile =
6460                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6461                boolean skipCurrentProfileIfNoMatchFound =
6462                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6463                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6464                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6465                    // Checking if there are activities in the target user that can handle the
6466                    // intent.
6467                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6468                            resolvedType, flags, sourceUserId);
6469                    if (resolveInfo != null) return resolveInfo;
6470                    alreadyTriedUserIds.put(targetUserId, true);
6471                }
6472            }
6473        }
6474        return null;
6475    }
6476
6477    /**
6478     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6479     * will forward the intent to the filter's target user.
6480     * Otherwise, returns null.
6481     */
6482    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6483            String resolvedType, int flags, int sourceUserId) {
6484        int targetUserId = filter.getTargetUserId();
6485        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6486                resolvedType, flags, targetUserId);
6487        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6488            // If all the matches in the target profile are suspended, return null.
6489            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6490                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6491                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6492                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6493                            targetUserId);
6494                }
6495            }
6496        }
6497        return null;
6498    }
6499
6500    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6501            int sourceUserId, int targetUserId) {
6502        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6503        long ident = Binder.clearCallingIdentity();
6504        boolean targetIsProfile;
6505        try {
6506            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6507        } finally {
6508            Binder.restoreCallingIdentity(ident);
6509        }
6510        String className;
6511        if (targetIsProfile) {
6512            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6513        } else {
6514            className = FORWARD_INTENT_TO_PARENT;
6515        }
6516        ComponentName forwardingActivityComponentName = new ComponentName(
6517                mAndroidApplication.packageName, className);
6518        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6519                sourceUserId);
6520        if (!targetIsProfile) {
6521            forwardingActivityInfo.showUserIcon = targetUserId;
6522            forwardingResolveInfo.noResourceId = true;
6523        }
6524        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6525        forwardingResolveInfo.priority = 0;
6526        forwardingResolveInfo.preferredOrder = 0;
6527        forwardingResolveInfo.match = 0;
6528        forwardingResolveInfo.isDefault = true;
6529        forwardingResolveInfo.filter = filter;
6530        forwardingResolveInfo.targetUserId = targetUserId;
6531        return forwardingResolveInfo;
6532    }
6533
6534    @Override
6535    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6536            Intent[] specifics, String[] specificTypes, Intent intent,
6537            String resolvedType, int flags, int userId) {
6538        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6539                specificTypes, intent, resolvedType, flags, userId));
6540    }
6541
6542    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6543            Intent[] specifics, String[] specificTypes, Intent intent,
6544            String resolvedType, int flags, int userId) {
6545        if (!sUserManager.exists(userId)) return Collections.emptyList();
6546        flags = updateFlagsForResolve(flags, userId, intent);
6547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6548                false /* requireFullPermission */, false /* checkShell */,
6549                "query intent activity options");
6550        final String resultsAction = intent.getAction();
6551
6552        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6553                | PackageManager.GET_RESOLVED_FILTER, userId);
6554
6555        if (DEBUG_INTENT_MATCHING) {
6556            Log.v(TAG, "Query " + intent + ": " + results);
6557        }
6558
6559        int specificsPos = 0;
6560        int N;
6561
6562        // todo: note that the algorithm used here is O(N^2).  This
6563        // isn't a problem in our current environment, but if we start running
6564        // into situations where we have more than 5 or 10 matches then this
6565        // should probably be changed to something smarter...
6566
6567        // First we go through and resolve each of the specific items
6568        // that were supplied, taking care of removing any corresponding
6569        // duplicate items in the generic resolve list.
6570        if (specifics != null) {
6571            for (int i=0; i<specifics.length; i++) {
6572                final Intent sintent = specifics[i];
6573                if (sintent == null) {
6574                    continue;
6575                }
6576
6577                if (DEBUG_INTENT_MATCHING) {
6578                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6579                }
6580
6581                String action = sintent.getAction();
6582                if (resultsAction != null && resultsAction.equals(action)) {
6583                    // If this action was explicitly requested, then don't
6584                    // remove things that have it.
6585                    action = null;
6586                }
6587
6588                ResolveInfo ri = null;
6589                ActivityInfo ai = null;
6590
6591                ComponentName comp = sintent.getComponent();
6592                if (comp == null) {
6593                    ri = resolveIntent(
6594                        sintent,
6595                        specificTypes != null ? specificTypes[i] : null,
6596                            flags, userId);
6597                    if (ri == null) {
6598                        continue;
6599                    }
6600                    if (ri == mResolveInfo) {
6601                        // ACK!  Must do something better with this.
6602                    }
6603                    ai = ri.activityInfo;
6604                    comp = new ComponentName(ai.applicationInfo.packageName,
6605                            ai.name);
6606                } else {
6607                    ai = getActivityInfo(comp, flags, userId);
6608                    if (ai == null) {
6609                        continue;
6610                    }
6611                }
6612
6613                // Look for any generic query activities that are duplicates
6614                // of this specific one, and remove them from the results.
6615                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6616                N = results.size();
6617                int j;
6618                for (j=specificsPos; j<N; j++) {
6619                    ResolveInfo sri = results.get(j);
6620                    if ((sri.activityInfo.name.equals(comp.getClassName())
6621                            && sri.activityInfo.applicationInfo.packageName.equals(
6622                                    comp.getPackageName()))
6623                        || (action != null && sri.filter.matchAction(action))) {
6624                        results.remove(j);
6625                        if (DEBUG_INTENT_MATCHING) Log.v(
6626                            TAG, "Removing duplicate item from " + j
6627                            + " due to specific " + specificsPos);
6628                        if (ri == null) {
6629                            ri = sri;
6630                        }
6631                        j--;
6632                        N--;
6633                    }
6634                }
6635
6636                // Add this specific item to its proper place.
6637                if (ri == null) {
6638                    ri = new ResolveInfo();
6639                    ri.activityInfo = ai;
6640                }
6641                results.add(specificsPos, ri);
6642                ri.specificIndex = i;
6643                specificsPos++;
6644            }
6645        }
6646
6647        // Now we go through the remaining generic results and remove any
6648        // duplicate actions that are found here.
6649        N = results.size();
6650        for (int i=specificsPos; i<N-1; i++) {
6651            final ResolveInfo rii = results.get(i);
6652            if (rii.filter == null) {
6653                continue;
6654            }
6655
6656            // Iterate over all of the actions of this result's intent
6657            // filter...  typically this should be just one.
6658            final Iterator<String> it = rii.filter.actionsIterator();
6659            if (it == null) {
6660                continue;
6661            }
6662            while (it.hasNext()) {
6663                final String action = it.next();
6664                if (resultsAction != null && resultsAction.equals(action)) {
6665                    // If this action was explicitly requested, then don't
6666                    // remove things that have it.
6667                    continue;
6668                }
6669                for (int j=i+1; j<N; j++) {
6670                    final ResolveInfo rij = results.get(j);
6671                    if (rij.filter != null && rij.filter.hasAction(action)) {
6672                        results.remove(j);
6673                        if (DEBUG_INTENT_MATCHING) Log.v(
6674                            TAG, "Removing duplicate item from " + j
6675                            + " due to action " + action + " at " + i);
6676                        j--;
6677                        N--;
6678                    }
6679                }
6680            }
6681
6682            // If the caller didn't request filter information, drop it now
6683            // so we don't have to marshall/unmarshall it.
6684            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6685                rii.filter = null;
6686            }
6687        }
6688
6689        // Filter out the caller activity if so requested.
6690        if (caller != null) {
6691            N = results.size();
6692            for (int i=0; i<N; i++) {
6693                ActivityInfo ainfo = results.get(i).activityInfo;
6694                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6695                        && caller.getClassName().equals(ainfo.name)) {
6696                    results.remove(i);
6697                    break;
6698                }
6699            }
6700        }
6701
6702        // If the caller didn't request filter information,
6703        // drop them now so we don't have to
6704        // marshall/unmarshall it.
6705        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6706            N = results.size();
6707            for (int i=0; i<N; i++) {
6708                results.get(i).filter = null;
6709            }
6710        }
6711
6712        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6713        return results;
6714    }
6715
6716    @Override
6717    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6718            String resolvedType, int flags, int userId) {
6719        return new ParceledListSlice<>(
6720                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6721    }
6722
6723    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6724            String resolvedType, int flags, int userId) {
6725        if (!sUserManager.exists(userId)) return Collections.emptyList();
6726        flags = updateFlagsForResolve(flags, userId, intent);
6727        ComponentName comp = intent.getComponent();
6728        if (comp == null) {
6729            if (intent.getSelector() != null) {
6730                intent = intent.getSelector();
6731                comp = intent.getComponent();
6732            }
6733        }
6734        if (comp != null) {
6735            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6736            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6737            if (ai != null) {
6738                ResolveInfo ri = new ResolveInfo();
6739                ri.activityInfo = ai;
6740                list.add(ri);
6741            }
6742            return list;
6743        }
6744
6745        // reader
6746        synchronized (mPackages) {
6747            String pkgName = intent.getPackage();
6748            if (pkgName == null) {
6749                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6750            }
6751            final PackageParser.Package pkg = mPackages.get(pkgName);
6752            if (pkg != null) {
6753                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6754                        userId);
6755            }
6756            return Collections.emptyList();
6757        }
6758    }
6759
6760    @Override
6761    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6762        if (!sUserManager.exists(userId)) return null;
6763        flags = updateFlagsForResolve(flags, userId, intent);
6764        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6765        if (query != null) {
6766            if (query.size() >= 1) {
6767                // If there is more than one service with the same priority,
6768                // just arbitrarily pick the first one.
6769                return query.get(0);
6770            }
6771        }
6772        return null;
6773    }
6774
6775    @Override
6776    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6777            String resolvedType, int flags, int userId) {
6778        return new ParceledListSlice<>(
6779                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6780    }
6781
6782    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6783            String resolvedType, int flags, int userId) {
6784        if (!sUserManager.exists(userId)) return Collections.emptyList();
6785        flags = updateFlagsForResolve(flags, userId, intent);
6786        ComponentName comp = intent.getComponent();
6787        if (comp == null) {
6788            if (intent.getSelector() != null) {
6789                intent = intent.getSelector();
6790                comp = intent.getComponent();
6791            }
6792        }
6793        if (comp != null) {
6794            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6795            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6796            if (si != null) {
6797                final ResolveInfo ri = new ResolveInfo();
6798                ri.serviceInfo = si;
6799                list.add(ri);
6800            }
6801            return list;
6802        }
6803
6804        // reader
6805        synchronized (mPackages) {
6806            String pkgName = intent.getPackage();
6807            if (pkgName == null) {
6808                return mServices.queryIntent(intent, resolvedType, flags, userId);
6809            }
6810            final PackageParser.Package pkg = mPackages.get(pkgName);
6811            if (pkg != null) {
6812                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6813                        userId);
6814            }
6815            return Collections.emptyList();
6816        }
6817    }
6818
6819    @Override
6820    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6821            String resolvedType, int flags, int userId) {
6822        return new ParceledListSlice<>(
6823                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6824    }
6825
6826    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6827            Intent intent, String resolvedType, int flags, int userId) {
6828        if (!sUserManager.exists(userId)) return Collections.emptyList();
6829        flags = updateFlagsForResolve(flags, userId, intent);
6830        ComponentName comp = intent.getComponent();
6831        if (comp == null) {
6832            if (intent.getSelector() != null) {
6833                intent = intent.getSelector();
6834                comp = intent.getComponent();
6835            }
6836        }
6837        if (comp != null) {
6838            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6839            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6840            if (pi != null) {
6841                final ResolveInfo ri = new ResolveInfo();
6842                ri.providerInfo = pi;
6843                list.add(ri);
6844            }
6845            return list;
6846        }
6847
6848        // reader
6849        synchronized (mPackages) {
6850            String pkgName = intent.getPackage();
6851            if (pkgName == null) {
6852                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6853            }
6854            final PackageParser.Package pkg = mPackages.get(pkgName);
6855            if (pkg != null) {
6856                return mProviders.queryIntentForPackage(
6857                        intent, resolvedType, flags, pkg.providers, userId);
6858            }
6859            return Collections.emptyList();
6860        }
6861    }
6862
6863    @Override
6864    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6865        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6866        flags = updateFlagsForPackage(flags, userId, null);
6867        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6868        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6869                true /* requireFullPermission */, false /* checkShell */,
6870                "get installed packages");
6871
6872        // writer
6873        synchronized (mPackages) {
6874            ArrayList<PackageInfo> list;
6875            if (listUninstalled) {
6876                list = new ArrayList<>(mSettings.mPackages.size());
6877                for (PackageSetting ps : mSettings.mPackages.values()) {
6878                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6879                        continue;
6880                    }
6881                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6882                    if (pi != null) {
6883                        list.add(pi);
6884                    }
6885                }
6886            } else {
6887                list = new ArrayList<>(mPackages.size());
6888                for (PackageParser.Package p : mPackages.values()) {
6889                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6890                            Binder.getCallingUid(), userId)) {
6891                        continue;
6892                    }
6893                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6894                            p.mExtras, flags, userId);
6895                    if (pi != null) {
6896                        list.add(pi);
6897                    }
6898                }
6899            }
6900
6901            return new ParceledListSlice<>(list);
6902        }
6903    }
6904
6905    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6906            String[] permissions, boolean[] tmp, int flags, int userId) {
6907        int numMatch = 0;
6908        final PermissionsState permissionsState = ps.getPermissionsState();
6909        for (int i=0; i<permissions.length; i++) {
6910            final String permission = permissions[i];
6911            if (permissionsState.hasPermission(permission, userId)) {
6912                tmp[i] = true;
6913                numMatch++;
6914            } else {
6915                tmp[i] = false;
6916            }
6917        }
6918        if (numMatch == 0) {
6919            return;
6920        }
6921        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6922
6923        // The above might return null in cases of uninstalled apps or install-state
6924        // skew across users/profiles.
6925        if (pi != null) {
6926            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6927                if (numMatch == permissions.length) {
6928                    pi.requestedPermissions = permissions;
6929                } else {
6930                    pi.requestedPermissions = new String[numMatch];
6931                    numMatch = 0;
6932                    for (int i=0; i<permissions.length; i++) {
6933                        if (tmp[i]) {
6934                            pi.requestedPermissions[numMatch] = permissions[i];
6935                            numMatch++;
6936                        }
6937                    }
6938                }
6939            }
6940            list.add(pi);
6941        }
6942    }
6943
6944    @Override
6945    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6946            String[] permissions, int flags, int userId) {
6947        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6948        flags = updateFlagsForPackage(flags, userId, permissions);
6949        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6950                true /* requireFullPermission */, false /* checkShell */,
6951                "get packages holding permissions");
6952        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6953
6954        // writer
6955        synchronized (mPackages) {
6956            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6957            boolean[] tmpBools = new boolean[permissions.length];
6958            if (listUninstalled) {
6959                for (PackageSetting ps : mSettings.mPackages.values()) {
6960                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6961                            userId);
6962                }
6963            } else {
6964                for (PackageParser.Package pkg : mPackages.values()) {
6965                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6966                    if (ps != null) {
6967                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6968                                userId);
6969                    }
6970                }
6971            }
6972
6973            return new ParceledListSlice<PackageInfo>(list);
6974        }
6975    }
6976
6977    @Override
6978    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6979        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6980        flags = updateFlagsForApplication(flags, userId, null);
6981        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6982
6983        // writer
6984        synchronized (mPackages) {
6985            ArrayList<ApplicationInfo> list;
6986            if (listUninstalled) {
6987                list = new ArrayList<>(mSettings.mPackages.size());
6988                for (PackageSetting ps : mSettings.mPackages.values()) {
6989                    ApplicationInfo ai;
6990                    int effectiveFlags = flags;
6991                    if (ps.isSystem()) {
6992                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6993                    }
6994                    if (ps.pkg != null) {
6995                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6996                            continue;
6997                        }
6998                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6999                                ps.readUserState(userId), userId);
7000                        if (ai != null) {
7001                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7002                        }
7003                    } else {
7004                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7005                        // and already converts to externally visible package name
7006                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7007                                Binder.getCallingUid(), effectiveFlags, userId);
7008                    }
7009                    if (ai != null) {
7010                        list.add(ai);
7011                    }
7012                }
7013            } else {
7014                list = new ArrayList<>(mPackages.size());
7015                for (PackageParser.Package p : mPackages.values()) {
7016                    if (p.mExtras != null) {
7017                        PackageSetting ps = (PackageSetting) p.mExtras;
7018                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7019                            continue;
7020                        }
7021                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7022                                ps.readUserState(userId), userId);
7023                        if (ai != null) {
7024                            ai.packageName = resolveExternalPackageNameLPr(p);
7025                            list.add(ai);
7026                        }
7027                    }
7028                }
7029            }
7030
7031            return new ParceledListSlice<>(list);
7032        }
7033    }
7034
7035    @Override
7036    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
7037        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7038            return null;
7039        }
7040
7041        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
7042                "getEphemeralApplications");
7043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7044                true /* requireFullPermission */, false /* checkShell */,
7045                "getEphemeralApplications");
7046        synchronized (mPackages) {
7047            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
7048                    .getEphemeralApplicationsLPw(userId);
7049            if (ephemeralApps != null) {
7050                return new ParceledListSlice<>(ephemeralApps);
7051            }
7052        }
7053        return null;
7054    }
7055
7056    @Override
7057    public boolean isEphemeralApplication(String packageName, int userId) {
7058        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7059                true /* requireFullPermission */, false /* checkShell */,
7060                "isEphemeral");
7061        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7062            return false;
7063        }
7064
7065        if (!isCallerSameApp(packageName)) {
7066            return false;
7067        }
7068        synchronized (mPackages) {
7069            PackageParser.Package pkg = mPackages.get(packageName);
7070            if (pkg != null) {
7071                return pkg.applicationInfo.isEphemeralApp();
7072            }
7073        }
7074        return false;
7075    }
7076
7077    @Override
7078    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
7079        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7080            return null;
7081        }
7082
7083        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7084                true /* requireFullPermission */, false /* checkShell */,
7085                "getCookie");
7086        if (!isCallerSameApp(packageName)) {
7087            return null;
7088        }
7089        synchronized (mPackages) {
7090            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
7091                    packageName, userId);
7092        }
7093    }
7094
7095    @Override
7096    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
7097        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7098            return true;
7099        }
7100
7101        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7102                true /* requireFullPermission */, true /* checkShell */,
7103                "setCookie");
7104        if (!isCallerSameApp(packageName)) {
7105            return false;
7106        }
7107        synchronized (mPackages) {
7108            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
7109                    packageName, cookie, userId);
7110        }
7111    }
7112
7113    @Override
7114    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
7115        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7116            return null;
7117        }
7118
7119        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
7120                "getEphemeralApplicationIcon");
7121
7122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7123                true /* requireFullPermission */, false /* checkShell */,
7124                "getEphemeralApplicationIcon");
7125        synchronized (mPackages) {
7126            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
7127                    packageName, userId);
7128        }
7129    }
7130
7131    private boolean isCallerSameApp(String packageName) {
7132        PackageParser.Package pkg = mPackages.get(packageName);
7133        return pkg != null
7134                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7135    }
7136
7137    @Override
7138    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7139        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7140    }
7141
7142    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7143        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7144
7145        // reader
7146        synchronized (mPackages) {
7147            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7148            final int userId = UserHandle.getCallingUserId();
7149            while (i.hasNext()) {
7150                final PackageParser.Package p = i.next();
7151                if (p.applicationInfo == null) continue;
7152
7153                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7154                        && !p.applicationInfo.isDirectBootAware();
7155                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7156                        && p.applicationInfo.isDirectBootAware();
7157
7158                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7159                        && (!mSafeMode || isSystemApp(p))
7160                        && (matchesUnaware || matchesAware)) {
7161                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7162                    if (ps != null) {
7163                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7164                                ps.readUserState(userId), userId);
7165                        if (ai != null) {
7166                            finalList.add(ai);
7167                        }
7168                    }
7169                }
7170            }
7171        }
7172
7173        return finalList;
7174    }
7175
7176    @Override
7177    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7178        if (!sUserManager.exists(userId)) return null;
7179        flags = updateFlagsForComponent(flags, userId, name);
7180        // reader
7181        synchronized (mPackages) {
7182            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7183            PackageSetting ps = provider != null
7184                    ? mSettings.mPackages.get(provider.owner.packageName)
7185                    : null;
7186            return ps != null
7187                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7188                    ? PackageParser.generateProviderInfo(provider, flags,
7189                            ps.readUserState(userId), userId)
7190                    : null;
7191        }
7192    }
7193
7194    /**
7195     * @deprecated
7196     */
7197    @Deprecated
7198    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7199        // reader
7200        synchronized (mPackages) {
7201            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7202                    .entrySet().iterator();
7203            final int userId = UserHandle.getCallingUserId();
7204            while (i.hasNext()) {
7205                Map.Entry<String, PackageParser.Provider> entry = i.next();
7206                PackageParser.Provider p = entry.getValue();
7207                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7208
7209                if (ps != null && p.syncable
7210                        && (!mSafeMode || (p.info.applicationInfo.flags
7211                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7212                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7213                            ps.readUserState(userId), userId);
7214                    if (info != null) {
7215                        outNames.add(entry.getKey());
7216                        outInfo.add(info);
7217                    }
7218                }
7219            }
7220        }
7221    }
7222
7223    @Override
7224    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7225            int uid, int flags) {
7226        final int userId = processName != null ? UserHandle.getUserId(uid)
7227                : UserHandle.getCallingUserId();
7228        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7229        flags = updateFlagsForComponent(flags, userId, processName);
7230
7231        ArrayList<ProviderInfo> finalList = null;
7232        // reader
7233        synchronized (mPackages) {
7234            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7235            while (i.hasNext()) {
7236                final PackageParser.Provider p = i.next();
7237                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7238                if (ps != null && p.info.authority != null
7239                        && (processName == null
7240                                || (p.info.processName.equals(processName)
7241                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7242                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7243                    if (finalList == null) {
7244                        finalList = new ArrayList<ProviderInfo>(3);
7245                    }
7246                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7247                            ps.readUserState(userId), userId);
7248                    if (info != null) {
7249                        finalList.add(info);
7250                    }
7251                }
7252            }
7253        }
7254
7255        if (finalList != null) {
7256            Collections.sort(finalList, mProviderInitOrderSorter);
7257            return new ParceledListSlice<ProviderInfo>(finalList);
7258        }
7259
7260        return ParceledListSlice.emptyList();
7261    }
7262
7263    @Override
7264    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7265        // reader
7266        synchronized (mPackages) {
7267            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7268            return PackageParser.generateInstrumentationInfo(i, flags);
7269        }
7270    }
7271
7272    @Override
7273    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7274            String targetPackage, int flags) {
7275        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7276    }
7277
7278    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7279            int flags) {
7280        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7281
7282        // reader
7283        synchronized (mPackages) {
7284            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7285            while (i.hasNext()) {
7286                final PackageParser.Instrumentation p = i.next();
7287                if (targetPackage == null
7288                        || targetPackage.equals(p.info.targetPackage)) {
7289                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7290                            flags);
7291                    if (ii != null) {
7292                        finalList.add(ii);
7293                    }
7294                }
7295            }
7296        }
7297
7298        return finalList;
7299    }
7300
7301    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7302        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7303        if (overlays == null) {
7304            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7305            return;
7306        }
7307        for (PackageParser.Package opkg : overlays.values()) {
7308            // Not much to do if idmap fails: we already logged the error
7309            // and we certainly don't want to abort installation of pkg simply
7310            // because an overlay didn't fit properly. For these reasons,
7311            // ignore the return value of createIdmapForPackagePairLI.
7312            createIdmapForPackagePairLI(pkg, opkg);
7313        }
7314    }
7315
7316    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7317            PackageParser.Package opkg) {
7318        if (!opkg.mTrustedOverlay) {
7319            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7320                    opkg.baseCodePath + ": overlay not trusted");
7321            return false;
7322        }
7323        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7324        if (overlaySet == null) {
7325            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7326                    opkg.baseCodePath + " but target package has no known overlays");
7327            return false;
7328        }
7329        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7330        // TODO: generate idmap for split APKs
7331        try {
7332            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7333        } catch (InstallerException e) {
7334            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7335                    + opkg.baseCodePath);
7336            return false;
7337        }
7338        PackageParser.Package[] overlayArray =
7339            overlaySet.values().toArray(new PackageParser.Package[0]);
7340        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7341            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7342                return p1.mOverlayPriority - p2.mOverlayPriority;
7343            }
7344        };
7345        Arrays.sort(overlayArray, cmp);
7346
7347        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7348        int i = 0;
7349        for (PackageParser.Package p : overlayArray) {
7350            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7351        }
7352        return true;
7353    }
7354
7355    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7356        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7357        try {
7358            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7359        } finally {
7360            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7361        }
7362    }
7363
7364    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7365        final File[] files = dir.listFiles();
7366        if (ArrayUtils.isEmpty(files)) {
7367            Log.d(TAG, "No files in app dir " + dir);
7368            return;
7369        }
7370
7371        if (DEBUG_PACKAGE_SCANNING) {
7372            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7373                    + " flags=0x" + Integer.toHexString(parseFlags));
7374        }
7375        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7376                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7377
7378        // Submit files for parsing in parallel
7379        int fileCount = 0;
7380        for (File file : files) {
7381            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7382                    && !PackageInstallerService.isStageName(file.getName());
7383            if (!isPackage) {
7384                // Ignore entries which are not packages
7385                continue;
7386            }
7387            parallelPackageParser.submit(file, parseFlags);
7388            fileCount++;
7389        }
7390
7391        // Process results one by one
7392        for (; fileCount > 0; fileCount--) {
7393            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7394            Throwable throwable = parseResult.throwable;
7395            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7396
7397            if (throwable == null) {
7398                // Static shared libraries have synthetic package names
7399                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7400                    renameStaticSharedLibraryPackage(parseResult.pkg);
7401                }
7402                try {
7403                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7404                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7405                                currentTime, null);
7406                    }
7407                } catch (PackageManagerException e) {
7408                    errorCode = e.error;
7409                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7410                }
7411            } else if (throwable instanceof PackageParser.PackageParserException) {
7412                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7413                        throwable;
7414                errorCode = e.error;
7415                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7416            } else {
7417                throw new IllegalStateException("Unexpected exception occurred while parsing "
7418                        + parseResult.scanFile, throwable);
7419            }
7420
7421            // Delete invalid userdata apps
7422            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7423                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7424                logCriticalInfo(Log.WARN,
7425                        "Deleting invalid package at " + parseResult.scanFile);
7426                removeCodePathLI(parseResult.scanFile);
7427            }
7428        }
7429        parallelPackageParser.close();
7430    }
7431
7432    private static File getSettingsProblemFile() {
7433        File dataDir = Environment.getDataDirectory();
7434        File systemDir = new File(dataDir, "system");
7435        File fname = new File(systemDir, "uiderrors.txt");
7436        return fname;
7437    }
7438
7439    static void reportSettingsProblem(int priority, String msg) {
7440        logCriticalInfo(priority, msg);
7441    }
7442
7443    static void logCriticalInfo(int priority, String msg) {
7444        Slog.println(priority, TAG, msg);
7445        EventLogTags.writePmCriticalInfo(msg);
7446        try {
7447            File fname = getSettingsProblemFile();
7448            FileOutputStream out = new FileOutputStream(fname, true);
7449            PrintWriter pw = new FastPrintWriter(out);
7450            SimpleDateFormat formatter = new SimpleDateFormat();
7451            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7452            pw.println(dateString + ": " + msg);
7453            pw.close();
7454            FileUtils.setPermissions(
7455                    fname.toString(),
7456                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7457                    -1, -1);
7458        } catch (java.io.IOException e) {
7459        }
7460    }
7461
7462    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7463        if (srcFile.isDirectory()) {
7464            final File baseFile = new File(pkg.baseCodePath);
7465            long maxModifiedTime = baseFile.lastModified();
7466            if (pkg.splitCodePaths != null) {
7467                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7468                    final File splitFile = new File(pkg.splitCodePaths[i]);
7469                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7470                }
7471            }
7472            return maxModifiedTime;
7473        }
7474        return srcFile.lastModified();
7475    }
7476
7477    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7478            final int policyFlags) throws PackageManagerException {
7479        // When upgrading from pre-N MR1, verify the package time stamp using the package
7480        // directory and not the APK file.
7481        final long lastModifiedTime = mIsPreNMR1Upgrade
7482                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7483        if (ps != null
7484                && ps.codePath.equals(srcFile)
7485                && ps.timeStamp == lastModifiedTime
7486                && !isCompatSignatureUpdateNeeded(pkg)
7487                && !isRecoverSignatureUpdateNeeded(pkg)) {
7488            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7489            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7490            ArraySet<PublicKey> signingKs;
7491            synchronized (mPackages) {
7492                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7493            }
7494            if (ps.signatures.mSignatures != null
7495                    && ps.signatures.mSignatures.length != 0
7496                    && signingKs != null) {
7497                // Optimization: reuse the existing cached certificates
7498                // if the package appears to be unchanged.
7499                pkg.mSignatures = ps.signatures.mSignatures;
7500                pkg.mSigningKeys = signingKs;
7501                return;
7502            }
7503
7504            Slog.w(TAG, "PackageSetting for " + ps.name
7505                    + " is missing signatures.  Collecting certs again to recover them.");
7506        } else {
7507            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7508        }
7509
7510        try {
7511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7512            PackageParser.collectCertificates(pkg, policyFlags);
7513        } catch (PackageParserException e) {
7514            throw PackageManagerException.from(e);
7515        } finally {
7516            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7517        }
7518    }
7519
7520    /**
7521     *  Traces a package scan.
7522     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7523     */
7524    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7525            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7526        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7527        try {
7528            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7529        } finally {
7530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7531        }
7532    }
7533
7534    /**
7535     *  Scans a package and returns the newly parsed package.
7536     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7537     */
7538    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7539            long currentTime, UserHandle user) throws PackageManagerException {
7540        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7541        PackageParser pp = new PackageParser();
7542        pp.setSeparateProcesses(mSeparateProcesses);
7543        pp.setOnlyCoreApps(mOnlyCore);
7544        pp.setDisplayMetrics(mMetrics);
7545
7546        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7547            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7548        }
7549
7550        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7551        final PackageParser.Package pkg;
7552        try {
7553            pkg = pp.parsePackage(scanFile, parseFlags);
7554        } catch (PackageParserException e) {
7555            throw PackageManagerException.from(e);
7556        } finally {
7557            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7558        }
7559
7560        // Static shared libraries have synthetic package names
7561        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7562            renameStaticSharedLibraryPackage(pkg);
7563        }
7564
7565        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7566    }
7567
7568    /**
7569     *  Scans a package and returns the newly parsed package.
7570     *  @throws PackageManagerException on a parse error.
7571     */
7572    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7573            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7574            throws PackageManagerException {
7575        // If the package has children and this is the first dive in the function
7576        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7577        // packages (parent and children) would be successfully scanned before the
7578        // actual scan since scanning mutates internal state and we want to atomically
7579        // install the package and its children.
7580        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7581            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7582                scanFlags |= SCAN_CHECK_ONLY;
7583            }
7584        } else {
7585            scanFlags &= ~SCAN_CHECK_ONLY;
7586        }
7587
7588        // Scan the parent
7589        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7590                scanFlags, currentTime, user);
7591
7592        // Scan the children
7593        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7594        for (int i = 0; i < childCount; i++) {
7595            PackageParser.Package childPackage = pkg.childPackages.get(i);
7596            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7597                    currentTime, user);
7598        }
7599
7600
7601        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7602            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7603        }
7604
7605        return scannedPkg;
7606    }
7607
7608    /**
7609     *  Scans a package and returns the newly parsed package.
7610     *  @throws PackageManagerException on a parse error.
7611     */
7612    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7613            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7614            throws PackageManagerException {
7615        PackageSetting ps = null;
7616        PackageSetting updatedPkg;
7617        // reader
7618        synchronized (mPackages) {
7619            // Look to see if we already know about this package.
7620            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7621            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7622                // This package has been renamed to its original name.  Let's
7623                // use that.
7624                ps = mSettings.getPackageLPr(oldName);
7625            }
7626            // If there was no original package, see one for the real package name.
7627            if (ps == null) {
7628                ps = mSettings.getPackageLPr(pkg.packageName);
7629            }
7630            // Check to see if this package could be hiding/updating a system
7631            // package.  Must look for it either under the original or real
7632            // package name depending on our state.
7633            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7634            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7635
7636            // If this is a package we don't know about on the system partition, we
7637            // may need to remove disabled child packages on the system partition
7638            // or may need to not add child packages if the parent apk is updated
7639            // on the data partition and no longer defines this child package.
7640            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7641                // If this is a parent package for an updated system app and this system
7642                // app got an OTA update which no longer defines some of the child packages
7643                // we have to prune them from the disabled system packages.
7644                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7645                if (disabledPs != null) {
7646                    final int scannedChildCount = (pkg.childPackages != null)
7647                            ? pkg.childPackages.size() : 0;
7648                    final int disabledChildCount = disabledPs.childPackageNames != null
7649                            ? disabledPs.childPackageNames.size() : 0;
7650                    for (int i = 0; i < disabledChildCount; i++) {
7651                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7652                        boolean disabledPackageAvailable = false;
7653                        for (int j = 0; j < scannedChildCount; j++) {
7654                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7655                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7656                                disabledPackageAvailable = true;
7657                                break;
7658                            }
7659                         }
7660                         if (!disabledPackageAvailable) {
7661                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7662                         }
7663                    }
7664                }
7665            }
7666        }
7667
7668        boolean updatedPkgBetter = false;
7669        // First check if this is a system package that may involve an update
7670        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7671            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7672            // it needs to drop FLAG_PRIVILEGED.
7673            if (locationIsPrivileged(scanFile)) {
7674                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7675            } else {
7676                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7677            }
7678
7679            if (ps != null && !ps.codePath.equals(scanFile)) {
7680                // The path has changed from what was last scanned...  check the
7681                // version of the new path against what we have stored to determine
7682                // what to do.
7683                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7684                if (pkg.mVersionCode <= ps.versionCode) {
7685                    // The system package has been updated and the code path does not match
7686                    // Ignore entry. Skip it.
7687                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7688                            + " ignored: updated version " + ps.versionCode
7689                            + " better than this " + pkg.mVersionCode);
7690                    if (!updatedPkg.codePath.equals(scanFile)) {
7691                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7692                                + ps.name + " changing from " + updatedPkg.codePathString
7693                                + " to " + scanFile);
7694                        updatedPkg.codePath = scanFile;
7695                        updatedPkg.codePathString = scanFile.toString();
7696                        updatedPkg.resourcePath = scanFile;
7697                        updatedPkg.resourcePathString = scanFile.toString();
7698                    }
7699                    updatedPkg.pkg = pkg;
7700                    updatedPkg.versionCode = pkg.mVersionCode;
7701
7702                    // Update the disabled system child packages to point to the package too.
7703                    final int childCount = updatedPkg.childPackageNames != null
7704                            ? updatedPkg.childPackageNames.size() : 0;
7705                    for (int i = 0; i < childCount; i++) {
7706                        String childPackageName = updatedPkg.childPackageNames.get(i);
7707                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7708                                childPackageName);
7709                        if (updatedChildPkg != null) {
7710                            updatedChildPkg.pkg = pkg;
7711                            updatedChildPkg.versionCode = pkg.mVersionCode;
7712                        }
7713                    }
7714
7715                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7716                            + scanFile + " ignored: updated version " + ps.versionCode
7717                            + " better than this " + pkg.mVersionCode);
7718                } else {
7719                    // The current app on the system partition is better than
7720                    // what we have updated to on the data partition; switch
7721                    // back to the system partition version.
7722                    // At this point, its safely assumed that package installation for
7723                    // apps in system partition will go through. If not there won't be a working
7724                    // version of the app
7725                    // writer
7726                    synchronized (mPackages) {
7727                        // Just remove the loaded entries from package lists.
7728                        mPackages.remove(ps.name);
7729                    }
7730
7731                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7732                            + " reverting from " + ps.codePathString
7733                            + ": new version " + pkg.mVersionCode
7734                            + " better than installed " + ps.versionCode);
7735
7736                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7737                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7738                    synchronized (mInstallLock) {
7739                        args.cleanUpResourcesLI();
7740                    }
7741                    synchronized (mPackages) {
7742                        mSettings.enableSystemPackageLPw(ps.name);
7743                    }
7744                    updatedPkgBetter = true;
7745                }
7746            }
7747        }
7748
7749        if (updatedPkg != null) {
7750            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7751            // initially
7752            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7753
7754            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7755            // flag set initially
7756            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7757                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7758            }
7759        }
7760
7761        // Verify certificates against what was last scanned
7762        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7763
7764        /*
7765         * A new system app appeared, but we already had a non-system one of the
7766         * same name installed earlier.
7767         */
7768        boolean shouldHideSystemApp = false;
7769        if (updatedPkg == null && ps != null
7770                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7771            /*
7772             * Check to make sure the signatures match first. If they don't,
7773             * wipe the installed application and its data.
7774             */
7775            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7776                    != PackageManager.SIGNATURE_MATCH) {
7777                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7778                        + " signatures don't match existing userdata copy; removing");
7779                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7780                        "scanPackageInternalLI")) {
7781                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7782                }
7783                ps = null;
7784            } else {
7785                /*
7786                 * If the newly-added system app is an older version than the
7787                 * already installed version, hide it. It will be scanned later
7788                 * and re-added like an update.
7789                 */
7790                if (pkg.mVersionCode <= ps.versionCode) {
7791                    shouldHideSystemApp = true;
7792                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7793                            + " but new version " + pkg.mVersionCode + " better than installed "
7794                            + ps.versionCode + "; hiding system");
7795                } else {
7796                    /*
7797                     * The newly found system app is a newer version that the
7798                     * one previously installed. Simply remove the
7799                     * already-installed application and replace it with our own
7800                     * while keeping the application data.
7801                     */
7802                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7803                            + " reverting from " + ps.codePathString + ": new version "
7804                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7805                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7806                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7807                    synchronized (mInstallLock) {
7808                        args.cleanUpResourcesLI();
7809                    }
7810                }
7811            }
7812        }
7813
7814        // The apk is forward locked (not public) if its code and resources
7815        // are kept in different files. (except for app in either system or
7816        // vendor path).
7817        // TODO grab this value from PackageSettings
7818        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7819            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7820                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7821            }
7822        }
7823
7824        // TODO: extend to support forward-locked splits
7825        String resourcePath = null;
7826        String baseResourcePath = null;
7827        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7828            if (ps != null && ps.resourcePathString != null) {
7829                resourcePath = ps.resourcePathString;
7830                baseResourcePath = ps.resourcePathString;
7831            } else {
7832                // Should not happen at all. Just log an error.
7833                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7834            }
7835        } else {
7836            resourcePath = pkg.codePath;
7837            baseResourcePath = pkg.baseCodePath;
7838        }
7839
7840        // Set application objects path explicitly.
7841        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7842        pkg.setApplicationInfoCodePath(pkg.codePath);
7843        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7844        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7845        pkg.setApplicationInfoResourcePath(resourcePath);
7846        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7847        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7848
7849        // Note that we invoke the following method only if we are about to unpack an application
7850        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7851                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7852
7853        /*
7854         * If the system app should be overridden by a previously installed
7855         * data, hide the system app now and let the /data/app scan pick it up
7856         * again.
7857         */
7858        if (shouldHideSystemApp) {
7859            synchronized (mPackages) {
7860                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7861            }
7862        }
7863
7864        return scannedPkg;
7865    }
7866
7867    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7868        // Derive the new package synthetic package name
7869        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7870                + pkg.staticSharedLibVersion);
7871    }
7872
7873    private static String fixProcessName(String defProcessName,
7874            String processName) {
7875        if (processName == null) {
7876            return defProcessName;
7877        }
7878        return processName;
7879    }
7880
7881    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7882            throws PackageManagerException {
7883        if (pkgSetting.signatures.mSignatures != null) {
7884            // Already existing package. Make sure signatures match
7885            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7886                    == PackageManager.SIGNATURE_MATCH;
7887            if (!match) {
7888                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7889                        == PackageManager.SIGNATURE_MATCH;
7890            }
7891            if (!match) {
7892                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7893                        == PackageManager.SIGNATURE_MATCH;
7894            }
7895            if (!match) {
7896                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7897                        + pkg.packageName + " signatures do not match the "
7898                        + "previously installed version; ignoring!");
7899            }
7900        }
7901
7902        // Check for shared user signatures
7903        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7904            // Already existing package. Make sure signatures match
7905            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7906                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7907            if (!match) {
7908                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7909                        == PackageManager.SIGNATURE_MATCH;
7910            }
7911            if (!match) {
7912                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7913                        == PackageManager.SIGNATURE_MATCH;
7914            }
7915            if (!match) {
7916                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7917                        "Package " + pkg.packageName
7918                        + " has no signatures that match those in shared user "
7919                        + pkgSetting.sharedUser.name + "; ignoring!");
7920            }
7921        }
7922    }
7923
7924    /**
7925     * Enforces that only the system UID or root's UID can call a method exposed
7926     * via Binder.
7927     *
7928     * @param message used as message if SecurityException is thrown
7929     * @throws SecurityException if the caller is not system or root
7930     */
7931    private static final void enforceSystemOrRoot(String message) {
7932        final int uid = Binder.getCallingUid();
7933        if (uid != Process.SYSTEM_UID && uid != 0) {
7934            throw new SecurityException(message);
7935        }
7936    }
7937
7938    @Override
7939    public void performFstrimIfNeeded() {
7940        enforceSystemOrRoot("Only the system can request fstrim");
7941
7942        // Before everything else, see whether we need to fstrim.
7943        try {
7944            IStorageManager sm = PackageHelper.getStorageManager();
7945            if (sm != null) {
7946                boolean doTrim = false;
7947                final long interval = android.provider.Settings.Global.getLong(
7948                        mContext.getContentResolver(),
7949                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7950                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7951                if (interval > 0) {
7952                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7953                    if (timeSinceLast > interval) {
7954                        doTrim = true;
7955                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7956                                + "; running immediately");
7957                    }
7958                }
7959                if (doTrim) {
7960                    final boolean dexOptDialogShown;
7961                    synchronized (mPackages) {
7962                        dexOptDialogShown = mDexOptDialogShown;
7963                    }
7964                    if (!isFirstBoot() && dexOptDialogShown) {
7965                        try {
7966                            ActivityManager.getService().showBootMessage(
7967                                    mContext.getResources().getString(
7968                                            R.string.android_upgrading_fstrim), true);
7969                        } catch (RemoteException e) {
7970                        }
7971                    }
7972                    sm.runMaintenance();
7973                }
7974            } else {
7975                Slog.e(TAG, "storageManager service unavailable!");
7976            }
7977        } catch (RemoteException e) {
7978            // Can't happen; StorageManagerService is local
7979        }
7980    }
7981
7982    @Override
7983    public void updatePackagesIfNeeded() {
7984        enforceSystemOrRoot("Only the system can request package update");
7985
7986        // We need to re-extract after an OTA.
7987        boolean causeUpgrade = isUpgrade();
7988
7989        // First boot or factory reset.
7990        // Note: we also handle devices that are upgrading to N right now as if it is their
7991        //       first boot, as they do not have profile data.
7992        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7993
7994        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7995        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7996
7997        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7998            return;
7999        }
8000
8001        List<PackageParser.Package> pkgs;
8002        synchronized (mPackages) {
8003            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8004        }
8005
8006        final long startTime = System.nanoTime();
8007        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8008                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8009
8010        final int elapsedTimeSeconds =
8011                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8012
8013        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8014        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8015        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8016        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8017        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8018    }
8019
8020    /**
8021     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8022     * containing statistics about the invocation. The array consists of three elements,
8023     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8024     * and {@code numberOfPackagesFailed}.
8025     */
8026    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8027            String compilerFilter) {
8028
8029        int numberOfPackagesVisited = 0;
8030        int numberOfPackagesOptimized = 0;
8031        int numberOfPackagesSkipped = 0;
8032        int numberOfPackagesFailed = 0;
8033        final int numberOfPackagesToDexopt = pkgs.size();
8034
8035        for (PackageParser.Package pkg : pkgs) {
8036            numberOfPackagesVisited++;
8037
8038            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8039                if (DEBUG_DEXOPT) {
8040                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8041                }
8042                numberOfPackagesSkipped++;
8043                continue;
8044            }
8045
8046            if (DEBUG_DEXOPT) {
8047                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8048                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8049            }
8050
8051            if (showDialog) {
8052                try {
8053                    ActivityManager.getService().showBootMessage(
8054                            mContext.getResources().getString(R.string.android_upgrading_apk,
8055                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8056                } catch (RemoteException e) {
8057                }
8058                synchronized (mPackages) {
8059                    mDexOptDialogShown = true;
8060                }
8061            }
8062
8063            // If the OTA updates a system app which was previously preopted to a non-preopted state
8064            // the app might end up being verified at runtime. That's because by default the apps
8065            // are verify-profile but for preopted apps there's no profile.
8066            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8067            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8068            // filter (by default interpret-only).
8069            // Note that at this stage unused apps are already filtered.
8070            if (isSystemApp(pkg) &&
8071                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8072                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8073                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8074            }
8075
8076            // checkProfiles is false to avoid merging profiles during boot which
8077            // might interfere with background compilation (b/28612421).
8078            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8079            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8080            // trade-off worth doing to save boot time work.
8081            int dexOptStatus = performDexOptTraced(pkg.packageName,
8082                    false /* checkProfiles */,
8083                    compilerFilter,
8084                    false /* force */);
8085            switch (dexOptStatus) {
8086                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8087                    numberOfPackagesOptimized++;
8088                    break;
8089                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8090                    numberOfPackagesSkipped++;
8091                    break;
8092                case PackageDexOptimizer.DEX_OPT_FAILED:
8093                    numberOfPackagesFailed++;
8094                    break;
8095                default:
8096                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8097                    break;
8098            }
8099        }
8100
8101        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8102                numberOfPackagesFailed };
8103    }
8104
8105    @Override
8106    public void notifyPackageUse(String packageName, int reason) {
8107        synchronized (mPackages) {
8108            PackageParser.Package p = mPackages.get(packageName);
8109            if (p == null) {
8110                return;
8111            }
8112            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8113        }
8114    }
8115
8116    @Override
8117    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8118        int userId = UserHandle.getCallingUserId();
8119        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8120        if (ai == null) {
8121            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8122                + loadingPackageName + ", user=" + userId);
8123            return;
8124        }
8125        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8126    }
8127
8128    // TODO: this is not used nor needed. Delete it.
8129    @Override
8130    public boolean performDexOptIfNeeded(String packageName) {
8131        int dexOptStatus = performDexOptTraced(packageName,
8132                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8133        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8134    }
8135
8136    @Override
8137    public boolean performDexOpt(String packageName,
8138            boolean checkProfiles, int compileReason, boolean force) {
8139        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8140                getCompilerFilterForReason(compileReason), force);
8141        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8142    }
8143
8144    @Override
8145    public boolean performDexOptMode(String packageName,
8146            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8147        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8148                targetCompilerFilter, force);
8149        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8150    }
8151
8152    private int performDexOptTraced(String packageName,
8153                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8154        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8155        try {
8156            return performDexOptInternal(packageName, checkProfiles,
8157                    targetCompilerFilter, force);
8158        } finally {
8159            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8160        }
8161    }
8162
8163    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8164    // if the package can now be considered up to date for the given filter.
8165    private int performDexOptInternal(String packageName,
8166                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8167        PackageParser.Package p;
8168        synchronized (mPackages) {
8169            p = mPackages.get(packageName);
8170            if (p == null) {
8171                // Package could not be found. Report failure.
8172                return PackageDexOptimizer.DEX_OPT_FAILED;
8173            }
8174            mPackageUsage.maybeWriteAsync(mPackages);
8175            mCompilerStats.maybeWriteAsync();
8176        }
8177        long callingId = Binder.clearCallingIdentity();
8178        try {
8179            synchronized (mInstallLock) {
8180                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8181                        targetCompilerFilter, force);
8182            }
8183        } finally {
8184            Binder.restoreCallingIdentity(callingId);
8185        }
8186    }
8187
8188    public ArraySet<String> getOptimizablePackages() {
8189        ArraySet<String> pkgs = new ArraySet<String>();
8190        synchronized (mPackages) {
8191            for (PackageParser.Package p : mPackages.values()) {
8192                if (PackageDexOptimizer.canOptimizePackage(p)) {
8193                    pkgs.add(p.packageName);
8194                }
8195            }
8196        }
8197        return pkgs;
8198    }
8199
8200    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8201            boolean checkProfiles, String targetCompilerFilter,
8202            boolean force) {
8203        // Select the dex optimizer based on the force parameter.
8204        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8205        //       allocate an object here.
8206        PackageDexOptimizer pdo = force
8207                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8208                : mPackageDexOptimizer;
8209
8210        // Optimize all dependencies first. Note: we ignore the return value and march on
8211        // on errors.
8212        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8213        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8214        if (!deps.isEmpty()) {
8215            for (PackageParser.Package depPackage : deps) {
8216                // TODO: Analyze and investigate if we (should) profile libraries.
8217                // Currently this will do a full compilation of the library by default.
8218                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8219                        false /* checkProfiles */,
8220                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8221                        getOrCreateCompilerPackageStats(depPackage));
8222            }
8223        }
8224        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8225                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8226    }
8227
8228    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8229        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8230                || p.usesStaticLibraries != null) {
8231            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8232            Set<String> collectedNames = new HashSet<>();
8233            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8234
8235            retValue.remove(p);
8236
8237            return retValue;
8238        } else {
8239            return Collections.emptyList();
8240        }
8241    }
8242
8243    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8244            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8245        if (!collectedNames.contains(p.packageName)) {
8246            collectedNames.add(p.packageName);
8247            collected.add(p);
8248
8249            if (p.usesLibraries != null) {
8250                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8251                        null, collected, collectedNames);
8252            }
8253            if (p.usesOptionalLibraries != null) {
8254                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8255                        null, collected, collectedNames);
8256            }
8257            if (p.usesStaticLibraries != null) {
8258                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8259                        p.usesStaticLibrariesVersions, collected, collectedNames);
8260            }
8261        }
8262    }
8263
8264    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8265            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8266        final int libNameCount = libs.size();
8267        for (int i = 0; i < libNameCount; i++) {
8268            String libName = libs.get(i);
8269            int version = (versions != null && versions.length == libNameCount)
8270                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8271            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8272            if (libPkg != null) {
8273                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8274            }
8275        }
8276    }
8277
8278    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8279        synchronized (mPackages) {
8280            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8281            if (libEntry != null) {
8282                return mPackages.get(libEntry.apk);
8283            }
8284            return null;
8285        }
8286    }
8287
8288    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8289        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8290        if (versionedLib == null) {
8291            return null;
8292        }
8293        return versionedLib.get(version);
8294    }
8295
8296    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8297        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8298                pkg.staticSharedLibName);
8299        if (versionedLib == null) {
8300            return null;
8301        }
8302        int previousLibVersion = -1;
8303        final int versionCount = versionedLib.size();
8304        for (int i = 0; i < versionCount; i++) {
8305            final int libVersion = versionedLib.keyAt(i);
8306            if (libVersion < pkg.staticSharedLibVersion) {
8307                previousLibVersion = Math.max(previousLibVersion, libVersion);
8308            }
8309        }
8310        if (previousLibVersion >= 0) {
8311            return versionedLib.get(previousLibVersion);
8312        }
8313        return null;
8314    }
8315
8316    public void shutdown() {
8317        mPackageUsage.writeNow(mPackages);
8318        mCompilerStats.writeNow();
8319    }
8320
8321    @Override
8322    public void dumpProfiles(String packageName) {
8323        PackageParser.Package pkg;
8324        synchronized (mPackages) {
8325            pkg = mPackages.get(packageName);
8326            if (pkg == null) {
8327                throw new IllegalArgumentException("Unknown package: " + packageName);
8328            }
8329        }
8330        /* Only the shell, root, or the app user should be able to dump profiles. */
8331        int callingUid = Binder.getCallingUid();
8332        if (callingUid != Process.SHELL_UID &&
8333            callingUid != Process.ROOT_UID &&
8334            callingUid != pkg.applicationInfo.uid) {
8335            throw new SecurityException("dumpProfiles");
8336        }
8337
8338        synchronized (mInstallLock) {
8339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8340            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8341            try {
8342                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8343                String codePaths = TextUtils.join(";", allCodePaths);
8344                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8345            } catch (InstallerException e) {
8346                Slog.w(TAG, "Failed to dump profiles", e);
8347            }
8348            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8349        }
8350    }
8351
8352    @Override
8353    public void forceDexOpt(String packageName) {
8354        enforceSystemOrRoot("forceDexOpt");
8355
8356        PackageParser.Package pkg;
8357        synchronized (mPackages) {
8358            pkg = mPackages.get(packageName);
8359            if (pkg == null) {
8360                throw new IllegalArgumentException("Unknown package: " + packageName);
8361            }
8362        }
8363
8364        synchronized (mInstallLock) {
8365            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8366
8367            // Whoever is calling forceDexOpt wants a fully compiled package.
8368            // Don't use profiles since that may cause compilation to be skipped.
8369            final int res = performDexOptInternalWithDependenciesLI(pkg,
8370                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8371                    true /* force */);
8372
8373            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8374            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8375                throw new IllegalStateException("Failed to dexopt: " + res);
8376            }
8377        }
8378    }
8379
8380    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8381        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8382            Slog.w(TAG, "Unable to update from " + oldPkg.name
8383                    + " to " + newPkg.packageName
8384                    + ": old package not in system partition");
8385            return false;
8386        } else if (mPackages.get(oldPkg.name) != null) {
8387            Slog.w(TAG, "Unable to update from " + oldPkg.name
8388                    + " to " + newPkg.packageName
8389                    + ": old package still exists");
8390            return false;
8391        }
8392        return true;
8393    }
8394
8395    void removeCodePathLI(File codePath) {
8396        if (codePath.isDirectory()) {
8397            try {
8398                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8399            } catch (InstallerException e) {
8400                Slog.w(TAG, "Failed to remove code path", e);
8401            }
8402        } else {
8403            codePath.delete();
8404        }
8405    }
8406
8407    private int[] resolveUserIds(int userId) {
8408        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8409    }
8410
8411    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8412        if (pkg == null) {
8413            Slog.wtf(TAG, "Package was null!", new Throwable());
8414            return;
8415        }
8416        clearAppDataLeafLIF(pkg, userId, flags);
8417        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8418        for (int i = 0; i < childCount; i++) {
8419            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8420        }
8421    }
8422
8423    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8424        final PackageSetting ps;
8425        synchronized (mPackages) {
8426            ps = mSettings.mPackages.get(pkg.packageName);
8427        }
8428        for (int realUserId : resolveUserIds(userId)) {
8429            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8430            try {
8431                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8432                        ceDataInode);
8433            } catch (InstallerException e) {
8434                Slog.w(TAG, String.valueOf(e));
8435            }
8436        }
8437    }
8438
8439    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8440        if (pkg == null) {
8441            Slog.wtf(TAG, "Package was null!", new Throwable());
8442            return;
8443        }
8444        destroyAppDataLeafLIF(pkg, userId, flags);
8445        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8446        for (int i = 0; i < childCount; i++) {
8447            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8448        }
8449    }
8450
8451    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8452        final PackageSetting ps;
8453        synchronized (mPackages) {
8454            ps = mSettings.mPackages.get(pkg.packageName);
8455        }
8456        for (int realUserId : resolveUserIds(userId)) {
8457            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8458            try {
8459                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8460                        ceDataInode);
8461            } catch (InstallerException e) {
8462                Slog.w(TAG, String.valueOf(e));
8463            }
8464        }
8465    }
8466
8467    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8468        if (pkg == null) {
8469            Slog.wtf(TAG, "Package was null!", new Throwable());
8470            return;
8471        }
8472        destroyAppProfilesLeafLIF(pkg);
8473        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8474        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8475        for (int i = 0; i < childCount; i++) {
8476            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8477            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8478                    true /* removeBaseMarker */);
8479        }
8480    }
8481
8482    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8483            boolean removeBaseMarker) {
8484        if (pkg.isForwardLocked()) {
8485            return;
8486        }
8487
8488        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8489            try {
8490                path = PackageManagerServiceUtils.realpath(new File(path));
8491            } catch (IOException e) {
8492                // TODO: Should we return early here ?
8493                Slog.w(TAG, "Failed to get canonical path", e);
8494                continue;
8495            }
8496
8497            final String useMarker = path.replace('/', '@');
8498            for (int realUserId : resolveUserIds(userId)) {
8499                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8500                if (removeBaseMarker) {
8501                    File foreignUseMark = new File(profileDir, useMarker);
8502                    if (foreignUseMark.exists()) {
8503                        if (!foreignUseMark.delete()) {
8504                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8505                                    + pkg.packageName);
8506                        }
8507                    }
8508                }
8509
8510                File[] markers = profileDir.listFiles();
8511                if (markers != null) {
8512                    final String searchString = "@" + pkg.packageName + "@";
8513                    // We also delete all markers that contain the package name we're
8514                    // uninstalling. These are associated with secondary dex-files belonging
8515                    // to the package. Reconstructing the path of these dex files is messy
8516                    // in general.
8517                    for (File marker : markers) {
8518                        if (marker.getName().indexOf(searchString) > 0) {
8519                            if (!marker.delete()) {
8520                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8521                                    + pkg.packageName);
8522                            }
8523                        }
8524                    }
8525                }
8526            }
8527        }
8528    }
8529
8530    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8531        try {
8532            mInstaller.destroyAppProfiles(pkg.packageName);
8533        } catch (InstallerException e) {
8534            Slog.w(TAG, String.valueOf(e));
8535        }
8536    }
8537
8538    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8539        if (pkg == null) {
8540            Slog.wtf(TAG, "Package was null!", new Throwable());
8541            return;
8542        }
8543        clearAppProfilesLeafLIF(pkg);
8544        // We don't remove the base foreign use marker when clearing profiles because
8545        // we will rename it when the app is updated. Unlike the actual profile contents,
8546        // the foreign use marker is good across installs.
8547        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8548        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8549        for (int i = 0; i < childCount; i++) {
8550            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8551        }
8552    }
8553
8554    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8555        try {
8556            mInstaller.clearAppProfiles(pkg.packageName);
8557        } catch (InstallerException e) {
8558            Slog.w(TAG, String.valueOf(e));
8559        }
8560    }
8561
8562    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8563            long lastUpdateTime) {
8564        // Set parent install/update time
8565        PackageSetting ps = (PackageSetting) pkg.mExtras;
8566        if (ps != null) {
8567            ps.firstInstallTime = firstInstallTime;
8568            ps.lastUpdateTime = lastUpdateTime;
8569        }
8570        // Set children install/update time
8571        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8572        for (int i = 0; i < childCount; i++) {
8573            PackageParser.Package childPkg = pkg.childPackages.get(i);
8574            ps = (PackageSetting) childPkg.mExtras;
8575            if (ps != null) {
8576                ps.firstInstallTime = firstInstallTime;
8577                ps.lastUpdateTime = lastUpdateTime;
8578            }
8579        }
8580    }
8581
8582    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8583            PackageParser.Package changingLib) {
8584        if (file.path != null) {
8585            usesLibraryFiles.add(file.path);
8586            return;
8587        }
8588        PackageParser.Package p = mPackages.get(file.apk);
8589        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8590            // If we are doing this while in the middle of updating a library apk,
8591            // then we need to make sure to use that new apk for determining the
8592            // dependencies here.  (We haven't yet finished committing the new apk
8593            // to the package manager state.)
8594            if (p == null || p.packageName.equals(changingLib.packageName)) {
8595                p = changingLib;
8596            }
8597        }
8598        if (p != null) {
8599            usesLibraryFiles.addAll(p.getAllCodePaths());
8600        }
8601    }
8602
8603    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8604            PackageParser.Package changingLib) throws PackageManagerException {
8605        if (pkg == null) {
8606            return;
8607        }
8608        ArraySet<String> usesLibraryFiles = null;
8609        if (pkg.usesLibraries != null) {
8610            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8611                    null, null, pkg.packageName, changingLib, true, null);
8612        }
8613        if (pkg.usesStaticLibraries != null) {
8614            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8615                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8616                    pkg.packageName, changingLib, true, usesLibraryFiles);
8617        }
8618        if (pkg.usesOptionalLibraries != null) {
8619            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8620                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8621        }
8622        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8623            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8624        } else {
8625            pkg.usesLibraryFiles = null;
8626        }
8627    }
8628
8629    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8630            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8631            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8632            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8633            throws PackageManagerException {
8634        final int libCount = requestedLibraries.size();
8635        for (int i = 0; i < libCount; i++) {
8636            final String libName = requestedLibraries.get(i);
8637            final int libVersion = requiredVersions != null ? requiredVersions[i]
8638                    : SharedLibraryInfo.VERSION_UNDEFINED;
8639            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8640            if (libEntry == null) {
8641                if (required) {
8642                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8643                            "Package " + packageName + " requires unavailable shared library "
8644                                    + libName + "; failing!");
8645                } else {
8646                    Slog.w(TAG, "Package " + packageName
8647                            + " desires unavailable shared library "
8648                            + libName + "; ignoring!");
8649                }
8650            } else {
8651                if (requiredVersions != null && requiredCertDigests != null) {
8652                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8653                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8654                            "Package " + packageName + " requires unavailable static shared"
8655                                    + " library " + libName + " version "
8656                                    + libEntry.info.getVersion() + "; failing!");
8657                    }
8658
8659                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8660                    if (libPkg == null) {
8661                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8662                                "Package " + packageName + " requires unavailable static shared"
8663                                        + " library; failing!");
8664                    }
8665
8666                    String expectedCertDigest = requiredCertDigests[i];
8667                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8668                                libPkg.mSignatures[0]);
8669                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8670                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8671                                "Package " + packageName + " requires differently signed" +
8672                                        " static shared library; failing!");
8673                    }
8674                }
8675
8676                if (outUsedLibraries == null) {
8677                    outUsedLibraries = new ArraySet<>();
8678                }
8679                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8680            }
8681        }
8682        return outUsedLibraries;
8683    }
8684
8685    private static boolean hasString(List<String> list, List<String> which) {
8686        if (list == null) {
8687            return false;
8688        }
8689        for (int i=list.size()-1; i>=0; i--) {
8690            for (int j=which.size()-1; j>=0; j--) {
8691                if (which.get(j).equals(list.get(i))) {
8692                    return true;
8693                }
8694            }
8695        }
8696        return false;
8697    }
8698
8699    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8700            PackageParser.Package changingPkg) {
8701        ArrayList<PackageParser.Package> res = null;
8702        for (PackageParser.Package pkg : mPackages.values()) {
8703            if (changingPkg != null
8704                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8705                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8706                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8707                            changingPkg.staticSharedLibName)) {
8708                return null;
8709            }
8710            if (res == null) {
8711                res = new ArrayList<>();
8712            }
8713            res.add(pkg);
8714            try {
8715                updateSharedLibrariesLPr(pkg, changingPkg);
8716            } catch (PackageManagerException e) {
8717                // If a system app update or an app and a required lib missing we
8718                // delete the package and for updated system apps keep the data as
8719                // it is better for the user to reinstall than to be in an limbo
8720                // state. Also libs disappearing under an app should never happen
8721                // - just in case.
8722                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8723                    final int flags = pkg.isUpdatedSystemApp()
8724                            ? PackageManager.DELETE_KEEP_DATA : 0;
8725                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8726                            flags , null, true, null);
8727                }
8728                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8729            }
8730        }
8731        return res;
8732    }
8733
8734    /**
8735     * Derive the value of the {@code cpuAbiOverride} based on the provided
8736     * value and an optional stored value from the package settings.
8737     */
8738    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8739        String cpuAbiOverride = null;
8740
8741        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8742            cpuAbiOverride = null;
8743        } else if (abiOverride != null) {
8744            cpuAbiOverride = abiOverride;
8745        } else if (settings != null) {
8746            cpuAbiOverride = settings.cpuAbiOverrideString;
8747        }
8748
8749        return cpuAbiOverride;
8750    }
8751
8752    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8753            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8754                    throws PackageManagerException {
8755        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8756        // If the package has children and this is the first dive in the function
8757        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8758        // whether all packages (parent and children) would be successfully scanned
8759        // before the actual scan since scanning mutates internal state and we want
8760        // to atomically install the package and its children.
8761        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8762            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8763                scanFlags |= SCAN_CHECK_ONLY;
8764            }
8765        } else {
8766            scanFlags &= ~SCAN_CHECK_ONLY;
8767        }
8768
8769        final PackageParser.Package scannedPkg;
8770        try {
8771            // Scan the parent
8772            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8773            // Scan the children
8774            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8775            for (int i = 0; i < childCount; i++) {
8776                PackageParser.Package childPkg = pkg.childPackages.get(i);
8777                scanPackageLI(childPkg, policyFlags,
8778                        scanFlags, currentTime, user);
8779            }
8780        } finally {
8781            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8782        }
8783
8784        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8785            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8786        }
8787
8788        return scannedPkg;
8789    }
8790
8791    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8792            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8793        boolean success = false;
8794        try {
8795            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8796                    currentTime, user);
8797            success = true;
8798            return res;
8799        } finally {
8800            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8801                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8802                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8803                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8804                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8805            }
8806        }
8807    }
8808
8809    /**
8810     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8811     */
8812    private static boolean apkHasCode(String fileName) {
8813        StrictJarFile jarFile = null;
8814        try {
8815            jarFile = new StrictJarFile(fileName,
8816                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8817            return jarFile.findEntry("classes.dex") != null;
8818        } catch (IOException ignore) {
8819        } finally {
8820            try {
8821                if (jarFile != null) {
8822                    jarFile.close();
8823                }
8824            } catch (IOException ignore) {}
8825        }
8826        return false;
8827    }
8828
8829    /**
8830     * Enforces code policy for the package. This ensures that if an APK has
8831     * declared hasCode="true" in its manifest that the APK actually contains
8832     * code.
8833     *
8834     * @throws PackageManagerException If bytecode could not be found when it should exist
8835     */
8836    private static void assertCodePolicy(PackageParser.Package pkg)
8837            throws PackageManagerException {
8838        final boolean shouldHaveCode =
8839                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8840        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8841            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8842                    "Package " + pkg.baseCodePath + " code is missing");
8843        }
8844
8845        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8846            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8847                final boolean splitShouldHaveCode =
8848                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8849                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8850                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8851                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8852                }
8853            }
8854        }
8855    }
8856
8857    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8858            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8859                    throws PackageManagerException {
8860        if (DEBUG_PACKAGE_SCANNING) {
8861            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8862                Log.d(TAG, "Scanning package " + pkg.packageName);
8863        }
8864
8865        applyPolicy(pkg, policyFlags);
8866
8867        assertPackageIsValid(pkg, policyFlags, scanFlags);
8868
8869        // Initialize package source and resource directories
8870        final File scanFile = new File(pkg.codePath);
8871        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8872        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8873
8874        SharedUserSetting suid = null;
8875        PackageSetting pkgSetting = null;
8876
8877        // Getting the package setting may have a side-effect, so if we
8878        // are only checking if scan would succeed, stash a copy of the
8879        // old setting to restore at the end.
8880        PackageSetting nonMutatedPs = null;
8881
8882        // We keep references to the derived CPU Abis from settings in oder to reuse
8883        // them in the case where we're not upgrading or booting for the first time.
8884        String primaryCpuAbiFromSettings = null;
8885        String secondaryCpuAbiFromSettings = null;
8886
8887        // writer
8888        synchronized (mPackages) {
8889            if (pkg.mSharedUserId != null) {
8890                // SIDE EFFECTS; may potentially allocate a new shared user
8891                suid = mSettings.getSharedUserLPw(
8892                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8893                if (DEBUG_PACKAGE_SCANNING) {
8894                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8895                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8896                                + "): packages=" + suid.packages);
8897                }
8898            }
8899
8900            // Check if we are renaming from an original package name.
8901            PackageSetting origPackage = null;
8902            String realName = null;
8903            if (pkg.mOriginalPackages != null) {
8904                // This package may need to be renamed to a previously
8905                // installed name.  Let's check on that...
8906                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8907                if (pkg.mOriginalPackages.contains(renamed)) {
8908                    // This package had originally been installed as the
8909                    // original name, and we have already taken care of
8910                    // transitioning to the new one.  Just update the new
8911                    // one to continue using the old name.
8912                    realName = pkg.mRealPackage;
8913                    if (!pkg.packageName.equals(renamed)) {
8914                        // Callers into this function may have already taken
8915                        // care of renaming the package; only do it here if
8916                        // it is not already done.
8917                        pkg.setPackageName(renamed);
8918                    }
8919                } else {
8920                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8921                        if ((origPackage = mSettings.getPackageLPr(
8922                                pkg.mOriginalPackages.get(i))) != null) {
8923                            // We do have the package already installed under its
8924                            // original name...  should we use it?
8925                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8926                                // New package is not compatible with original.
8927                                origPackage = null;
8928                                continue;
8929                            } else if (origPackage.sharedUser != null) {
8930                                // Make sure uid is compatible between packages.
8931                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8932                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8933                                            + " to " + pkg.packageName + ": old uid "
8934                                            + origPackage.sharedUser.name
8935                                            + " differs from " + pkg.mSharedUserId);
8936                                    origPackage = null;
8937                                    continue;
8938                                }
8939                                // TODO: Add case when shared user id is added [b/28144775]
8940                            } else {
8941                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8942                                        + pkg.packageName + " to old name " + origPackage.name);
8943                            }
8944                            break;
8945                        }
8946                    }
8947                }
8948            }
8949
8950            if (mTransferedPackages.contains(pkg.packageName)) {
8951                Slog.w(TAG, "Package " + pkg.packageName
8952                        + " was transferred to another, but its .apk remains");
8953            }
8954
8955            // See comments in nonMutatedPs declaration
8956            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8957                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8958                if (foundPs != null) {
8959                    nonMutatedPs = new PackageSetting(foundPs);
8960                }
8961            }
8962
8963            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8964                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8965                if (foundPs != null) {
8966                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8967                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8968                }
8969            }
8970
8971            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8972            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8973                PackageManagerService.reportSettingsProblem(Log.WARN,
8974                        "Package " + pkg.packageName + " shared user changed from "
8975                                + (pkgSetting.sharedUser != null
8976                                        ? pkgSetting.sharedUser.name : "<nothing>")
8977                                + " to "
8978                                + (suid != null ? suid.name : "<nothing>")
8979                                + "; replacing with new");
8980                pkgSetting = null;
8981            }
8982            final PackageSetting oldPkgSetting =
8983                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8984            final PackageSetting disabledPkgSetting =
8985                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8986
8987            String[] usesStaticLibraries = null;
8988            if (pkg.usesStaticLibraries != null) {
8989                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
8990                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
8991            }
8992
8993            if (pkgSetting == null) {
8994                final String parentPackageName = (pkg.parentPackage != null)
8995                        ? pkg.parentPackage.packageName : null;
8996
8997                // REMOVE SharedUserSetting from method; update in a separate call
8998                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8999                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9000                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9001                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9002                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9003                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9004                        UserManagerService.getInstance(), usesStaticLibraries,
9005                        pkg.usesStaticLibrariesVersions);
9006                // SIDE EFFECTS; updates system state; move elsewhere
9007                if (origPackage != null) {
9008                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9009                }
9010                mSettings.addUserToSettingLPw(pkgSetting);
9011            } else {
9012                // REMOVE SharedUserSetting from method; update in a separate call.
9013                //
9014                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9015                // secondaryCpuAbi are not known at this point so we always update them
9016                // to null here, only to reset them at a later point.
9017                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9018                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9019                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9020                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9021                        UserManagerService.getInstance(), usesStaticLibraries,
9022                        pkg.usesStaticLibrariesVersions);
9023            }
9024            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9025            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9026
9027            // SIDE EFFECTS; modifies system state; move elsewhere
9028            if (pkgSetting.origPackage != null) {
9029                // If we are first transitioning from an original package,
9030                // fix up the new package's name now.  We need to do this after
9031                // looking up the package under its new name, so getPackageLP
9032                // can take care of fiddling things correctly.
9033                pkg.setPackageName(origPackage.name);
9034
9035                // File a report about this.
9036                String msg = "New package " + pkgSetting.realName
9037                        + " renamed to replace old package " + pkgSetting.name;
9038                reportSettingsProblem(Log.WARN, msg);
9039
9040                // Make a note of it.
9041                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9042                    mTransferedPackages.add(origPackage.name);
9043                }
9044
9045                // No longer need to retain this.
9046                pkgSetting.origPackage = null;
9047            }
9048
9049            // SIDE EFFECTS; modifies system state; move elsewhere
9050            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9051                // Make a note of it.
9052                mTransferedPackages.add(pkg.packageName);
9053            }
9054
9055            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9056                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9057            }
9058
9059            if ((scanFlags & SCAN_BOOTING) == 0
9060                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9061                // Check all shared libraries and map to their actual file path.
9062                // We only do this here for apps not on a system dir, because those
9063                // are the only ones that can fail an install due to this.  We
9064                // will take care of the system apps by updating all of their
9065                // library paths after the scan is done. Also during the initial
9066                // scan don't update any libs as we do this wholesale after all
9067                // apps are scanned to avoid dependency based scanning.
9068                updateSharedLibrariesLPr(pkg, null);
9069            }
9070
9071            if (mFoundPolicyFile) {
9072                SELinuxMMAC.assignSeinfoValue(pkg);
9073            }
9074
9075            pkg.applicationInfo.uid = pkgSetting.appId;
9076            pkg.mExtras = pkgSetting;
9077
9078
9079            // Static shared libs have same package with different versions where
9080            // we internally use a synthetic package name to allow multiple versions
9081            // of the same package, therefore we need to compare signatures against
9082            // the package setting for the latest library version.
9083            PackageSetting signatureCheckPs = pkgSetting;
9084            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9085                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9086                if (libraryEntry != null) {
9087                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9088                }
9089            }
9090
9091            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9092                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9093                    // We just determined the app is signed correctly, so bring
9094                    // over the latest parsed certs.
9095                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9096                } else {
9097                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9098                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9099                                "Package " + pkg.packageName + " upgrade keys do not match the "
9100                                + "previously installed version");
9101                    } else {
9102                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9103                        String msg = "System package " + pkg.packageName
9104                                + " signature changed; retaining data.";
9105                        reportSettingsProblem(Log.WARN, msg);
9106                    }
9107                }
9108            } else {
9109                try {
9110                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9111                    verifySignaturesLP(signatureCheckPs, pkg);
9112                    // We just determined the app is signed correctly, so bring
9113                    // over the latest parsed certs.
9114                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9115                } catch (PackageManagerException e) {
9116                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9117                        throw e;
9118                    }
9119                    // The signature has changed, but this package is in the system
9120                    // image...  let's recover!
9121                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9122                    // However...  if this package is part of a shared user, but it
9123                    // doesn't match the signature of the shared user, let's fail.
9124                    // What this means is that you can't change the signatures
9125                    // associated with an overall shared user, which doesn't seem all
9126                    // that unreasonable.
9127                    if (signatureCheckPs.sharedUser != null) {
9128                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9129                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9130                            throw new PackageManagerException(
9131                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9132                                    "Signature mismatch for shared user: "
9133                                            + pkgSetting.sharedUser);
9134                        }
9135                    }
9136                    // File a report about this.
9137                    String msg = "System package " + pkg.packageName
9138                            + " signature changed; retaining data.";
9139                    reportSettingsProblem(Log.WARN, msg);
9140                }
9141            }
9142
9143            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9144                // This package wants to adopt ownership of permissions from
9145                // another package.
9146                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9147                    final String origName = pkg.mAdoptPermissions.get(i);
9148                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9149                    if (orig != null) {
9150                        if (verifyPackageUpdateLPr(orig, pkg)) {
9151                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9152                                    + pkg.packageName);
9153                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9154                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9155                        }
9156                    }
9157                }
9158            }
9159        }
9160
9161        pkg.applicationInfo.processName = fixProcessName(
9162                pkg.applicationInfo.packageName,
9163                pkg.applicationInfo.processName);
9164
9165        if (pkg != mPlatformPackage) {
9166            // Get all of our default paths setup
9167            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9168        }
9169
9170        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9171
9172        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9173            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9174                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9175                derivePackageAbi(
9176                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9177                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9178
9179                // Some system apps still use directory structure for native libraries
9180                // in which case we might end up not detecting abi solely based on apk
9181                // structure. Try to detect abi based on directory structure.
9182                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9183                        pkg.applicationInfo.primaryCpuAbi == null) {
9184                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9185                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9186                }
9187            } else {
9188                // This is not a first boot or an upgrade, don't bother deriving the
9189                // ABI during the scan. Instead, trust the value that was stored in the
9190                // package setting.
9191                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9192                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9193
9194                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9195
9196                if (DEBUG_ABI_SELECTION) {
9197                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9198                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9199                        pkg.applicationInfo.secondaryCpuAbi);
9200                }
9201            }
9202        } else {
9203            if ((scanFlags & SCAN_MOVE) != 0) {
9204                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9205                // but we already have this packages package info in the PackageSetting. We just
9206                // use that and derive the native library path based on the new codepath.
9207                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9208                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9209            }
9210
9211            // Set native library paths again. For moves, the path will be updated based on the
9212            // ABIs we've determined above. For non-moves, the path will be updated based on the
9213            // ABIs we determined during compilation, but the path will depend on the final
9214            // package path (after the rename away from the stage path).
9215            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9216        }
9217
9218        // This is a special case for the "system" package, where the ABI is
9219        // dictated by the zygote configuration (and init.rc). We should keep track
9220        // of this ABI so that we can deal with "normal" applications that run under
9221        // the same UID correctly.
9222        if (mPlatformPackage == pkg) {
9223            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9224                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9225        }
9226
9227        // If there's a mismatch between the abi-override in the package setting
9228        // and the abiOverride specified for the install. Warn about this because we
9229        // would've already compiled the app without taking the package setting into
9230        // account.
9231        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9232            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9233                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9234                        " for package " + pkg.packageName);
9235            }
9236        }
9237
9238        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9239        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9240        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9241
9242        // Copy the derived override back to the parsed package, so that we can
9243        // update the package settings accordingly.
9244        pkg.cpuAbiOverride = cpuAbiOverride;
9245
9246        if (DEBUG_ABI_SELECTION) {
9247            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9248                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9249                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9250        }
9251
9252        // Push the derived path down into PackageSettings so we know what to
9253        // clean up at uninstall time.
9254        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9255
9256        if (DEBUG_ABI_SELECTION) {
9257            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9258                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9259                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9260        }
9261
9262        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9263        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9264            // We don't do this here during boot because we can do it all
9265            // at once after scanning all existing packages.
9266            //
9267            // We also do this *before* we perform dexopt on this package, so that
9268            // we can avoid redundant dexopts, and also to make sure we've got the
9269            // code and package path correct.
9270            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9271        }
9272
9273        if (mFactoryTest && pkg.requestedPermissions.contains(
9274                android.Manifest.permission.FACTORY_TEST)) {
9275            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9276        }
9277
9278        if (isSystemApp(pkg)) {
9279            pkgSetting.isOrphaned = true;
9280        }
9281
9282        // Take care of first install / last update times.
9283        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9284        if (currentTime != 0) {
9285            if (pkgSetting.firstInstallTime == 0) {
9286                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9287            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9288                pkgSetting.lastUpdateTime = currentTime;
9289            }
9290        } else if (pkgSetting.firstInstallTime == 0) {
9291            // We need *something*.  Take time time stamp of the file.
9292            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9293        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9294            if (scanFileTime != pkgSetting.timeStamp) {
9295                // A package on the system image has changed; consider this
9296                // to be an update.
9297                pkgSetting.lastUpdateTime = scanFileTime;
9298            }
9299        }
9300        pkgSetting.setTimeStamp(scanFileTime);
9301
9302        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9303            if (nonMutatedPs != null) {
9304                synchronized (mPackages) {
9305                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9306                }
9307            }
9308        } else {
9309            // Modify state for the given package setting
9310            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9311                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9312            if (isEphemeral(pkg)) {
9313                final int userId = user == null ? 0 : user.getIdentifier();
9314                mEphemeralApplicationRegistry.addEphemeralAppLPw(userId, pkgSetting.appId);
9315            }
9316        }
9317        return pkg;
9318    }
9319
9320    /**
9321     * Applies policy to the parsed package based upon the given policy flags.
9322     * Ensures the package is in a good state.
9323     * <p>
9324     * Implementation detail: This method must NOT have any side effect. It would
9325     * ideally be static, but, it requires locks to read system state.
9326     */
9327    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9328        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9329            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9330            if (pkg.applicationInfo.isDirectBootAware()) {
9331                // we're direct boot aware; set for all components
9332                for (PackageParser.Service s : pkg.services) {
9333                    s.info.encryptionAware = s.info.directBootAware = true;
9334                }
9335                for (PackageParser.Provider p : pkg.providers) {
9336                    p.info.encryptionAware = p.info.directBootAware = true;
9337                }
9338                for (PackageParser.Activity a : pkg.activities) {
9339                    a.info.encryptionAware = a.info.directBootAware = true;
9340                }
9341                for (PackageParser.Activity r : pkg.receivers) {
9342                    r.info.encryptionAware = r.info.directBootAware = true;
9343                }
9344            }
9345        } else {
9346            // Only allow system apps to be flagged as core apps.
9347            pkg.coreApp = false;
9348            // clear flags not applicable to regular apps
9349            pkg.applicationInfo.privateFlags &=
9350                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9351            pkg.applicationInfo.privateFlags &=
9352                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9353        }
9354        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9355
9356        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9357            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9358        }
9359
9360        if (!isSystemApp(pkg)) {
9361            // Only system apps can use these features.
9362            pkg.mOriginalPackages = null;
9363            pkg.mRealPackage = null;
9364            pkg.mAdoptPermissions = null;
9365        }
9366    }
9367
9368    /**
9369     * Asserts the parsed package is valid according to the given policy. If the
9370     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9371     * <p>
9372     * Implementation detail: This method must NOT have any side effects. It would
9373     * ideally be static, but, it requires locks to read system state.
9374     *
9375     * @throws PackageManagerException If the package fails any of the validation checks
9376     */
9377    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9378            throws PackageManagerException {
9379        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9380            assertCodePolicy(pkg);
9381        }
9382
9383        if (pkg.applicationInfo.getCodePath() == null ||
9384                pkg.applicationInfo.getResourcePath() == null) {
9385            // Bail out. The resource and code paths haven't been set.
9386            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9387                    "Code and resource paths haven't been set correctly");
9388        }
9389
9390        // Make sure we're not adding any bogus keyset info
9391        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9392        ksms.assertScannedPackageValid(pkg);
9393
9394        synchronized (mPackages) {
9395            // The special "android" package can only be defined once
9396            if (pkg.packageName.equals("android")) {
9397                if (mAndroidApplication != null) {
9398                    Slog.w(TAG, "*************************************************");
9399                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9400                    Slog.w(TAG, " codePath=" + pkg.codePath);
9401                    Slog.w(TAG, "*************************************************");
9402                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9403                            "Core android package being redefined.  Skipping.");
9404                }
9405            }
9406
9407            // A package name must be unique; don't allow duplicates
9408            if (mPackages.containsKey(pkg.packageName)) {
9409                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9410                        "Application package " + pkg.packageName
9411                        + " already installed.  Skipping duplicate.");
9412            }
9413
9414            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9415                // Static libs have a synthetic package name containing the version
9416                // but we still want the base name to be unique.
9417                if (mPackages.containsKey(pkg.manifestPackageName)) {
9418                    throw new PackageManagerException(
9419                            "Duplicate static shared lib provider package");
9420                }
9421
9422                // Static shared libraries should have at least O target SDK
9423                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9424                    throw new PackageManagerException(
9425                            "Packages declaring static-shared libs must target O SDK or higher");
9426                }
9427
9428                // Package declaring static a shared lib cannot be ephemeral
9429                if (pkg.applicationInfo.isEphemeralApp()) {
9430                    throw new PackageManagerException(
9431                            "Packages declaring static-shared libs cannot be ephemeral");
9432                }
9433
9434                // Package declaring static a shared lib cannot be renamed since the package
9435                // name is synthetic and apps can't code around package manager internals.
9436                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9437                    throw new PackageManagerException(
9438                            "Packages declaring static-shared libs cannot be renamed");
9439                }
9440
9441                // Package declaring static a shared lib cannot declare child packages
9442                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9443                    throw new PackageManagerException(
9444                            "Packages declaring static-shared libs cannot have child packages");
9445                }
9446
9447                // Package declaring static a shared lib cannot declare dynamic libs
9448                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9449                    throw new PackageManagerException(
9450                            "Packages declaring static-shared libs cannot declare dynamic libs");
9451                }
9452
9453                // Package declaring static a shared lib cannot declare shared users
9454                if (pkg.mSharedUserId != null) {
9455                    throw new PackageManagerException(
9456                            "Packages declaring static-shared libs cannot declare shared users");
9457                }
9458
9459                // Static shared libs cannot declare activities
9460                if (!pkg.activities.isEmpty()) {
9461                    throw new PackageManagerException(
9462                            "Static shared libs cannot declare activities");
9463                }
9464
9465                // Static shared libs cannot declare services
9466                if (!pkg.services.isEmpty()) {
9467                    throw new PackageManagerException(
9468                            "Static shared libs cannot declare services");
9469                }
9470
9471                // Static shared libs cannot declare providers
9472                if (!pkg.providers.isEmpty()) {
9473                    throw new PackageManagerException(
9474                            "Static shared libs cannot declare content providers");
9475                }
9476
9477                // Static shared libs cannot declare receivers
9478                if (!pkg.receivers.isEmpty()) {
9479                    throw new PackageManagerException(
9480                            "Static shared libs cannot declare broadcast receivers");
9481                }
9482
9483                // Static shared libs cannot declare permission groups
9484                if (!pkg.permissionGroups.isEmpty()) {
9485                    throw new PackageManagerException(
9486                            "Static shared libs cannot declare permission groups");
9487                }
9488
9489                // Static shared libs cannot declare permissions
9490                if (!pkg.permissions.isEmpty()) {
9491                    throw new PackageManagerException(
9492                            "Static shared libs cannot declare permissions");
9493                }
9494
9495                // Static shared libs cannot declare protected broadcasts
9496                if (pkg.protectedBroadcasts != null) {
9497                    throw new PackageManagerException(
9498                            "Static shared libs cannot declare protected broadcasts");
9499                }
9500
9501                // Static shared libs cannot be overlay targets
9502                if (pkg.mOverlayTarget != null) {
9503                    throw new PackageManagerException(
9504                            "Static shared libs cannot be overlay targets");
9505                }
9506
9507                // The version codes must be ordered as lib versions
9508                int minVersionCode = Integer.MIN_VALUE;
9509                int maxVersionCode = Integer.MAX_VALUE;
9510
9511                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9512                        pkg.staticSharedLibName);
9513                if (versionedLib != null) {
9514                    final int versionCount = versionedLib.size();
9515                    for (int i = 0; i < versionCount; i++) {
9516                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9517                        // TODO: We will change version code to long, so in the new API it is long
9518                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9519                                .getVersionCode();
9520                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9521                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9522                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9523                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9524                        } else {
9525                            minVersionCode = maxVersionCode = libVersionCode;
9526                            break;
9527                        }
9528                    }
9529                }
9530                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9531                    throw new PackageManagerException("Static shared"
9532                            + " lib version codes must be ordered as lib versions");
9533                }
9534            }
9535
9536            // Only privileged apps and updated privileged apps can add child packages.
9537            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9538                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9539                    throw new PackageManagerException("Only privileged apps can add child "
9540                            + "packages. Ignoring package " + pkg.packageName);
9541                }
9542                final int childCount = pkg.childPackages.size();
9543                for (int i = 0; i < childCount; i++) {
9544                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9545                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9546                            childPkg.packageName)) {
9547                        throw new PackageManagerException("Can't override child of "
9548                                + "another disabled app. Ignoring package " + pkg.packageName);
9549                    }
9550                }
9551            }
9552
9553            // If we're only installing presumed-existing packages, require that the
9554            // scanned APK is both already known and at the path previously established
9555            // for it.  Previously unknown packages we pick up normally, but if we have an
9556            // a priori expectation about this package's install presence, enforce it.
9557            // With a singular exception for new system packages. When an OTA contains
9558            // a new system package, we allow the codepath to change from a system location
9559            // to the user-installed location. If we don't allow this change, any newer,
9560            // user-installed version of the application will be ignored.
9561            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9562                if (mExpectingBetter.containsKey(pkg.packageName)) {
9563                    logCriticalInfo(Log.WARN,
9564                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9565                } else {
9566                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9567                    if (known != null) {
9568                        if (DEBUG_PACKAGE_SCANNING) {
9569                            Log.d(TAG, "Examining " + pkg.codePath
9570                                    + " and requiring known paths " + known.codePathString
9571                                    + " & " + known.resourcePathString);
9572                        }
9573                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9574                                || !pkg.applicationInfo.getResourcePath().equals(
9575                                        known.resourcePathString)) {
9576                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9577                                    "Application package " + pkg.packageName
9578                                    + " found at " + pkg.applicationInfo.getCodePath()
9579                                    + " but expected at " + known.codePathString
9580                                    + "; ignoring.");
9581                        }
9582                    }
9583                }
9584            }
9585
9586            // Verify that this new package doesn't have any content providers
9587            // that conflict with existing packages.  Only do this if the
9588            // package isn't already installed, since we don't want to break
9589            // things that are installed.
9590            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9591                final int N = pkg.providers.size();
9592                int i;
9593                for (i=0; i<N; i++) {
9594                    PackageParser.Provider p = pkg.providers.get(i);
9595                    if (p.info.authority != null) {
9596                        String names[] = p.info.authority.split(";");
9597                        for (int j = 0; j < names.length; j++) {
9598                            if (mProvidersByAuthority.containsKey(names[j])) {
9599                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9600                                final String otherPackageName =
9601                                        ((other != null && other.getComponentName() != null) ?
9602                                                other.getComponentName().getPackageName() : "?");
9603                                throw new PackageManagerException(
9604                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9605                                        "Can't install because provider name " + names[j]
9606                                                + " (in package " + pkg.applicationInfo.packageName
9607                                                + ") is already used by " + otherPackageName);
9608                            }
9609                        }
9610                    }
9611                }
9612            }
9613        }
9614    }
9615
9616    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9617            int type, String declaringPackageName, int declaringVersionCode) {
9618        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9619        if (versionedLib == null) {
9620            versionedLib = new SparseArray<>();
9621            mSharedLibraries.put(name, versionedLib);
9622            if (type == SharedLibraryInfo.TYPE_STATIC) {
9623                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9624            }
9625        } else if (versionedLib.indexOfKey(version) >= 0) {
9626            return false;
9627        }
9628        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9629                version, type, declaringPackageName, declaringVersionCode);
9630        versionedLib.put(version, libEntry);
9631        return true;
9632    }
9633
9634    private boolean removeSharedLibraryLPw(String name, int version) {
9635        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9636        if (versionedLib == null) {
9637            return false;
9638        }
9639        final int libIdx = versionedLib.indexOfKey(version);
9640        if (libIdx < 0) {
9641            return false;
9642        }
9643        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9644        versionedLib.remove(version);
9645        if (versionedLib.size() <= 0) {
9646            mSharedLibraries.remove(name);
9647            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9648                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9649                        .getPackageName());
9650            }
9651        }
9652        return true;
9653    }
9654
9655    /**
9656     * Adds a scanned package to the system. When this method is finished, the package will
9657     * be available for query, resolution, etc...
9658     */
9659    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9660            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9661        final String pkgName = pkg.packageName;
9662        if (mCustomResolverComponentName != null &&
9663                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9664            setUpCustomResolverActivity(pkg);
9665        }
9666
9667        if (pkg.packageName.equals("android")) {
9668            synchronized (mPackages) {
9669                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9670                    // Set up information for our fall-back user intent resolution activity.
9671                    mPlatformPackage = pkg;
9672                    pkg.mVersionCode = mSdkVersion;
9673                    mAndroidApplication = pkg.applicationInfo;
9674
9675                    if (!mResolverReplaced) {
9676                        mResolveActivity.applicationInfo = mAndroidApplication;
9677                        mResolveActivity.name = ResolverActivity.class.getName();
9678                        mResolveActivity.packageName = mAndroidApplication.packageName;
9679                        mResolveActivity.processName = "system:ui";
9680                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9681                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9682                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9683                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9684                        mResolveActivity.exported = true;
9685                        mResolveActivity.enabled = true;
9686                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9687                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9688                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9689                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9690                                | ActivityInfo.CONFIG_ORIENTATION
9691                                | ActivityInfo.CONFIG_KEYBOARD
9692                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9693                        mResolveInfo.activityInfo = mResolveActivity;
9694                        mResolveInfo.priority = 0;
9695                        mResolveInfo.preferredOrder = 0;
9696                        mResolveInfo.match = 0;
9697                        mResolveComponentName = new ComponentName(
9698                                mAndroidApplication.packageName, mResolveActivity.name);
9699                    }
9700                }
9701            }
9702        }
9703
9704        ArrayList<PackageParser.Package> clientLibPkgs = null;
9705        // writer
9706        synchronized (mPackages) {
9707            boolean hasStaticSharedLibs = false;
9708
9709            // Any app can add new static shared libraries
9710            if (pkg.staticSharedLibName != null) {
9711                // Static shared libs don't allow renaming as they have synthetic package
9712                // names to allow install of multiple versions, so use name from manifest.
9713                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9714                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9715                        pkg.manifestPackageName, pkg.mVersionCode)) {
9716                    hasStaticSharedLibs = true;
9717                } else {
9718                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9719                                + pkg.staticSharedLibName + " already exists; skipping");
9720                }
9721                // Static shared libs cannot be updated once installed since they
9722                // use synthetic package name which includes the version code, so
9723                // not need to update other packages's shared lib dependencies.
9724            }
9725
9726            if (!hasStaticSharedLibs
9727                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9728                // Only system apps can add new dynamic shared libraries.
9729                if (pkg.libraryNames != null) {
9730                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9731                        String name = pkg.libraryNames.get(i);
9732                        boolean allowed = false;
9733                        if (pkg.isUpdatedSystemApp()) {
9734                            // New library entries can only be added through the
9735                            // system image.  This is important to get rid of a lot
9736                            // of nasty edge cases: for example if we allowed a non-
9737                            // system update of the app to add a library, then uninstalling
9738                            // the update would make the library go away, and assumptions
9739                            // we made such as through app install filtering would now
9740                            // have allowed apps on the device which aren't compatible
9741                            // with it.  Better to just have the restriction here, be
9742                            // conservative, and create many fewer cases that can negatively
9743                            // impact the user experience.
9744                            final PackageSetting sysPs = mSettings
9745                                    .getDisabledSystemPkgLPr(pkg.packageName);
9746                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9747                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9748                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9749                                        allowed = true;
9750                                        break;
9751                                    }
9752                                }
9753                            }
9754                        } else {
9755                            allowed = true;
9756                        }
9757                        if (allowed) {
9758                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9759                                    SharedLibraryInfo.VERSION_UNDEFINED,
9760                                    SharedLibraryInfo.TYPE_DYNAMIC,
9761                                    pkg.packageName, pkg.mVersionCode)) {
9762                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9763                                        + name + " already exists; skipping");
9764                            }
9765                        } else {
9766                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9767                                    + name + " that is not declared on system image; skipping");
9768                        }
9769                    }
9770
9771                    if ((scanFlags & SCAN_BOOTING) == 0) {
9772                        // If we are not booting, we need to update any applications
9773                        // that are clients of our shared library.  If we are booting,
9774                        // this will all be done once the scan is complete.
9775                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9776                    }
9777                }
9778            }
9779        }
9780
9781        if ((scanFlags & SCAN_BOOTING) != 0) {
9782            // No apps can run during boot scan, so they don't need to be frozen
9783        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9784            // Caller asked to not kill app, so it's probably not frozen
9785        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9786            // Caller asked us to ignore frozen check for some reason; they
9787            // probably didn't know the package name
9788        } else {
9789            // We're doing major surgery on this package, so it better be frozen
9790            // right now to keep it from launching
9791            checkPackageFrozen(pkgName);
9792        }
9793
9794        // Also need to kill any apps that are dependent on the library.
9795        if (clientLibPkgs != null) {
9796            for (int i=0; i<clientLibPkgs.size(); i++) {
9797                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9798                killApplication(clientPkg.applicationInfo.packageName,
9799                        clientPkg.applicationInfo.uid, "update lib");
9800            }
9801        }
9802
9803        // writer
9804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9805
9806        boolean createIdmapFailed = false;
9807        synchronized (mPackages) {
9808            // We don't expect installation to fail beyond this point
9809
9810            if (pkgSetting.pkg != null) {
9811                // Note that |user| might be null during the initial boot scan. If a codePath
9812                // for an app has changed during a boot scan, it's due to an app update that's
9813                // part of the system partition and marker changes must be applied to all users.
9814                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9815                final int[] userIds = resolveUserIds(userId);
9816                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9817            }
9818
9819            // Add the new setting to mSettings
9820            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9821            // Add the new setting to mPackages
9822            mPackages.put(pkg.applicationInfo.packageName, pkg);
9823            // Make sure we don't accidentally delete its data.
9824            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9825            while (iter.hasNext()) {
9826                PackageCleanItem item = iter.next();
9827                if (pkgName.equals(item.packageName)) {
9828                    iter.remove();
9829                }
9830            }
9831
9832            // Add the package's KeySets to the global KeySetManagerService
9833            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9834            ksms.addScannedPackageLPw(pkg);
9835
9836            int N = pkg.providers.size();
9837            StringBuilder r = null;
9838            int i;
9839            for (i=0; i<N; i++) {
9840                PackageParser.Provider p = pkg.providers.get(i);
9841                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9842                        p.info.processName);
9843                mProviders.addProvider(p);
9844                p.syncable = p.info.isSyncable;
9845                if (p.info.authority != null) {
9846                    String names[] = p.info.authority.split(";");
9847                    p.info.authority = null;
9848                    for (int j = 0; j < names.length; j++) {
9849                        if (j == 1 && p.syncable) {
9850                            // We only want the first authority for a provider to possibly be
9851                            // syncable, so if we already added this provider using a different
9852                            // authority clear the syncable flag. We copy the provider before
9853                            // changing it because the mProviders object contains a reference
9854                            // to a provider that we don't want to change.
9855                            // Only do this for the second authority since the resulting provider
9856                            // object can be the same for all future authorities for this provider.
9857                            p = new PackageParser.Provider(p);
9858                            p.syncable = false;
9859                        }
9860                        if (!mProvidersByAuthority.containsKey(names[j])) {
9861                            mProvidersByAuthority.put(names[j], p);
9862                            if (p.info.authority == null) {
9863                                p.info.authority = names[j];
9864                            } else {
9865                                p.info.authority = p.info.authority + ";" + names[j];
9866                            }
9867                            if (DEBUG_PACKAGE_SCANNING) {
9868                                if (chatty)
9869                                    Log.d(TAG, "Registered content provider: " + names[j]
9870                                            + ", className = " + p.info.name + ", isSyncable = "
9871                                            + p.info.isSyncable);
9872                            }
9873                        } else {
9874                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9875                            Slog.w(TAG, "Skipping provider name " + names[j] +
9876                                    " (in package " + pkg.applicationInfo.packageName +
9877                                    "): name already used by "
9878                                    + ((other != null && other.getComponentName() != null)
9879                                            ? other.getComponentName().getPackageName() : "?"));
9880                        }
9881                    }
9882                }
9883                if (chatty) {
9884                    if (r == null) {
9885                        r = new StringBuilder(256);
9886                    } else {
9887                        r.append(' ');
9888                    }
9889                    r.append(p.info.name);
9890                }
9891            }
9892            if (r != null) {
9893                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9894            }
9895
9896            N = pkg.services.size();
9897            r = null;
9898            for (i=0; i<N; i++) {
9899                PackageParser.Service s = pkg.services.get(i);
9900                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9901                        s.info.processName);
9902                mServices.addService(s);
9903                if (chatty) {
9904                    if (r == null) {
9905                        r = new StringBuilder(256);
9906                    } else {
9907                        r.append(' ');
9908                    }
9909                    r.append(s.info.name);
9910                }
9911            }
9912            if (r != null) {
9913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9914            }
9915
9916            N = pkg.receivers.size();
9917            r = null;
9918            for (i=0; i<N; i++) {
9919                PackageParser.Activity a = pkg.receivers.get(i);
9920                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9921                        a.info.processName);
9922                mReceivers.addActivity(a, "receiver");
9923                if (chatty) {
9924                    if (r == null) {
9925                        r = new StringBuilder(256);
9926                    } else {
9927                        r.append(' ');
9928                    }
9929                    r.append(a.info.name);
9930                }
9931            }
9932            if (r != null) {
9933                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9934            }
9935
9936            N = pkg.activities.size();
9937            r = null;
9938            for (i=0; i<N; i++) {
9939                PackageParser.Activity a = pkg.activities.get(i);
9940                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9941                        a.info.processName);
9942                mActivities.addActivity(a, "activity");
9943                if (chatty) {
9944                    if (r == null) {
9945                        r = new StringBuilder(256);
9946                    } else {
9947                        r.append(' ');
9948                    }
9949                    r.append(a.info.name);
9950                }
9951            }
9952            if (r != null) {
9953                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9954            }
9955
9956            N = pkg.permissionGroups.size();
9957            r = null;
9958            for (i=0; i<N; i++) {
9959                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9960                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9961                final String curPackageName = cur == null ? null : cur.info.packageName;
9962                // Dont allow ephemeral apps to define new permission groups.
9963                if (pkg.applicationInfo.isEphemeralApp()) {
9964                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9965                            + pg.info.packageName
9966                            + " ignored: ephemeral apps cannot define new permission groups.");
9967                    continue;
9968                }
9969                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9970                if (cur == null || isPackageUpdate) {
9971                    mPermissionGroups.put(pg.info.name, pg);
9972                    if (chatty) {
9973                        if (r == null) {
9974                            r = new StringBuilder(256);
9975                        } else {
9976                            r.append(' ');
9977                        }
9978                        if (isPackageUpdate) {
9979                            r.append("UPD:");
9980                        }
9981                        r.append(pg.info.name);
9982                    }
9983                } else {
9984                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9985                            + pg.info.packageName + " ignored: original from "
9986                            + cur.info.packageName);
9987                    if (chatty) {
9988                        if (r == null) {
9989                            r = new StringBuilder(256);
9990                        } else {
9991                            r.append(' ');
9992                        }
9993                        r.append("DUP:");
9994                        r.append(pg.info.name);
9995                    }
9996                }
9997            }
9998            if (r != null) {
9999                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10000            }
10001
10002            N = pkg.permissions.size();
10003            r = null;
10004            for (i=0; i<N; i++) {
10005                PackageParser.Permission p = pkg.permissions.get(i);
10006
10007                // Dont allow ephemeral apps to define new permissions.
10008                if (pkg.applicationInfo.isEphemeralApp()) {
10009                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10010                            + p.info.packageName
10011                            + " ignored: ephemeral apps cannot define new permissions.");
10012                    continue;
10013                }
10014
10015                // Assume by default that we did not install this permission into the system.
10016                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10017
10018                // Now that permission groups have a special meaning, we ignore permission
10019                // groups for legacy apps to prevent unexpected behavior. In particular,
10020                // permissions for one app being granted to someone just becase they happen
10021                // to be in a group defined by another app (before this had no implications).
10022                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10023                    p.group = mPermissionGroups.get(p.info.group);
10024                    // Warn for a permission in an unknown group.
10025                    if (p.info.group != null && p.group == null) {
10026                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10027                                + p.info.packageName + " in an unknown group " + p.info.group);
10028                    }
10029                }
10030
10031                ArrayMap<String, BasePermission> permissionMap =
10032                        p.tree ? mSettings.mPermissionTrees
10033                                : mSettings.mPermissions;
10034                BasePermission bp = permissionMap.get(p.info.name);
10035
10036                // Allow system apps to redefine non-system permissions
10037                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10038                    final boolean currentOwnerIsSystem = (bp.perm != null
10039                            && isSystemApp(bp.perm.owner));
10040                    if (isSystemApp(p.owner)) {
10041                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10042                            // It's a built-in permission and no owner, take ownership now
10043                            bp.packageSetting = pkgSetting;
10044                            bp.perm = p;
10045                            bp.uid = pkg.applicationInfo.uid;
10046                            bp.sourcePackage = p.info.packageName;
10047                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10048                        } else if (!currentOwnerIsSystem) {
10049                            String msg = "New decl " + p.owner + " of permission  "
10050                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10051                            reportSettingsProblem(Log.WARN, msg);
10052                            bp = null;
10053                        }
10054                    }
10055                }
10056
10057                if (bp == null) {
10058                    bp = new BasePermission(p.info.name, p.info.packageName,
10059                            BasePermission.TYPE_NORMAL);
10060                    permissionMap.put(p.info.name, bp);
10061                }
10062
10063                if (bp.perm == null) {
10064                    if (bp.sourcePackage == null
10065                            || bp.sourcePackage.equals(p.info.packageName)) {
10066                        BasePermission tree = findPermissionTreeLP(p.info.name);
10067                        if (tree == null
10068                                || tree.sourcePackage.equals(p.info.packageName)) {
10069                            bp.packageSetting = pkgSetting;
10070                            bp.perm = p;
10071                            bp.uid = pkg.applicationInfo.uid;
10072                            bp.sourcePackage = p.info.packageName;
10073                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10074                            if (chatty) {
10075                                if (r == null) {
10076                                    r = new StringBuilder(256);
10077                                } else {
10078                                    r.append(' ');
10079                                }
10080                                r.append(p.info.name);
10081                            }
10082                        } else {
10083                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10084                                    + p.info.packageName + " ignored: base tree "
10085                                    + tree.name + " is from package "
10086                                    + tree.sourcePackage);
10087                        }
10088                    } else {
10089                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10090                                + p.info.packageName + " ignored: original from "
10091                                + bp.sourcePackage);
10092                    }
10093                } else if (chatty) {
10094                    if (r == null) {
10095                        r = new StringBuilder(256);
10096                    } else {
10097                        r.append(' ');
10098                    }
10099                    r.append("DUP:");
10100                    r.append(p.info.name);
10101                }
10102                if (bp.perm == p) {
10103                    bp.protectionLevel = p.info.protectionLevel;
10104                }
10105            }
10106
10107            if (r != null) {
10108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10109            }
10110
10111            N = pkg.instrumentation.size();
10112            r = null;
10113            for (i=0; i<N; i++) {
10114                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10115                a.info.packageName = pkg.applicationInfo.packageName;
10116                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10117                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10118                a.info.splitNames = pkg.splitNames;
10119                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10120                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10121                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10122                a.info.dataDir = pkg.applicationInfo.dataDir;
10123                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10124                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10125                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10126                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10127                mInstrumentation.put(a.getComponentName(), a);
10128                if (chatty) {
10129                    if (r == null) {
10130                        r = new StringBuilder(256);
10131                    } else {
10132                        r.append(' ');
10133                    }
10134                    r.append(a.info.name);
10135                }
10136            }
10137            if (r != null) {
10138                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10139            }
10140
10141            if (pkg.protectedBroadcasts != null) {
10142                N = pkg.protectedBroadcasts.size();
10143                for (i=0; i<N; i++) {
10144                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10145                }
10146            }
10147
10148            // Create idmap files for pairs of (packages, overlay packages).
10149            // Note: "android", ie framework-res.apk, is handled by native layers.
10150            if (pkg.mOverlayTarget != null) {
10151                // This is an overlay package.
10152                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10153                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10154                        mOverlays.put(pkg.mOverlayTarget,
10155                                new ArrayMap<String, PackageParser.Package>());
10156                    }
10157                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10158                    map.put(pkg.packageName, pkg);
10159                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10160                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10161                        createIdmapFailed = true;
10162                    }
10163                }
10164            } else if (mOverlays.containsKey(pkg.packageName) &&
10165                    !pkg.packageName.equals("android")) {
10166                // This is a regular package, with one or more known overlay packages.
10167                createIdmapsForPackageLI(pkg);
10168            }
10169        }
10170
10171        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10172
10173        if (createIdmapFailed) {
10174            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10175                    "scanPackageLI failed to createIdmap");
10176        }
10177    }
10178
10179    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10180            PackageParser.Package update, int[] userIds) {
10181        if (existing.applicationInfo == null || update.applicationInfo == null) {
10182            // This isn't due to an app installation.
10183            return;
10184        }
10185
10186        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10187        final File newCodePath = new File(update.applicationInfo.getCodePath());
10188
10189        // The codePath hasn't changed, so there's nothing for us to do.
10190        if (Objects.equals(oldCodePath, newCodePath)) {
10191            return;
10192        }
10193
10194        File canonicalNewCodePath;
10195        try {
10196            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10197        } catch (IOException e) {
10198            Slog.w(TAG, "Failed to get canonical path.", e);
10199            return;
10200        }
10201
10202        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10203        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10204        // that the last component of the path (i.e, the name) doesn't need canonicalization
10205        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10206        // but may change in the future. Hopefully this function won't exist at that point.
10207        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10208                oldCodePath.getName());
10209
10210        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10211        // with "@".
10212        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10213        if (!oldMarkerPrefix.endsWith("@")) {
10214            oldMarkerPrefix += "@";
10215        }
10216        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10217        if (!newMarkerPrefix.endsWith("@")) {
10218            newMarkerPrefix += "@";
10219        }
10220
10221        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10222        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10223        for (String updatedPath : updatedPaths) {
10224            String updatedPathName = new File(updatedPath).getName();
10225            markerSuffixes.add(updatedPathName.replace('/', '@'));
10226        }
10227
10228        for (int userId : userIds) {
10229            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10230
10231            for (String markerSuffix : markerSuffixes) {
10232                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10233                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10234                if (oldForeignUseMark.exists()) {
10235                    try {
10236                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10237                                newForeignUseMark.getAbsolutePath());
10238                    } catch (ErrnoException e) {
10239                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10240                        oldForeignUseMark.delete();
10241                    }
10242                }
10243            }
10244        }
10245    }
10246
10247    /**
10248     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10249     * is derived purely on the basis of the contents of {@code scanFile} and
10250     * {@code cpuAbiOverride}.
10251     *
10252     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10253     */
10254    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10255                                 String cpuAbiOverride, boolean extractLibs,
10256                                 File appLib32InstallDir)
10257            throws PackageManagerException {
10258        // Give ourselves some initial paths; we'll come back for another
10259        // pass once we've determined ABI below.
10260        setNativeLibraryPaths(pkg, appLib32InstallDir);
10261
10262        // We would never need to extract libs for forward-locked and external packages,
10263        // since the container service will do it for us. We shouldn't attempt to
10264        // extract libs from system app when it was not updated.
10265        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10266                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10267            extractLibs = false;
10268        }
10269
10270        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10271        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10272
10273        NativeLibraryHelper.Handle handle = null;
10274        try {
10275            handle = NativeLibraryHelper.Handle.create(pkg);
10276            // TODO(multiArch): This can be null for apps that didn't go through the
10277            // usual installation process. We can calculate it again, like we
10278            // do during install time.
10279            //
10280            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10281            // unnecessary.
10282            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10283
10284            // Null out the abis so that they can be recalculated.
10285            pkg.applicationInfo.primaryCpuAbi = null;
10286            pkg.applicationInfo.secondaryCpuAbi = null;
10287            if (isMultiArch(pkg.applicationInfo)) {
10288                // Warn if we've set an abiOverride for multi-lib packages..
10289                // By definition, we need to copy both 32 and 64 bit libraries for
10290                // such packages.
10291                if (pkg.cpuAbiOverride != null
10292                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10293                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10294                }
10295
10296                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10297                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10298                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10299                    if (extractLibs) {
10300                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10301                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10302                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10303                                useIsaSpecificSubdirs);
10304                    } else {
10305                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10306                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10307                    }
10308                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10309                }
10310
10311                maybeThrowExceptionForMultiArchCopy(
10312                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10313
10314                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10315                    if (extractLibs) {
10316                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10317                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10318                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10319                                useIsaSpecificSubdirs);
10320                    } else {
10321                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10322                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10323                    }
10324                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10325                }
10326
10327                maybeThrowExceptionForMultiArchCopy(
10328                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10329
10330                if (abi64 >= 0) {
10331                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10332                }
10333
10334                if (abi32 >= 0) {
10335                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10336                    if (abi64 >= 0) {
10337                        if (pkg.use32bitAbi) {
10338                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10339                            pkg.applicationInfo.primaryCpuAbi = abi;
10340                        } else {
10341                            pkg.applicationInfo.secondaryCpuAbi = abi;
10342                        }
10343                    } else {
10344                        pkg.applicationInfo.primaryCpuAbi = abi;
10345                    }
10346                }
10347
10348            } else {
10349                String[] abiList = (cpuAbiOverride != null) ?
10350                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10351
10352                // Enable gross and lame hacks for apps that are built with old
10353                // SDK tools. We must scan their APKs for renderscript bitcode and
10354                // not launch them if it's present. Don't bother checking on devices
10355                // that don't have 64 bit support.
10356                boolean needsRenderScriptOverride = false;
10357                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10358                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10359                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10360                    needsRenderScriptOverride = true;
10361                }
10362
10363                final int copyRet;
10364                if (extractLibs) {
10365                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10366                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10367                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10368                } else {
10369                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10370                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10371                }
10372                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10373
10374                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10375                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10376                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10377                }
10378
10379                if (copyRet >= 0) {
10380                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10381                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10382                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10383                } else if (needsRenderScriptOverride) {
10384                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10385                }
10386            }
10387        } catch (IOException ioe) {
10388            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10389        } finally {
10390            IoUtils.closeQuietly(handle);
10391        }
10392
10393        // Now that we've calculated the ABIs and determined if it's an internal app,
10394        // we will go ahead and populate the nativeLibraryPath.
10395        setNativeLibraryPaths(pkg, appLib32InstallDir);
10396    }
10397
10398    /**
10399     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10400     * i.e, so that all packages can be run inside a single process if required.
10401     *
10402     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10403     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10404     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10405     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10406     * updating a package that belongs to a shared user.
10407     *
10408     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10409     * adds unnecessary complexity.
10410     */
10411    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10412            PackageParser.Package scannedPackage) {
10413        String requiredInstructionSet = null;
10414        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10415            requiredInstructionSet = VMRuntime.getInstructionSet(
10416                     scannedPackage.applicationInfo.primaryCpuAbi);
10417        }
10418
10419        PackageSetting requirer = null;
10420        for (PackageSetting ps : packagesForUser) {
10421            // If packagesForUser contains scannedPackage, we skip it. This will happen
10422            // when scannedPackage is an update of an existing package. Without this check,
10423            // we will never be able to change the ABI of any package belonging to a shared
10424            // user, even if it's compatible with other packages.
10425            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10426                if (ps.primaryCpuAbiString == null) {
10427                    continue;
10428                }
10429
10430                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10431                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10432                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10433                    // this but there's not much we can do.
10434                    String errorMessage = "Instruction set mismatch, "
10435                            + ((requirer == null) ? "[caller]" : requirer)
10436                            + " requires " + requiredInstructionSet + " whereas " + ps
10437                            + " requires " + instructionSet;
10438                    Slog.w(TAG, errorMessage);
10439                }
10440
10441                if (requiredInstructionSet == null) {
10442                    requiredInstructionSet = instructionSet;
10443                    requirer = ps;
10444                }
10445            }
10446        }
10447
10448        if (requiredInstructionSet != null) {
10449            String adjustedAbi;
10450            if (requirer != null) {
10451                // requirer != null implies that either scannedPackage was null or that scannedPackage
10452                // did not require an ABI, in which case we have to adjust scannedPackage to match
10453                // the ABI of the set (which is the same as requirer's ABI)
10454                adjustedAbi = requirer.primaryCpuAbiString;
10455                if (scannedPackage != null) {
10456                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10457                }
10458            } else {
10459                // requirer == null implies that we're updating all ABIs in the set to
10460                // match scannedPackage.
10461                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10462            }
10463
10464            for (PackageSetting ps : packagesForUser) {
10465                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10466                    if (ps.primaryCpuAbiString != null) {
10467                        continue;
10468                    }
10469
10470                    ps.primaryCpuAbiString = adjustedAbi;
10471                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10472                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10473                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10474                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10475                                + " (requirer="
10476                                + (requirer == null ? "null" : requirer.pkg.packageName)
10477                                + ", scannedPackage="
10478                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10479                                + ")");
10480                        try {
10481                            mInstaller.rmdex(ps.codePathString,
10482                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10483                        } catch (InstallerException ignored) {
10484                        }
10485                    }
10486                }
10487            }
10488        }
10489    }
10490
10491    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10492        synchronized (mPackages) {
10493            mResolverReplaced = true;
10494            // Set up information for custom user intent resolution activity.
10495            mResolveActivity.applicationInfo = pkg.applicationInfo;
10496            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10497            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10498            mResolveActivity.processName = pkg.applicationInfo.packageName;
10499            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10500            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10501                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10502            mResolveActivity.theme = 0;
10503            mResolveActivity.exported = true;
10504            mResolveActivity.enabled = true;
10505            mResolveInfo.activityInfo = mResolveActivity;
10506            mResolveInfo.priority = 0;
10507            mResolveInfo.preferredOrder = 0;
10508            mResolveInfo.match = 0;
10509            mResolveComponentName = mCustomResolverComponentName;
10510            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10511                    mResolveComponentName);
10512        }
10513    }
10514
10515    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10516        if (installerComponent == null) {
10517            if (DEBUG_EPHEMERAL) {
10518                Slog.d(TAG, "Clear ephemeral installer activity");
10519            }
10520            mEphemeralInstallerActivity.applicationInfo = null;
10521            return;
10522        }
10523
10524        if (DEBUG_EPHEMERAL) {
10525            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10526        }
10527        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10528        // Set up information for ephemeral installer activity
10529        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10530        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10531        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10532        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10533        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10534        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10535                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10536        mEphemeralInstallerActivity.theme = 0;
10537        mEphemeralInstallerActivity.exported = true;
10538        mEphemeralInstallerActivity.enabled = true;
10539        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10540        mEphemeralInstallerInfo.priority = 0;
10541        mEphemeralInstallerInfo.preferredOrder = 1;
10542        mEphemeralInstallerInfo.isDefault = true;
10543        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10544                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10545    }
10546
10547    private static String calculateBundledApkRoot(final String codePathString) {
10548        final File codePath = new File(codePathString);
10549        final File codeRoot;
10550        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10551            codeRoot = Environment.getRootDirectory();
10552        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10553            codeRoot = Environment.getOemDirectory();
10554        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10555            codeRoot = Environment.getVendorDirectory();
10556        } else {
10557            // Unrecognized code path; take its top real segment as the apk root:
10558            // e.g. /something/app/blah.apk => /something
10559            try {
10560                File f = codePath.getCanonicalFile();
10561                File parent = f.getParentFile();    // non-null because codePath is a file
10562                File tmp;
10563                while ((tmp = parent.getParentFile()) != null) {
10564                    f = parent;
10565                    parent = tmp;
10566                }
10567                codeRoot = f;
10568                Slog.w(TAG, "Unrecognized code path "
10569                        + codePath + " - using " + codeRoot);
10570            } catch (IOException e) {
10571                // Can't canonicalize the code path -- shenanigans?
10572                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10573                return Environment.getRootDirectory().getPath();
10574            }
10575        }
10576        return codeRoot.getPath();
10577    }
10578
10579    /**
10580     * Derive and set the location of native libraries for the given package,
10581     * which varies depending on where and how the package was installed.
10582     */
10583    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10584        final ApplicationInfo info = pkg.applicationInfo;
10585        final String codePath = pkg.codePath;
10586        final File codeFile = new File(codePath);
10587        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10588        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10589
10590        info.nativeLibraryRootDir = null;
10591        info.nativeLibraryRootRequiresIsa = false;
10592        info.nativeLibraryDir = null;
10593        info.secondaryNativeLibraryDir = null;
10594
10595        if (isApkFile(codeFile)) {
10596            // Monolithic install
10597            if (bundledApp) {
10598                // If "/system/lib64/apkname" exists, assume that is the per-package
10599                // native library directory to use; otherwise use "/system/lib/apkname".
10600                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10601                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10602                        getPrimaryInstructionSet(info));
10603
10604                // This is a bundled system app so choose the path based on the ABI.
10605                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10606                // is just the default path.
10607                final String apkName = deriveCodePathName(codePath);
10608                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10609                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10610                        apkName).getAbsolutePath();
10611
10612                if (info.secondaryCpuAbi != null) {
10613                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10614                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10615                            secondaryLibDir, apkName).getAbsolutePath();
10616                }
10617            } else if (asecApp) {
10618                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10619                        .getAbsolutePath();
10620            } else {
10621                final String apkName = deriveCodePathName(codePath);
10622                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10623                        .getAbsolutePath();
10624            }
10625
10626            info.nativeLibraryRootRequiresIsa = false;
10627            info.nativeLibraryDir = info.nativeLibraryRootDir;
10628        } else {
10629            // Cluster install
10630            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10631            info.nativeLibraryRootRequiresIsa = true;
10632
10633            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10634                    getPrimaryInstructionSet(info)).getAbsolutePath();
10635
10636            if (info.secondaryCpuAbi != null) {
10637                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10638                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10639            }
10640        }
10641    }
10642
10643    /**
10644     * Calculate the abis and roots for a bundled app. These can uniquely
10645     * be determined from the contents of the system partition, i.e whether
10646     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10647     * of this information, and instead assume that the system was built
10648     * sensibly.
10649     */
10650    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10651                                           PackageSetting pkgSetting) {
10652        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10653
10654        // If "/system/lib64/apkname" exists, assume that is the per-package
10655        // native library directory to use; otherwise use "/system/lib/apkname".
10656        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10657        setBundledAppAbi(pkg, apkRoot, apkName);
10658        // pkgSetting might be null during rescan following uninstall of updates
10659        // to a bundled app, so accommodate that possibility.  The settings in
10660        // that case will be established later from the parsed package.
10661        //
10662        // If the settings aren't null, sync them up with what we've just derived.
10663        // note that apkRoot isn't stored in the package settings.
10664        if (pkgSetting != null) {
10665            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10666            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10667        }
10668    }
10669
10670    /**
10671     * Deduces the ABI of a bundled app and sets the relevant fields on the
10672     * parsed pkg object.
10673     *
10674     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10675     *        under which system libraries are installed.
10676     * @param apkName the name of the installed package.
10677     */
10678    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10679        final File codeFile = new File(pkg.codePath);
10680
10681        final boolean has64BitLibs;
10682        final boolean has32BitLibs;
10683        if (isApkFile(codeFile)) {
10684            // Monolithic install
10685            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10686            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10687        } else {
10688            // Cluster install
10689            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10690            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10691                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10692                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10693                has64BitLibs = (new File(rootDir, isa)).exists();
10694            } else {
10695                has64BitLibs = false;
10696            }
10697            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10698                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10699                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10700                has32BitLibs = (new File(rootDir, isa)).exists();
10701            } else {
10702                has32BitLibs = false;
10703            }
10704        }
10705
10706        if (has64BitLibs && !has32BitLibs) {
10707            // The package has 64 bit libs, but not 32 bit libs. Its primary
10708            // ABI should be 64 bit. We can safely assume here that the bundled
10709            // native libraries correspond to the most preferred ABI in the list.
10710
10711            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10712            pkg.applicationInfo.secondaryCpuAbi = null;
10713        } else if (has32BitLibs && !has64BitLibs) {
10714            // The package has 32 bit libs but not 64 bit libs. Its primary
10715            // ABI should be 32 bit.
10716
10717            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10718            pkg.applicationInfo.secondaryCpuAbi = null;
10719        } else if (has32BitLibs && has64BitLibs) {
10720            // The application has both 64 and 32 bit bundled libraries. We check
10721            // here that the app declares multiArch support, and warn if it doesn't.
10722            //
10723            // We will be lenient here and record both ABIs. The primary will be the
10724            // ABI that's higher on the list, i.e, a device that's configured to prefer
10725            // 64 bit apps will see a 64 bit primary ABI,
10726
10727            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10728                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10729            }
10730
10731            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10732                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10733                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10734            } else {
10735                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10736                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10737            }
10738        } else {
10739            pkg.applicationInfo.primaryCpuAbi = null;
10740            pkg.applicationInfo.secondaryCpuAbi = null;
10741        }
10742    }
10743
10744    private void killApplication(String pkgName, int appId, String reason) {
10745        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10746    }
10747
10748    private void killApplication(String pkgName, int appId, int userId, String reason) {
10749        // Request the ActivityManager to kill the process(only for existing packages)
10750        // so that we do not end up in a confused state while the user is still using the older
10751        // version of the application while the new one gets installed.
10752        final long token = Binder.clearCallingIdentity();
10753        try {
10754            IActivityManager am = ActivityManager.getService();
10755            if (am != null) {
10756                try {
10757                    am.killApplication(pkgName, appId, userId, reason);
10758                } catch (RemoteException e) {
10759                }
10760            }
10761        } finally {
10762            Binder.restoreCallingIdentity(token);
10763        }
10764    }
10765
10766    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10767        // Remove the parent package setting
10768        PackageSetting ps = (PackageSetting) pkg.mExtras;
10769        if (ps != null) {
10770            removePackageLI(ps, chatty);
10771        }
10772        // Remove the child package setting
10773        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10774        for (int i = 0; i < childCount; i++) {
10775            PackageParser.Package childPkg = pkg.childPackages.get(i);
10776            ps = (PackageSetting) childPkg.mExtras;
10777            if (ps != null) {
10778                removePackageLI(ps, chatty);
10779            }
10780        }
10781    }
10782
10783    void removePackageLI(PackageSetting ps, boolean chatty) {
10784        if (DEBUG_INSTALL) {
10785            if (chatty)
10786                Log.d(TAG, "Removing package " + ps.name);
10787        }
10788
10789        // writer
10790        synchronized (mPackages) {
10791            mPackages.remove(ps.name);
10792            final PackageParser.Package pkg = ps.pkg;
10793            if (pkg != null) {
10794                cleanPackageDataStructuresLILPw(pkg, chatty);
10795            }
10796        }
10797    }
10798
10799    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10800        if (DEBUG_INSTALL) {
10801            if (chatty)
10802                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10803        }
10804
10805        // writer
10806        synchronized (mPackages) {
10807            // Remove the parent package
10808            mPackages.remove(pkg.applicationInfo.packageName);
10809            cleanPackageDataStructuresLILPw(pkg, chatty);
10810
10811            // Remove the child packages
10812            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10813            for (int i = 0; i < childCount; i++) {
10814                PackageParser.Package childPkg = pkg.childPackages.get(i);
10815                mPackages.remove(childPkg.applicationInfo.packageName);
10816                cleanPackageDataStructuresLILPw(childPkg, chatty);
10817            }
10818        }
10819    }
10820
10821    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10822        int N = pkg.providers.size();
10823        StringBuilder r = null;
10824        int i;
10825        for (i=0; i<N; i++) {
10826            PackageParser.Provider p = pkg.providers.get(i);
10827            mProviders.removeProvider(p);
10828            if (p.info.authority == null) {
10829
10830                /* There was another ContentProvider with this authority when
10831                 * this app was installed so this authority is null,
10832                 * Ignore it as we don't have to unregister the provider.
10833                 */
10834                continue;
10835            }
10836            String names[] = p.info.authority.split(";");
10837            for (int j = 0; j < names.length; j++) {
10838                if (mProvidersByAuthority.get(names[j]) == p) {
10839                    mProvidersByAuthority.remove(names[j]);
10840                    if (DEBUG_REMOVE) {
10841                        if (chatty)
10842                            Log.d(TAG, "Unregistered content provider: " + names[j]
10843                                    + ", className = " + p.info.name + ", isSyncable = "
10844                                    + p.info.isSyncable);
10845                    }
10846                }
10847            }
10848            if (DEBUG_REMOVE && chatty) {
10849                if (r == null) {
10850                    r = new StringBuilder(256);
10851                } else {
10852                    r.append(' ');
10853                }
10854                r.append(p.info.name);
10855            }
10856        }
10857        if (r != null) {
10858            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10859        }
10860
10861        N = pkg.services.size();
10862        r = null;
10863        for (i=0; i<N; i++) {
10864            PackageParser.Service s = pkg.services.get(i);
10865            mServices.removeService(s);
10866            if (chatty) {
10867                if (r == null) {
10868                    r = new StringBuilder(256);
10869                } else {
10870                    r.append(' ');
10871                }
10872                r.append(s.info.name);
10873            }
10874        }
10875        if (r != null) {
10876            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10877        }
10878
10879        N = pkg.receivers.size();
10880        r = null;
10881        for (i=0; i<N; i++) {
10882            PackageParser.Activity a = pkg.receivers.get(i);
10883            mReceivers.removeActivity(a, "receiver");
10884            if (DEBUG_REMOVE && chatty) {
10885                if (r == null) {
10886                    r = new StringBuilder(256);
10887                } else {
10888                    r.append(' ');
10889                }
10890                r.append(a.info.name);
10891            }
10892        }
10893        if (r != null) {
10894            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10895        }
10896
10897        N = pkg.activities.size();
10898        r = null;
10899        for (i=0; i<N; i++) {
10900            PackageParser.Activity a = pkg.activities.get(i);
10901            mActivities.removeActivity(a, "activity");
10902            if (DEBUG_REMOVE && chatty) {
10903                if (r == null) {
10904                    r = new StringBuilder(256);
10905                } else {
10906                    r.append(' ');
10907                }
10908                r.append(a.info.name);
10909            }
10910        }
10911        if (r != null) {
10912            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10913        }
10914
10915        N = pkg.permissions.size();
10916        r = null;
10917        for (i=0; i<N; i++) {
10918            PackageParser.Permission p = pkg.permissions.get(i);
10919            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10920            if (bp == null) {
10921                bp = mSettings.mPermissionTrees.get(p.info.name);
10922            }
10923            if (bp != null && bp.perm == p) {
10924                bp.perm = null;
10925                if (DEBUG_REMOVE && chatty) {
10926                    if (r == null) {
10927                        r = new StringBuilder(256);
10928                    } else {
10929                        r.append(' ');
10930                    }
10931                    r.append(p.info.name);
10932                }
10933            }
10934            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10935                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10936                if (appOpPkgs != null) {
10937                    appOpPkgs.remove(pkg.packageName);
10938                }
10939            }
10940        }
10941        if (r != null) {
10942            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10943        }
10944
10945        N = pkg.requestedPermissions.size();
10946        r = null;
10947        for (i=0; i<N; i++) {
10948            String perm = pkg.requestedPermissions.get(i);
10949            BasePermission bp = mSettings.mPermissions.get(perm);
10950            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10951                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10952                if (appOpPkgs != null) {
10953                    appOpPkgs.remove(pkg.packageName);
10954                    if (appOpPkgs.isEmpty()) {
10955                        mAppOpPermissionPackages.remove(perm);
10956                    }
10957                }
10958            }
10959        }
10960        if (r != null) {
10961            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10962        }
10963
10964        N = pkg.instrumentation.size();
10965        r = null;
10966        for (i=0; i<N; i++) {
10967            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10968            mInstrumentation.remove(a.getComponentName());
10969            if (DEBUG_REMOVE && chatty) {
10970                if (r == null) {
10971                    r = new StringBuilder(256);
10972                } else {
10973                    r.append(' ');
10974                }
10975                r.append(a.info.name);
10976            }
10977        }
10978        if (r != null) {
10979            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10980        }
10981
10982        r = null;
10983        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10984            // Only system apps can hold shared libraries.
10985            if (pkg.libraryNames != null) {
10986                for (i = 0; i < pkg.libraryNames.size(); i++) {
10987                    String name = pkg.libraryNames.get(i);
10988                    if (removeSharedLibraryLPw(name, 0)) {
10989                        if (DEBUG_REMOVE && chatty) {
10990                            if (r == null) {
10991                                r = new StringBuilder(256);
10992                            } else {
10993                                r.append(' ');
10994                            }
10995                            r.append(name);
10996                        }
10997                    }
10998                }
10999            }
11000        }
11001
11002        r = null;
11003
11004        // Any package can hold static shared libraries.
11005        if (pkg.staticSharedLibName != null) {
11006            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11007                if (DEBUG_REMOVE && chatty) {
11008                    if (r == null) {
11009                        r = new StringBuilder(256);
11010                    } else {
11011                        r.append(' ');
11012                    }
11013                    r.append(pkg.staticSharedLibName);
11014                }
11015            }
11016        }
11017
11018        if (r != null) {
11019            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11020        }
11021    }
11022
11023    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11024        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11025            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11026                return true;
11027            }
11028        }
11029        return false;
11030    }
11031
11032    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11033    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11034    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11035
11036    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11037        // Update the parent permissions
11038        updatePermissionsLPw(pkg.packageName, pkg, flags);
11039        // Update the child permissions
11040        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11041        for (int i = 0; i < childCount; i++) {
11042            PackageParser.Package childPkg = pkg.childPackages.get(i);
11043            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11044        }
11045    }
11046
11047    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11048            int flags) {
11049        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11050        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11051    }
11052
11053    private void updatePermissionsLPw(String changingPkg,
11054            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11055        // Make sure there are no dangling permission trees.
11056        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11057        while (it.hasNext()) {
11058            final BasePermission bp = it.next();
11059            if (bp.packageSetting == null) {
11060                // We may not yet have parsed the package, so just see if
11061                // we still know about its settings.
11062                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11063            }
11064            if (bp.packageSetting == null) {
11065                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11066                        + " from package " + bp.sourcePackage);
11067                it.remove();
11068            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11069                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11070                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11071                            + " from package " + bp.sourcePackage);
11072                    flags |= UPDATE_PERMISSIONS_ALL;
11073                    it.remove();
11074                }
11075            }
11076        }
11077
11078        // Make sure all dynamic permissions have been assigned to a package,
11079        // and make sure there are no dangling permissions.
11080        it = mSettings.mPermissions.values().iterator();
11081        while (it.hasNext()) {
11082            final BasePermission bp = it.next();
11083            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11084                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11085                        + bp.name + " pkg=" + bp.sourcePackage
11086                        + " info=" + bp.pendingInfo);
11087                if (bp.packageSetting == null && bp.pendingInfo != null) {
11088                    final BasePermission tree = findPermissionTreeLP(bp.name);
11089                    if (tree != null && tree.perm != null) {
11090                        bp.packageSetting = tree.packageSetting;
11091                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11092                                new PermissionInfo(bp.pendingInfo));
11093                        bp.perm.info.packageName = tree.perm.info.packageName;
11094                        bp.perm.info.name = bp.name;
11095                        bp.uid = tree.uid;
11096                    }
11097                }
11098            }
11099            if (bp.packageSetting == null) {
11100                // We may not yet have parsed the package, so just see if
11101                // we still know about its settings.
11102                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11103            }
11104            if (bp.packageSetting == null) {
11105                Slog.w(TAG, "Removing dangling permission: " + bp.name
11106                        + " from package " + bp.sourcePackage);
11107                it.remove();
11108            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11109                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11110                    Slog.i(TAG, "Removing old permission: " + bp.name
11111                            + " from package " + bp.sourcePackage);
11112                    flags |= UPDATE_PERMISSIONS_ALL;
11113                    it.remove();
11114                }
11115            }
11116        }
11117
11118        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11119        // Now update the permissions for all packages, in particular
11120        // replace the granted permissions of the system packages.
11121        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11122            for (PackageParser.Package pkg : mPackages.values()) {
11123                if (pkg != pkgInfo) {
11124                    // Only replace for packages on requested volume
11125                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11126                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11127                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11128                    grantPermissionsLPw(pkg, replace, changingPkg);
11129                }
11130            }
11131        }
11132
11133        if (pkgInfo != null) {
11134            // Only replace for packages on requested volume
11135            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11136            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11137                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11138            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11139        }
11140        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11141    }
11142
11143    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11144            String packageOfInterest) {
11145        // IMPORTANT: There are two types of permissions: install and runtime.
11146        // Install time permissions are granted when the app is installed to
11147        // all device users and users added in the future. Runtime permissions
11148        // are granted at runtime explicitly to specific users. Normal and signature
11149        // protected permissions are install time permissions. Dangerous permissions
11150        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11151        // otherwise they are runtime permissions. This function does not manage
11152        // runtime permissions except for the case an app targeting Lollipop MR1
11153        // being upgraded to target a newer SDK, in which case dangerous permissions
11154        // are transformed from install time to runtime ones.
11155
11156        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11157        if (ps == null) {
11158            return;
11159        }
11160
11161        PermissionsState permissionsState = ps.getPermissionsState();
11162        PermissionsState origPermissions = permissionsState;
11163
11164        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11165
11166        boolean runtimePermissionsRevoked = false;
11167        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11168
11169        boolean changedInstallPermission = false;
11170
11171        if (replace) {
11172            ps.installPermissionsFixed = false;
11173            if (!ps.isSharedUser()) {
11174                origPermissions = new PermissionsState(permissionsState);
11175                permissionsState.reset();
11176            } else {
11177                // We need to know only about runtime permission changes since the
11178                // calling code always writes the install permissions state but
11179                // the runtime ones are written only if changed. The only cases of
11180                // changed runtime permissions here are promotion of an install to
11181                // runtime and revocation of a runtime from a shared user.
11182                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11183                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11184                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11185                    runtimePermissionsRevoked = true;
11186                }
11187            }
11188        }
11189
11190        permissionsState.setGlobalGids(mGlobalGids);
11191
11192        final int N = pkg.requestedPermissions.size();
11193        for (int i=0; i<N; i++) {
11194            final String name = pkg.requestedPermissions.get(i);
11195            final BasePermission bp = mSettings.mPermissions.get(name);
11196
11197            if (DEBUG_INSTALL) {
11198                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11199            }
11200
11201            if (bp == null || bp.packageSetting == null) {
11202                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11203                    Slog.w(TAG, "Unknown permission " + name
11204                            + " in package " + pkg.packageName);
11205                }
11206                continue;
11207            }
11208
11209
11210            // Limit ephemeral apps to ephemeral allowed permissions.
11211            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
11212                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11213                        + pkg.packageName);
11214                continue;
11215            }
11216
11217            final String perm = bp.name;
11218            boolean allowedSig = false;
11219            int grant = GRANT_DENIED;
11220
11221            // Keep track of app op permissions.
11222            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11223                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11224                if (pkgs == null) {
11225                    pkgs = new ArraySet<>();
11226                    mAppOpPermissionPackages.put(bp.name, pkgs);
11227                }
11228                pkgs.add(pkg.packageName);
11229            }
11230
11231            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11232            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11233                    >= Build.VERSION_CODES.M;
11234            switch (level) {
11235                case PermissionInfo.PROTECTION_NORMAL: {
11236                    // For all apps normal permissions are install time ones.
11237                    grant = GRANT_INSTALL;
11238                } break;
11239
11240                case PermissionInfo.PROTECTION_DANGEROUS: {
11241                    // If a permission review is required for legacy apps we represent
11242                    // their permissions as always granted runtime ones since we need
11243                    // to keep the review required permission flag per user while an
11244                    // install permission's state is shared across all users.
11245                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11246                        // For legacy apps dangerous permissions are install time ones.
11247                        grant = GRANT_INSTALL;
11248                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11249                        // For legacy apps that became modern, install becomes runtime.
11250                        grant = GRANT_UPGRADE;
11251                    } else if (mPromoteSystemApps
11252                            && isSystemApp(ps)
11253                            && mExistingSystemPackages.contains(ps.name)) {
11254                        // For legacy system apps, install becomes runtime.
11255                        // We cannot check hasInstallPermission() for system apps since those
11256                        // permissions were granted implicitly and not persisted pre-M.
11257                        grant = GRANT_UPGRADE;
11258                    } else {
11259                        // For modern apps keep runtime permissions unchanged.
11260                        grant = GRANT_RUNTIME;
11261                    }
11262                } break;
11263
11264                case PermissionInfo.PROTECTION_SIGNATURE: {
11265                    // For all apps signature permissions are install time ones.
11266                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11267                    if (allowedSig) {
11268                        grant = GRANT_INSTALL;
11269                    }
11270                } break;
11271            }
11272
11273            if (DEBUG_INSTALL) {
11274                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11275            }
11276
11277            if (grant != GRANT_DENIED) {
11278                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11279                    // If this is an existing, non-system package, then
11280                    // we can't add any new permissions to it.
11281                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11282                        // Except...  if this is a permission that was added
11283                        // to the platform (note: need to only do this when
11284                        // updating the platform).
11285                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11286                            grant = GRANT_DENIED;
11287                        }
11288                    }
11289                }
11290
11291                switch (grant) {
11292                    case GRANT_INSTALL: {
11293                        // Revoke this as runtime permission to handle the case of
11294                        // a runtime permission being downgraded to an install one.
11295                        // Also in permission review mode we keep dangerous permissions
11296                        // for legacy apps
11297                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11298                            if (origPermissions.getRuntimePermissionState(
11299                                    bp.name, userId) != null) {
11300                                // Revoke the runtime permission and clear the flags.
11301                                origPermissions.revokeRuntimePermission(bp, userId);
11302                                origPermissions.updatePermissionFlags(bp, userId,
11303                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11304                                // If we revoked a permission permission, we have to write.
11305                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11306                                        changedRuntimePermissionUserIds, userId);
11307                            }
11308                        }
11309                        // Grant an install permission.
11310                        if (permissionsState.grantInstallPermission(bp) !=
11311                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11312                            changedInstallPermission = true;
11313                        }
11314                    } break;
11315
11316                    case GRANT_RUNTIME: {
11317                        // Grant previously granted runtime permissions.
11318                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11319                            PermissionState permissionState = origPermissions
11320                                    .getRuntimePermissionState(bp.name, userId);
11321                            int flags = permissionState != null
11322                                    ? permissionState.getFlags() : 0;
11323                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11324                                // Don't propagate the permission in a permission review mode if
11325                                // the former was revoked, i.e. marked to not propagate on upgrade.
11326                                // Note that in a permission review mode install permissions are
11327                                // represented as constantly granted runtime ones since we need to
11328                                // keep a per user state associated with the permission. Also the
11329                                // revoke on upgrade flag is no longer applicable and is reset.
11330                                final boolean revokeOnUpgrade = (flags & PackageManager
11331                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11332                                if (revokeOnUpgrade) {
11333                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11334                                    // Since we changed the flags, we have to write.
11335                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11336                                            changedRuntimePermissionUserIds, userId);
11337                                }
11338                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11339                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11340                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11341                                        // If we cannot put the permission as it was,
11342                                        // we have to write.
11343                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11344                                                changedRuntimePermissionUserIds, userId);
11345                                    }
11346                                }
11347
11348                                // If the app supports runtime permissions no need for a review.
11349                                if (mPermissionReviewRequired
11350                                        && appSupportsRuntimePermissions
11351                                        && (flags & PackageManager
11352                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11353                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11354                                    // Since we changed the flags, we have to write.
11355                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11356                                            changedRuntimePermissionUserIds, userId);
11357                                }
11358                            } else if (mPermissionReviewRequired
11359                                    && !appSupportsRuntimePermissions) {
11360                                // For legacy apps that need a permission review, every new
11361                                // runtime permission is granted but it is pending a review.
11362                                // We also need to review only platform defined runtime
11363                                // permissions as these are the only ones the platform knows
11364                                // how to disable the API to simulate revocation as legacy
11365                                // apps don't expect to run with revoked permissions.
11366                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11367                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11368                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11369                                        // We changed the flags, hence have to write.
11370                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11371                                                changedRuntimePermissionUserIds, userId);
11372                                    }
11373                                }
11374                                if (permissionsState.grantRuntimePermission(bp, userId)
11375                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11376                                    // We changed the permission, hence have to write.
11377                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11378                                            changedRuntimePermissionUserIds, userId);
11379                                }
11380                            }
11381                            // Propagate the permission flags.
11382                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11383                        }
11384                    } break;
11385
11386                    case GRANT_UPGRADE: {
11387                        // Grant runtime permissions for a previously held install permission.
11388                        PermissionState permissionState = origPermissions
11389                                .getInstallPermissionState(bp.name);
11390                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11391
11392                        if (origPermissions.revokeInstallPermission(bp)
11393                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11394                            // We will be transferring the permission flags, so clear them.
11395                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11396                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11397                            changedInstallPermission = true;
11398                        }
11399
11400                        // If the permission is not to be promoted to runtime we ignore it and
11401                        // also its other flags as they are not applicable to install permissions.
11402                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11403                            for (int userId : currentUserIds) {
11404                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11405                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11406                                    // Transfer the permission flags.
11407                                    permissionsState.updatePermissionFlags(bp, userId,
11408                                            flags, flags);
11409                                    // If we granted the permission, we have to write.
11410                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11411                                            changedRuntimePermissionUserIds, userId);
11412                                }
11413                            }
11414                        }
11415                    } break;
11416
11417                    default: {
11418                        if (packageOfInterest == null
11419                                || packageOfInterest.equals(pkg.packageName)) {
11420                            Slog.w(TAG, "Not granting permission " + perm
11421                                    + " to package " + pkg.packageName
11422                                    + " because it was previously installed without");
11423                        }
11424                    } break;
11425                }
11426            } else {
11427                if (permissionsState.revokeInstallPermission(bp) !=
11428                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11429                    // Also drop the permission flags.
11430                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11431                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11432                    changedInstallPermission = true;
11433                    Slog.i(TAG, "Un-granting permission " + perm
11434                            + " from package " + pkg.packageName
11435                            + " (protectionLevel=" + bp.protectionLevel
11436                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11437                            + ")");
11438                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11439                    // Don't print warning for app op permissions, since it is fine for them
11440                    // not to be granted, there is a UI for the user to decide.
11441                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11442                        Slog.w(TAG, "Not granting permission " + perm
11443                                + " to package " + pkg.packageName
11444                                + " (protectionLevel=" + bp.protectionLevel
11445                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11446                                + ")");
11447                    }
11448                }
11449            }
11450        }
11451
11452        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11453                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11454            // This is the first that we have heard about this package, so the
11455            // permissions we have now selected are fixed until explicitly
11456            // changed.
11457            ps.installPermissionsFixed = true;
11458        }
11459
11460        // Persist the runtime permissions state for users with changes. If permissions
11461        // were revoked because no app in the shared user declares them we have to
11462        // write synchronously to avoid losing runtime permissions state.
11463        for (int userId : changedRuntimePermissionUserIds) {
11464            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11465        }
11466    }
11467
11468    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11469        boolean allowed = false;
11470        final int NP = PackageParser.NEW_PERMISSIONS.length;
11471        for (int ip=0; ip<NP; ip++) {
11472            final PackageParser.NewPermissionInfo npi
11473                    = PackageParser.NEW_PERMISSIONS[ip];
11474            if (npi.name.equals(perm)
11475                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11476                allowed = true;
11477                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11478                        + pkg.packageName);
11479                break;
11480            }
11481        }
11482        return allowed;
11483    }
11484
11485    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11486            BasePermission bp, PermissionsState origPermissions) {
11487        boolean privilegedPermission = (bp.protectionLevel
11488                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11489        boolean privappPermissionsDisable =
11490                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11491        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11492        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11493        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11494                && !platformPackage && platformPermission) {
11495            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11496                    .getPrivAppPermissions(pkg.packageName);
11497            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11498            if (!whitelisted) {
11499                Slog.w(TAG, "Privileged permission " + perm + " for package "
11500                        + pkg.packageName + " - not in privapp-permissions whitelist");
11501                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11502                    return false;
11503                }
11504            }
11505        }
11506        boolean allowed = (compareSignatures(
11507                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11508                        == PackageManager.SIGNATURE_MATCH)
11509                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11510                        == PackageManager.SIGNATURE_MATCH);
11511        if (!allowed && privilegedPermission) {
11512            if (isSystemApp(pkg)) {
11513                // For updated system applications, a system permission
11514                // is granted only if it had been defined by the original application.
11515                if (pkg.isUpdatedSystemApp()) {
11516                    final PackageSetting sysPs = mSettings
11517                            .getDisabledSystemPkgLPr(pkg.packageName);
11518                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11519                        // If the original was granted this permission, we take
11520                        // that grant decision as read and propagate it to the
11521                        // update.
11522                        if (sysPs.isPrivileged()) {
11523                            allowed = true;
11524                        }
11525                    } else {
11526                        // The system apk may have been updated with an older
11527                        // version of the one on the data partition, but which
11528                        // granted a new system permission that it didn't have
11529                        // before.  In this case we do want to allow the app to
11530                        // now get the new permission if the ancestral apk is
11531                        // privileged to get it.
11532                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11533                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11534                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11535                                    allowed = true;
11536                                    break;
11537                                }
11538                            }
11539                        }
11540                        // Also if a privileged parent package on the system image or any of
11541                        // its children requested a privileged permission, the updated child
11542                        // packages can also get the permission.
11543                        if (pkg.parentPackage != null) {
11544                            final PackageSetting disabledSysParentPs = mSettings
11545                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11546                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11547                                    && disabledSysParentPs.isPrivileged()) {
11548                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11549                                    allowed = true;
11550                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11551                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11552                                    for (int i = 0; i < count; i++) {
11553                                        PackageParser.Package disabledSysChildPkg =
11554                                                disabledSysParentPs.pkg.childPackages.get(i);
11555                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11556                                                perm)) {
11557                                            allowed = true;
11558                                            break;
11559                                        }
11560                                    }
11561                                }
11562                            }
11563                        }
11564                    }
11565                } else {
11566                    allowed = isPrivilegedApp(pkg);
11567                }
11568            }
11569        }
11570        if (!allowed) {
11571            if (!allowed && (bp.protectionLevel
11572                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11573                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11574                // If this was a previously normal/dangerous permission that got moved
11575                // to a system permission as part of the runtime permission redesign, then
11576                // we still want to blindly grant it to old apps.
11577                allowed = true;
11578            }
11579            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11580                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11581                // If this permission is to be granted to the system installer and
11582                // this app is an installer, then it gets the permission.
11583                allowed = true;
11584            }
11585            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11586                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11587                // If this permission is to be granted to the system verifier and
11588                // this app is a verifier, then it gets the permission.
11589                allowed = true;
11590            }
11591            if (!allowed && (bp.protectionLevel
11592                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11593                    && isSystemApp(pkg)) {
11594                // Any pre-installed system app is allowed to get this permission.
11595                allowed = true;
11596            }
11597            if (!allowed && (bp.protectionLevel
11598                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11599                // For development permissions, a development permission
11600                // is granted only if it was already granted.
11601                allowed = origPermissions.hasInstallPermission(perm);
11602            }
11603            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11604                    && pkg.packageName.equals(mSetupWizardPackage)) {
11605                // If this permission is to be granted to the system setup wizard and
11606                // this app is a setup wizard, then it gets the permission.
11607                allowed = true;
11608            }
11609        }
11610        return allowed;
11611    }
11612
11613    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11614        final int permCount = pkg.requestedPermissions.size();
11615        for (int j = 0; j < permCount; j++) {
11616            String requestedPermission = pkg.requestedPermissions.get(j);
11617            if (permission.equals(requestedPermission)) {
11618                return true;
11619            }
11620        }
11621        return false;
11622    }
11623
11624    final class ActivityIntentResolver
11625            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11626        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11627                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11628            if (!sUserManager.exists(userId)) return null;
11629            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11630                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11631                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11632            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11633                    isEphemeral, userId);
11634        }
11635
11636        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11637                int userId) {
11638            if (!sUserManager.exists(userId)) return null;
11639            mFlags = flags;
11640            return super.queryIntent(intent, resolvedType,
11641                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11642                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11643                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11644        }
11645
11646        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11647                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11648            if (!sUserManager.exists(userId)) return null;
11649            if (packageActivities == null) {
11650                return null;
11651            }
11652            mFlags = flags;
11653            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11654            final boolean vislbleToEphemeral =
11655                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11656            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11657            final int N = packageActivities.size();
11658            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11659                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11660
11661            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11662            for (int i = 0; i < N; ++i) {
11663                intentFilters = packageActivities.get(i).intents;
11664                if (intentFilters != null && intentFilters.size() > 0) {
11665                    PackageParser.ActivityIntentInfo[] array =
11666                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11667                    intentFilters.toArray(array);
11668                    listCut.add(array);
11669                }
11670            }
11671            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11672                    vislbleToEphemeral, isEphemeral, listCut, userId);
11673        }
11674
11675        /**
11676         * Finds a privileged activity that matches the specified activity names.
11677         */
11678        private PackageParser.Activity findMatchingActivity(
11679                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11680            for (PackageParser.Activity sysActivity : activityList) {
11681                if (sysActivity.info.name.equals(activityInfo.name)) {
11682                    return sysActivity;
11683                }
11684                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11685                    return sysActivity;
11686                }
11687                if (sysActivity.info.targetActivity != null) {
11688                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11689                        return sysActivity;
11690                    }
11691                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11692                        return sysActivity;
11693                    }
11694                }
11695            }
11696            return null;
11697        }
11698
11699        public class IterGenerator<E> {
11700            public Iterator<E> generate(ActivityIntentInfo info) {
11701                return null;
11702            }
11703        }
11704
11705        public class ActionIterGenerator extends IterGenerator<String> {
11706            @Override
11707            public Iterator<String> generate(ActivityIntentInfo info) {
11708                return info.actionsIterator();
11709            }
11710        }
11711
11712        public class CategoriesIterGenerator extends IterGenerator<String> {
11713            @Override
11714            public Iterator<String> generate(ActivityIntentInfo info) {
11715                return info.categoriesIterator();
11716            }
11717        }
11718
11719        public class SchemesIterGenerator extends IterGenerator<String> {
11720            @Override
11721            public Iterator<String> generate(ActivityIntentInfo info) {
11722                return info.schemesIterator();
11723            }
11724        }
11725
11726        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11727            @Override
11728            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11729                return info.authoritiesIterator();
11730            }
11731        }
11732
11733        /**
11734         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11735         * MODIFIED. Do not pass in a list that should not be changed.
11736         */
11737        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11738                IterGenerator<T> generator, Iterator<T> searchIterator) {
11739            // loop through the set of actions; every one must be found in the intent filter
11740            while (searchIterator.hasNext()) {
11741                // we must have at least one filter in the list to consider a match
11742                if (intentList.size() == 0) {
11743                    break;
11744                }
11745
11746                final T searchAction = searchIterator.next();
11747
11748                // loop through the set of intent filters
11749                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11750                while (intentIter.hasNext()) {
11751                    final ActivityIntentInfo intentInfo = intentIter.next();
11752                    boolean selectionFound = false;
11753
11754                    // loop through the intent filter's selection criteria; at least one
11755                    // of them must match the searched criteria
11756                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11757                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11758                        final T intentSelection = intentSelectionIter.next();
11759                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11760                            selectionFound = true;
11761                            break;
11762                        }
11763                    }
11764
11765                    // the selection criteria wasn't found in this filter's set; this filter
11766                    // is not a potential match
11767                    if (!selectionFound) {
11768                        intentIter.remove();
11769                    }
11770                }
11771            }
11772        }
11773
11774        private boolean isProtectedAction(ActivityIntentInfo filter) {
11775            final Iterator<String> actionsIter = filter.actionsIterator();
11776            while (actionsIter != null && actionsIter.hasNext()) {
11777                final String filterAction = actionsIter.next();
11778                if (PROTECTED_ACTIONS.contains(filterAction)) {
11779                    return true;
11780                }
11781            }
11782            return false;
11783        }
11784
11785        /**
11786         * Adjusts the priority of the given intent filter according to policy.
11787         * <p>
11788         * <ul>
11789         * <li>The priority for non privileged applications is capped to '0'</li>
11790         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11791         * <li>The priority for unbundled updates to privileged applications is capped to the
11792         *      priority defined on the system partition</li>
11793         * </ul>
11794         * <p>
11795         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11796         * allowed to obtain any priority on any action.
11797         */
11798        private void adjustPriority(
11799                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11800            // nothing to do; priority is fine as-is
11801            if (intent.getPriority() <= 0) {
11802                return;
11803            }
11804
11805            final ActivityInfo activityInfo = intent.activity.info;
11806            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11807
11808            final boolean privilegedApp =
11809                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11810            if (!privilegedApp) {
11811                // non-privileged applications can never define a priority >0
11812                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11813                        + " package: " + applicationInfo.packageName
11814                        + " activity: " + intent.activity.className
11815                        + " origPrio: " + intent.getPriority());
11816                intent.setPriority(0);
11817                return;
11818            }
11819
11820            if (systemActivities == null) {
11821                // the system package is not disabled; we're parsing the system partition
11822                if (isProtectedAction(intent)) {
11823                    if (mDeferProtectedFilters) {
11824                        // We can't deal with these just yet. No component should ever obtain a
11825                        // >0 priority for a protected actions, with ONE exception -- the setup
11826                        // wizard. The setup wizard, however, cannot be known until we're able to
11827                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11828                        // until all intent filters have been processed. Chicken, meet egg.
11829                        // Let the filter temporarily have a high priority and rectify the
11830                        // priorities after all system packages have been scanned.
11831                        mProtectedFilters.add(intent);
11832                        if (DEBUG_FILTERS) {
11833                            Slog.i(TAG, "Protected action; save for later;"
11834                                    + " package: " + applicationInfo.packageName
11835                                    + " activity: " + intent.activity.className
11836                                    + " origPrio: " + intent.getPriority());
11837                        }
11838                        return;
11839                    } else {
11840                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11841                            Slog.i(TAG, "No setup wizard;"
11842                                + " All protected intents capped to priority 0");
11843                        }
11844                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11845                            if (DEBUG_FILTERS) {
11846                                Slog.i(TAG, "Found setup wizard;"
11847                                    + " allow priority " + intent.getPriority() + ";"
11848                                    + " package: " + intent.activity.info.packageName
11849                                    + " activity: " + intent.activity.className
11850                                    + " priority: " + intent.getPriority());
11851                            }
11852                            // setup wizard gets whatever it wants
11853                            return;
11854                        }
11855                        Slog.w(TAG, "Protected action; cap priority to 0;"
11856                                + " package: " + intent.activity.info.packageName
11857                                + " activity: " + intent.activity.className
11858                                + " origPrio: " + intent.getPriority());
11859                        intent.setPriority(0);
11860                        return;
11861                    }
11862                }
11863                // privileged apps on the system image get whatever priority they request
11864                return;
11865            }
11866
11867            // privileged app unbundled update ... try to find the same activity
11868            final PackageParser.Activity foundActivity =
11869                    findMatchingActivity(systemActivities, activityInfo);
11870            if (foundActivity == null) {
11871                // this is a new activity; it cannot obtain >0 priority
11872                if (DEBUG_FILTERS) {
11873                    Slog.i(TAG, "New activity; cap priority to 0;"
11874                            + " package: " + applicationInfo.packageName
11875                            + " activity: " + intent.activity.className
11876                            + " origPrio: " + intent.getPriority());
11877                }
11878                intent.setPriority(0);
11879                return;
11880            }
11881
11882            // found activity, now check for filter equivalence
11883
11884            // a shallow copy is enough; we modify the list, not its contents
11885            final List<ActivityIntentInfo> intentListCopy =
11886                    new ArrayList<>(foundActivity.intents);
11887            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11888
11889            // find matching action subsets
11890            final Iterator<String> actionsIterator = intent.actionsIterator();
11891            if (actionsIterator != null) {
11892                getIntentListSubset(
11893                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11894                if (intentListCopy.size() == 0) {
11895                    // no more intents to match; we're not equivalent
11896                    if (DEBUG_FILTERS) {
11897                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11898                                + " package: " + applicationInfo.packageName
11899                                + " activity: " + intent.activity.className
11900                                + " origPrio: " + intent.getPriority());
11901                    }
11902                    intent.setPriority(0);
11903                    return;
11904                }
11905            }
11906
11907            // find matching category subsets
11908            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11909            if (categoriesIterator != null) {
11910                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11911                        categoriesIterator);
11912                if (intentListCopy.size() == 0) {
11913                    // no more intents to match; we're not equivalent
11914                    if (DEBUG_FILTERS) {
11915                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11916                                + " package: " + applicationInfo.packageName
11917                                + " activity: " + intent.activity.className
11918                                + " origPrio: " + intent.getPriority());
11919                    }
11920                    intent.setPriority(0);
11921                    return;
11922                }
11923            }
11924
11925            // find matching schemes subsets
11926            final Iterator<String> schemesIterator = intent.schemesIterator();
11927            if (schemesIterator != null) {
11928                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11929                        schemesIterator);
11930                if (intentListCopy.size() == 0) {
11931                    // no more intents to match; we're not equivalent
11932                    if (DEBUG_FILTERS) {
11933                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11934                                + " package: " + applicationInfo.packageName
11935                                + " activity: " + intent.activity.className
11936                                + " origPrio: " + intent.getPriority());
11937                    }
11938                    intent.setPriority(0);
11939                    return;
11940                }
11941            }
11942
11943            // find matching authorities subsets
11944            final Iterator<IntentFilter.AuthorityEntry>
11945                    authoritiesIterator = intent.authoritiesIterator();
11946            if (authoritiesIterator != null) {
11947                getIntentListSubset(intentListCopy,
11948                        new AuthoritiesIterGenerator(),
11949                        authoritiesIterator);
11950                if (intentListCopy.size() == 0) {
11951                    // no more intents to match; we're not equivalent
11952                    if (DEBUG_FILTERS) {
11953                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11954                                + " package: " + applicationInfo.packageName
11955                                + " activity: " + intent.activity.className
11956                                + " origPrio: " + intent.getPriority());
11957                    }
11958                    intent.setPriority(0);
11959                    return;
11960                }
11961            }
11962
11963            // we found matching filter(s); app gets the max priority of all intents
11964            int cappedPriority = 0;
11965            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11966                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11967            }
11968            if (intent.getPriority() > cappedPriority) {
11969                if (DEBUG_FILTERS) {
11970                    Slog.i(TAG, "Found matching filter(s);"
11971                            + " cap priority to " + cappedPriority + ";"
11972                            + " package: " + applicationInfo.packageName
11973                            + " activity: " + intent.activity.className
11974                            + " origPrio: " + intent.getPriority());
11975                }
11976                intent.setPriority(cappedPriority);
11977                return;
11978            }
11979            // all this for nothing; the requested priority was <= what was on the system
11980        }
11981
11982        public final void addActivity(PackageParser.Activity a, String type) {
11983            mActivities.put(a.getComponentName(), a);
11984            if (DEBUG_SHOW_INFO)
11985                Log.v(
11986                TAG, "  " + type + " " +
11987                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11988            if (DEBUG_SHOW_INFO)
11989                Log.v(TAG, "    Class=" + a.info.name);
11990            final int NI = a.intents.size();
11991            for (int j=0; j<NI; j++) {
11992                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11993                if ("activity".equals(type)) {
11994                    final PackageSetting ps =
11995                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11996                    final List<PackageParser.Activity> systemActivities =
11997                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11998                    adjustPriority(systemActivities, intent);
11999                }
12000                if (DEBUG_SHOW_INFO) {
12001                    Log.v(TAG, "    IntentFilter:");
12002                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12003                }
12004                if (!intent.debugCheck()) {
12005                    Log.w(TAG, "==> For Activity " + a.info.name);
12006                }
12007                addFilter(intent);
12008            }
12009        }
12010
12011        public final void removeActivity(PackageParser.Activity a, String type) {
12012            mActivities.remove(a.getComponentName());
12013            if (DEBUG_SHOW_INFO) {
12014                Log.v(TAG, "  " + type + " "
12015                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12016                                : a.info.name) + ":");
12017                Log.v(TAG, "    Class=" + a.info.name);
12018            }
12019            final int NI = a.intents.size();
12020            for (int j=0; j<NI; j++) {
12021                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12022                if (DEBUG_SHOW_INFO) {
12023                    Log.v(TAG, "    IntentFilter:");
12024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12025                }
12026                removeFilter(intent);
12027            }
12028        }
12029
12030        @Override
12031        protected boolean allowFilterResult(
12032                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12033            ActivityInfo filterAi = filter.activity.info;
12034            for (int i=dest.size()-1; i>=0; i--) {
12035                ActivityInfo destAi = dest.get(i).activityInfo;
12036                if (destAi.name == filterAi.name
12037                        && destAi.packageName == filterAi.packageName) {
12038                    return false;
12039                }
12040            }
12041            return true;
12042        }
12043
12044        @Override
12045        protected ActivityIntentInfo[] newArray(int size) {
12046            return new ActivityIntentInfo[size];
12047        }
12048
12049        @Override
12050        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12051            if (!sUserManager.exists(userId)) return true;
12052            PackageParser.Package p = filter.activity.owner;
12053            if (p != null) {
12054                PackageSetting ps = (PackageSetting)p.mExtras;
12055                if (ps != null) {
12056                    // System apps are never considered stopped for purposes of
12057                    // filtering, because there may be no way for the user to
12058                    // actually re-launch them.
12059                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12060                            && ps.getStopped(userId);
12061                }
12062            }
12063            return false;
12064        }
12065
12066        @Override
12067        protected boolean isPackageForFilter(String packageName,
12068                PackageParser.ActivityIntentInfo info) {
12069            return packageName.equals(info.activity.owner.packageName);
12070        }
12071
12072        @Override
12073        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12074                int match, int userId) {
12075            if (!sUserManager.exists(userId)) return null;
12076            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12077                return null;
12078            }
12079            final PackageParser.Activity activity = info.activity;
12080            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12081            if (ps == null) {
12082                return null;
12083            }
12084            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12085                    ps.readUserState(userId), userId);
12086            if (ai == null) {
12087                return null;
12088            }
12089            final ResolveInfo res = new ResolveInfo();
12090            res.activityInfo = ai;
12091            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12092                res.filter = info;
12093            }
12094            if (info != null) {
12095                res.handleAllWebDataURI = info.handleAllWebDataURI();
12096            }
12097            res.priority = info.getPriority();
12098            res.preferredOrder = activity.owner.mPreferredOrder;
12099            //System.out.println("Result: " + res.activityInfo.className +
12100            //                   " = " + res.priority);
12101            res.match = match;
12102            res.isDefault = info.hasDefault;
12103            res.labelRes = info.labelRes;
12104            res.nonLocalizedLabel = info.nonLocalizedLabel;
12105            if (userNeedsBadging(userId)) {
12106                res.noResourceId = true;
12107            } else {
12108                res.icon = info.icon;
12109            }
12110            res.iconResourceId = info.icon;
12111            res.system = res.activityInfo.applicationInfo.isSystemApp();
12112            return res;
12113        }
12114
12115        @Override
12116        protected void sortResults(List<ResolveInfo> results) {
12117            Collections.sort(results, mResolvePrioritySorter);
12118        }
12119
12120        @Override
12121        protected void dumpFilter(PrintWriter out, String prefix,
12122                PackageParser.ActivityIntentInfo filter) {
12123            out.print(prefix); out.print(
12124                    Integer.toHexString(System.identityHashCode(filter.activity)));
12125                    out.print(' ');
12126                    filter.activity.printComponentShortName(out);
12127                    out.print(" filter ");
12128                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12129        }
12130
12131        @Override
12132        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12133            return filter.activity;
12134        }
12135
12136        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12137            PackageParser.Activity activity = (PackageParser.Activity)label;
12138            out.print(prefix); out.print(
12139                    Integer.toHexString(System.identityHashCode(activity)));
12140                    out.print(' ');
12141                    activity.printComponentShortName(out);
12142            if (count > 1) {
12143                out.print(" ("); out.print(count); out.print(" filters)");
12144            }
12145            out.println();
12146        }
12147
12148        // Keys are String (activity class name), values are Activity.
12149        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12150                = new ArrayMap<ComponentName, PackageParser.Activity>();
12151        private int mFlags;
12152    }
12153
12154    private final class ServiceIntentResolver
12155            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12156        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12157                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12158            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12159            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12160                    isEphemeral, userId);
12161        }
12162
12163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12164                int userId) {
12165            if (!sUserManager.exists(userId)) return null;
12166            mFlags = flags;
12167            return super.queryIntent(intent, resolvedType,
12168                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12169                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12170                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12171        }
12172
12173        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12174                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12175            if (!sUserManager.exists(userId)) return null;
12176            if (packageServices == null) {
12177                return null;
12178            }
12179            mFlags = flags;
12180            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12181            final boolean vislbleToEphemeral =
12182                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12183            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12184            final int N = packageServices.size();
12185            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12186                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12187
12188            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12189            for (int i = 0; i < N; ++i) {
12190                intentFilters = packageServices.get(i).intents;
12191                if (intentFilters != null && intentFilters.size() > 0) {
12192                    PackageParser.ServiceIntentInfo[] array =
12193                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12194                    intentFilters.toArray(array);
12195                    listCut.add(array);
12196                }
12197            }
12198            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12199                    vislbleToEphemeral, isEphemeral, listCut, userId);
12200        }
12201
12202        public final void addService(PackageParser.Service s) {
12203            mServices.put(s.getComponentName(), s);
12204            if (DEBUG_SHOW_INFO) {
12205                Log.v(TAG, "  "
12206                        + (s.info.nonLocalizedLabel != null
12207                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12208                Log.v(TAG, "    Class=" + s.info.name);
12209            }
12210            final int NI = s.intents.size();
12211            int j;
12212            for (j=0; j<NI; j++) {
12213                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12214                if (DEBUG_SHOW_INFO) {
12215                    Log.v(TAG, "    IntentFilter:");
12216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12217                }
12218                if (!intent.debugCheck()) {
12219                    Log.w(TAG, "==> For Service " + s.info.name);
12220                }
12221                addFilter(intent);
12222            }
12223        }
12224
12225        public final void removeService(PackageParser.Service s) {
12226            mServices.remove(s.getComponentName());
12227            if (DEBUG_SHOW_INFO) {
12228                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12229                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12230                Log.v(TAG, "    Class=" + s.info.name);
12231            }
12232            final int NI = s.intents.size();
12233            int j;
12234            for (j=0; j<NI; j++) {
12235                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12236                if (DEBUG_SHOW_INFO) {
12237                    Log.v(TAG, "    IntentFilter:");
12238                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12239                }
12240                removeFilter(intent);
12241            }
12242        }
12243
12244        @Override
12245        protected boolean allowFilterResult(
12246                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12247            ServiceInfo filterSi = filter.service.info;
12248            for (int i=dest.size()-1; i>=0; i--) {
12249                ServiceInfo destAi = dest.get(i).serviceInfo;
12250                if (destAi.name == filterSi.name
12251                        && destAi.packageName == filterSi.packageName) {
12252                    return false;
12253                }
12254            }
12255            return true;
12256        }
12257
12258        @Override
12259        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12260            return new PackageParser.ServiceIntentInfo[size];
12261        }
12262
12263        @Override
12264        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12265            if (!sUserManager.exists(userId)) return true;
12266            PackageParser.Package p = filter.service.owner;
12267            if (p != null) {
12268                PackageSetting ps = (PackageSetting)p.mExtras;
12269                if (ps != null) {
12270                    // System apps are never considered stopped for purposes of
12271                    // filtering, because there may be no way for the user to
12272                    // actually re-launch them.
12273                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12274                            && ps.getStopped(userId);
12275                }
12276            }
12277            return false;
12278        }
12279
12280        @Override
12281        protected boolean isPackageForFilter(String packageName,
12282                PackageParser.ServiceIntentInfo info) {
12283            return packageName.equals(info.service.owner.packageName);
12284        }
12285
12286        @Override
12287        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12288                int match, int userId) {
12289            if (!sUserManager.exists(userId)) return null;
12290            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12291            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12292                return null;
12293            }
12294            final PackageParser.Service service = info.service;
12295            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12296            if (ps == null) {
12297                return null;
12298            }
12299            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12300                    ps.readUserState(userId), userId);
12301            if (si == null) {
12302                return null;
12303            }
12304            final ResolveInfo res = new ResolveInfo();
12305            res.serviceInfo = si;
12306            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12307                res.filter = filter;
12308            }
12309            res.priority = info.getPriority();
12310            res.preferredOrder = service.owner.mPreferredOrder;
12311            res.match = match;
12312            res.isDefault = info.hasDefault;
12313            res.labelRes = info.labelRes;
12314            res.nonLocalizedLabel = info.nonLocalizedLabel;
12315            res.icon = info.icon;
12316            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12317            return res;
12318        }
12319
12320        @Override
12321        protected void sortResults(List<ResolveInfo> results) {
12322            Collections.sort(results, mResolvePrioritySorter);
12323        }
12324
12325        @Override
12326        protected void dumpFilter(PrintWriter out, String prefix,
12327                PackageParser.ServiceIntentInfo filter) {
12328            out.print(prefix); out.print(
12329                    Integer.toHexString(System.identityHashCode(filter.service)));
12330                    out.print(' ');
12331                    filter.service.printComponentShortName(out);
12332                    out.print(" filter ");
12333                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12334        }
12335
12336        @Override
12337        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12338            return filter.service;
12339        }
12340
12341        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12342            PackageParser.Service service = (PackageParser.Service)label;
12343            out.print(prefix); out.print(
12344                    Integer.toHexString(System.identityHashCode(service)));
12345                    out.print(' ');
12346                    service.printComponentShortName(out);
12347            if (count > 1) {
12348                out.print(" ("); out.print(count); out.print(" filters)");
12349            }
12350            out.println();
12351        }
12352
12353//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12354//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12355//            final List<ResolveInfo> retList = Lists.newArrayList();
12356//            while (i.hasNext()) {
12357//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12358//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12359//                    retList.add(resolveInfo);
12360//                }
12361//            }
12362//            return retList;
12363//        }
12364
12365        // Keys are String (activity class name), values are Activity.
12366        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12367                = new ArrayMap<ComponentName, PackageParser.Service>();
12368        private int mFlags;
12369    }
12370
12371    private final class ProviderIntentResolver
12372            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12374                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12375            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12376            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12377                    isEphemeral, userId);
12378        }
12379
12380        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12381                int userId) {
12382            if (!sUserManager.exists(userId))
12383                return null;
12384            mFlags = flags;
12385            return super.queryIntent(intent, resolvedType,
12386                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12387                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12388                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12389        }
12390
12391        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12392                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12393            if (!sUserManager.exists(userId))
12394                return null;
12395            if (packageProviders == null) {
12396                return null;
12397            }
12398            mFlags = flags;
12399            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12400            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12401            final boolean vislbleToEphemeral =
12402                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12403            final int N = packageProviders.size();
12404            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12405                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12406
12407            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12408            for (int i = 0; i < N; ++i) {
12409                intentFilters = packageProviders.get(i).intents;
12410                if (intentFilters != null && intentFilters.size() > 0) {
12411                    PackageParser.ProviderIntentInfo[] array =
12412                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12413                    intentFilters.toArray(array);
12414                    listCut.add(array);
12415                }
12416            }
12417            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12418                    vislbleToEphemeral, isEphemeral, listCut, userId);
12419        }
12420
12421        public final void addProvider(PackageParser.Provider p) {
12422            if (mProviders.containsKey(p.getComponentName())) {
12423                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12424                return;
12425            }
12426
12427            mProviders.put(p.getComponentName(), p);
12428            if (DEBUG_SHOW_INFO) {
12429                Log.v(TAG, "  "
12430                        + (p.info.nonLocalizedLabel != null
12431                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12432                Log.v(TAG, "    Class=" + p.info.name);
12433            }
12434            final int NI = p.intents.size();
12435            int j;
12436            for (j = 0; j < NI; j++) {
12437                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12438                if (DEBUG_SHOW_INFO) {
12439                    Log.v(TAG, "    IntentFilter:");
12440                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12441                }
12442                if (!intent.debugCheck()) {
12443                    Log.w(TAG, "==> For Provider " + p.info.name);
12444                }
12445                addFilter(intent);
12446            }
12447        }
12448
12449        public final void removeProvider(PackageParser.Provider p) {
12450            mProviders.remove(p.getComponentName());
12451            if (DEBUG_SHOW_INFO) {
12452                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12453                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12454                Log.v(TAG, "    Class=" + p.info.name);
12455            }
12456            final int NI = p.intents.size();
12457            int j;
12458            for (j = 0; j < NI; j++) {
12459                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12460                if (DEBUG_SHOW_INFO) {
12461                    Log.v(TAG, "    IntentFilter:");
12462                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12463                }
12464                removeFilter(intent);
12465            }
12466        }
12467
12468        @Override
12469        protected boolean allowFilterResult(
12470                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12471            ProviderInfo filterPi = filter.provider.info;
12472            for (int i = dest.size() - 1; i >= 0; i--) {
12473                ProviderInfo destPi = dest.get(i).providerInfo;
12474                if (destPi.name == filterPi.name
12475                        && destPi.packageName == filterPi.packageName) {
12476                    return false;
12477                }
12478            }
12479            return true;
12480        }
12481
12482        @Override
12483        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12484            return new PackageParser.ProviderIntentInfo[size];
12485        }
12486
12487        @Override
12488        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12489            if (!sUserManager.exists(userId))
12490                return true;
12491            PackageParser.Package p = filter.provider.owner;
12492            if (p != null) {
12493                PackageSetting ps = (PackageSetting) p.mExtras;
12494                if (ps != null) {
12495                    // System apps are never considered stopped for purposes of
12496                    // filtering, because there may be no way for the user to
12497                    // actually re-launch them.
12498                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12499                            && ps.getStopped(userId);
12500                }
12501            }
12502            return false;
12503        }
12504
12505        @Override
12506        protected boolean isPackageForFilter(String packageName,
12507                PackageParser.ProviderIntentInfo info) {
12508            return packageName.equals(info.provider.owner.packageName);
12509        }
12510
12511        @Override
12512        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12513                int match, int userId) {
12514            if (!sUserManager.exists(userId))
12515                return null;
12516            final PackageParser.ProviderIntentInfo info = filter;
12517            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12518                return null;
12519            }
12520            final PackageParser.Provider provider = info.provider;
12521            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12522            if (ps == null) {
12523                return null;
12524            }
12525            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12526                    ps.readUserState(userId), userId);
12527            if (pi == null) {
12528                return null;
12529            }
12530            final ResolveInfo res = new ResolveInfo();
12531            res.providerInfo = pi;
12532            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12533                res.filter = filter;
12534            }
12535            res.priority = info.getPriority();
12536            res.preferredOrder = provider.owner.mPreferredOrder;
12537            res.match = match;
12538            res.isDefault = info.hasDefault;
12539            res.labelRes = info.labelRes;
12540            res.nonLocalizedLabel = info.nonLocalizedLabel;
12541            res.icon = info.icon;
12542            res.system = res.providerInfo.applicationInfo.isSystemApp();
12543            return res;
12544        }
12545
12546        @Override
12547        protected void sortResults(List<ResolveInfo> results) {
12548            Collections.sort(results, mResolvePrioritySorter);
12549        }
12550
12551        @Override
12552        protected void dumpFilter(PrintWriter out, String prefix,
12553                PackageParser.ProviderIntentInfo filter) {
12554            out.print(prefix);
12555            out.print(
12556                    Integer.toHexString(System.identityHashCode(filter.provider)));
12557            out.print(' ');
12558            filter.provider.printComponentShortName(out);
12559            out.print(" filter ");
12560            out.println(Integer.toHexString(System.identityHashCode(filter)));
12561        }
12562
12563        @Override
12564        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12565            return filter.provider;
12566        }
12567
12568        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12569            PackageParser.Provider provider = (PackageParser.Provider)label;
12570            out.print(prefix); out.print(
12571                    Integer.toHexString(System.identityHashCode(provider)));
12572                    out.print(' ');
12573                    provider.printComponentShortName(out);
12574            if (count > 1) {
12575                out.print(" ("); out.print(count); out.print(" filters)");
12576            }
12577            out.println();
12578        }
12579
12580        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12581                = new ArrayMap<ComponentName, PackageParser.Provider>();
12582        private int mFlags;
12583    }
12584
12585    static final class EphemeralIntentResolver
12586            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12587        /**
12588         * The result that has the highest defined order. Ordering applies on a
12589         * per-package basis. Mapping is from package name to Pair of order and
12590         * EphemeralResolveInfo.
12591         * <p>
12592         * NOTE: This is implemented as a field variable for convenience and efficiency.
12593         * By having a field variable, we're able to track filter ordering as soon as
12594         * a non-zero order is defined. Otherwise, multiple loops across the result set
12595         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12596         * this needs to be contained entirely within {@link #filterResults()}.
12597         */
12598        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12599
12600        @Override
12601        protected EphemeralResponse[] newArray(int size) {
12602            return new EphemeralResponse[size];
12603        }
12604
12605        @Override
12606        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12607            return true;
12608        }
12609
12610        @Override
12611        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12612                int userId) {
12613            if (!sUserManager.exists(userId)) {
12614                return null;
12615            }
12616            final String packageName = responseObj.resolveInfo.getPackageName();
12617            final Integer order = responseObj.getOrder();
12618            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12619                    mOrderResult.get(packageName);
12620            // ordering is enabled and this item's order isn't high enough
12621            if (lastOrderResult != null && lastOrderResult.first >= order) {
12622                return null;
12623            }
12624            final EphemeralResolveInfo res = responseObj.resolveInfo;
12625            if (order > 0) {
12626                // non-zero order, enable ordering
12627                mOrderResult.put(packageName, new Pair<>(order, res));
12628            }
12629            return responseObj;
12630        }
12631
12632        @Override
12633        protected void filterResults(List<EphemeralResponse> results) {
12634            // only do work if ordering is enabled [most of the time it won't be]
12635            if (mOrderResult.size() == 0) {
12636                return;
12637            }
12638            int resultSize = results.size();
12639            for (int i = 0; i < resultSize; i++) {
12640                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12641                final String packageName = info.getPackageName();
12642                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12643                if (savedInfo == null) {
12644                    // package doesn't having ordering
12645                    continue;
12646                }
12647                if (savedInfo.second == info) {
12648                    // circled back to the highest ordered item; remove from order list
12649                    mOrderResult.remove(savedInfo);
12650                    if (mOrderResult.size() == 0) {
12651                        // no more ordered items
12652                        break;
12653                    }
12654                    continue;
12655                }
12656                // item has a worse order, remove it from the result list
12657                results.remove(i);
12658                resultSize--;
12659                i--;
12660            }
12661        }
12662    }
12663
12664    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12665            new Comparator<ResolveInfo>() {
12666        public int compare(ResolveInfo r1, ResolveInfo r2) {
12667            int v1 = r1.priority;
12668            int v2 = r2.priority;
12669            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12670            if (v1 != v2) {
12671                return (v1 > v2) ? -1 : 1;
12672            }
12673            v1 = r1.preferredOrder;
12674            v2 = r2.preferredOrder;
12675            if (v1 != v2) {
12676                return (v1 > v2) ? -1 : 1;
12677            }
12678            if (r1.isDefault != r2.isDefault) {
12679                return r1.isDefault ? -1 : 1;
12680            }
12681            v1 = r1.match;
12682            v2 = r2.match;
12683            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12684            if (v1 != v2) {
12685                return (v1 > v2) ? -1 : 1;
12686            }
12687            if (r1.system != r2.system) {
12688                return r1.system ? -1 : 1;
12689            }
12690            if (r1.activityInfo != null) {
12691                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12692            }
12693            if (r1.serviceInfo != null) {
12694                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12695            }
12696            if (r1.providerInfo != null) {
12697                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12698            }
12699            return 0;
12700        }
12701    };
12702
12703    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12704            new Comparator<ProviderInfo>() {
12705        public int compare(ProviderInfo p1, ProviderInfo p2) {
12706            final int v1 = p1.initOrder;
12707            final int v2 = p2.initOrder;
12708            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12709        }
12710    };
12711
12712    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12713            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12714            final int[] userIds) {
12715        mHandler.post(new Runnable() {
12716            @Override
12717            public void run() {
12718                try {
12719                    final IActivityManager am = ActivityManager.getService();
12720                    if (am == null) return;
12721                    final int[] resolvedUserIds;
12722                    if (userIds == null) {
12723                        resolvedUserIds = am.getRunningUserIds();
12724                    } else {
12725                        resolvedUserIds = userIds;
12726                    }
12727                    for (int id : resolvedUserIds) {
12728                        final Intent intent = new Intent(action,
12729                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12730                        if (extras != null) {
12731                            intent.putExtras(extras);
12732                        }
12733                        if (targetPkg != null) {
12734                            intent.setPackage(targetPkg);
12735                        }
12736                        // Modify the UID when posting to other users
12737                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12738                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12739                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12740                            intent.putExtra(Intent.EXTRA_UID, uid);
12741                        }
12742                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12743                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12744                        if (DEBUG_BROADCASTS) {
12745                            RuntimeException here = new RuntimeException("here");
12746                            here.fillInStackTrace();
12747                            Slog.d(TAG, "Sending to user " + id + ": "
12748                                    + intent.toShortString(false, true, false, false)
12749                                    + " " + intent.getExtras(), here);
12750                        }
12751                        am.broadcastIntent(null, intent, null, finishedReceiver,
12752                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12753                                null, finishedReceiver != null, false, id);
12754                    }
12755                } catch (RemoteException ex) {
12756                }
12757            }
12758        });
12759    }
12760
12761    /**
12762     * Check if the external storage media is available. This is true if there
12763     * is a mounted external storage medium or if the external storage is
12764     * emulated.
12765     */
12766    private boolean isExternalMediaAvailable() {
12767        return mMediaMounted || Environment.isExternalStorageEmulated();
12768    }
12769
12770    @Override
12771    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12772        // writer
12773        synchronized (mPackages) {
12774            if (!isExternalMediaAvailable()) {
12775                // If the external storage is no longer mounted at this point,
12776                // the caller may not have been able to delete all of this
12777                // packages files and can not delete any more.  Bail.
12778                return null;
12779            }
12780            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12781            if (lastPackage != null) {
12782                pkgs.remove(lastPackage);
12783            }
12784            if (pkgs.size() > 0) {
12785                return pkgs.get(0);
12786            }
12787        }
12788        return null;
12789    }
12790
12791    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12792        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12793                userId, andCode ? 1 : 0, packageName);
12794        if (mSystemReady) {
12795            msg.sendToTarget();
12796        } else {
12797            if (mPostSystemReadyMessages == null) {
12798                mPostSystemReadyMessages = new ArrayList<>();
12799            }
12800            mPostSystemReadyMessages.add(msg);
12801        }
12802    }
12803
12804    void startCleaningPackages() {
12805        // reader
12806        if (!isExternalMediaAvailable()) {
12807            return;
12808        }
12809        synchronized (mPackages) {
12810            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12811                return;
12812            }
12813        }
12814        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12815        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12816        IActivityManager am = ActivityManager.getService();
12817        if (am != null) {
12818            try {
12819                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12820                        UserHandle.USER_SYSTEM);
12821            } catch (RemoteException e) {
12822            }
12823        }
12824    }
12825
12826    @Override
12827    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12828            int installFlags, String installerPackageName, int userId) {
12829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12830
12831        final int callingUid = Binder.getCallingUid();
12832        enforceCrossUserPermission(callingUid, userId,
12833                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12834
12835        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12836            try {
12837                if (observer != null) {
12838                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12839                }
12840            } catch (RemoteException re) {
12841            }
12842            return;
12843        }
12844
12845        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12846            installFlags |= PackageManager.INSTALL_FROM_ADB;
12847
12848        } else {
12849            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12850            // about installerPackageName.
12851
12852            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12853            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12854        }
12855
12856        UserHandle user;
12857        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12858            user = UserHandle.ALL;
12859        } else {
12860            user = new UserHandle(userId);
12861        }
12862
12863        // Only system components can circumvent runtime permissions when installing.
12864        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12865                && mContext.checkCallingOrSelfPermission(Manifest.permission
12866                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12867            throw new SecurityException("You need the "
12868                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12869                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12870        }
12871
12872        final File originFile = new File(originPath);
12873        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12874
12875        final Message msg = mHandler.obtainMessage(INIT_COPY);
12876        final VerificationInfo verificationInfo = new VerificationInfo(
12877                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12878        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12879                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12880                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12881                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12882        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12883        msg.obj = params;
12884
12885        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12886                System.identityHashCode(msg.obj));
12887        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12888                System.identityHashCode(msg.obj));
12889
12890        mHandler.sendMessage(msg);
12891    }
12892
12893
12894    /**
12895     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12896     * it is acting on behalf on an enterprise or the user).
12897     *
12898     * Note that the ordering of the conditionals in this method is important. The checks we perform
12899     * are as follows, in this order:
12900     *
12901     * 1) If the install is being performed by a system app, we can trust the app to have set the
12902     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12903     *    what it is.
12904     * 2) If the install is being performed by a device or profile owner app, the install reason
12905     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12906     *    set the install reason correctly. If the app targets an older SDK version where install
12907     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12908     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12909     * 3) In all other cases, the install is being performed by a regular app that is neither part
12910     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12911     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12912     *    set to enterprise policy and if so, change it to unknown instead.
12913     */
12914    private int fixUpInstallReason(String installerPackageName, int installerUid,
12915            int installReason) {
12916        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12917                == PERMISSION_GRANTED) {
12918            // If the install is being performed by a system app, we trust that app to have set the
12919            // install reason correctly.
12920            return installReason;
12921        }
12922
12923        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12924            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12925        if (dpm != null) {
12926            ComponentName owner = null;
12927            try {
12928                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12929                if (owner == null) {
12930                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12931                }
12932            } catch (RemoteException e) {
12933            }
12934            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12935                // If the install is being performed by a device or profile owner, the install
12936                // reason should be enterprise policy.
12937                return PackageManager.INSTALL_REASON_POLICY;
12938            }
12939        }
12940
12941        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12942            // If the install is being performed by a regular app (i.e. neither system app nor
12943            // device or profile owner), we have no reason to believe that the app is acting on
12944            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12945            // change it to unknown instead.
12946            return PackageManager.INSTALL_REASON_UNKNOWN;
12947        }
12948
12949        // If the install is being performed by a regular app and the install reason was set to any
12950        // value but enterprise policy, leave the install reason unchanged.
12951        return installReason;
12952    }
12953
12954    void installStage(String packageName, File stagedDir, String stagedCid,
12955            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12956            String installerPackageName, int installerUid, UserHandle user,
12957            Certificate[][] certificates) {
12958        if (DEBUG_EPHEMERAL) {
12959            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12960                Slog.d(TAG, "Ephemeral install of " + packageName);
12961            }
12962        }
12963        final VerificationInfo verificationInfo = new VerificationInfo(
12964                sessionParams.originatingUri, sessionParams.referrerUri,
12965                sessionParams.originatingUid, installerUid);
12966
12967        final OriginInfo origin;
12968        if (stagedDir != null) {
12969            origin = OriginInfo.fromStagedFile(stagedDir);
12970        } else {
12971            origin = OriginInfo.fromStagedContainer(stagedCid);
12972        }
12973
12974        final Message msg = mHandler.obtainMessage(INIT_COPY);
12975        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12976                sessionParams.installReason);
12977        final InstallParams params = new InstallParams(origin, null, observer,
12978                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12979                verificationInfo, user, sessionParams.abiOverride,
12980                sessionParams.grantedRuntimePermissions, certificates, installReason);
12981        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12982        msg.obj = params;
12983
12984        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12985                System.identityHashCode(msg.obj));
12986        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12987                System.identityHashCode(msg.obj));
12988
12989        mHandler.sendMessage(msg);
12990    }
12991
12992    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12993            int userId) {
12994        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12995        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12996    }
12997
12998    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12999            int appId, int... userIds) {
13000        if (ArrayUtils.isEmpty(userIds)) {
13001            return;
13002        }
13003        Bundle extras = new Bundle(1);
13004        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13005        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13006
13007        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13008                packageName, extras, 0, null, null, userIds);
13009        if (isSystem) {
13010            mHandler.post(() -> {
13011                        for (int userId : userIds) {
13012                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13013                        }
13014                    }
13015            );
13016        }
13017    }
13018
13019    /**
13020     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13021     * automatically without needing an explicit launch.
13022     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13023     */
13024    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13025        // If user is not running, the app didn't miss any broadcast
13026        if (!mUserManagerInternal.isUserRunning(userId)) {
13027            return;
13028        }
13029        final IActivityManager am = ActivityManager.getService();
13030        try {
13031            // Deliver LOCKED_BOOT_COMPLETED first
13032            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13033                    .setPackage(packageName);
13034            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13035            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13036                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13037
13038            // Deliver BOOT_COMPLETED only if user is unlocked
13039            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13040                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13041                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13042                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13043            }
13044        } catch (RemoteException e) {
13045            throw e.rethrowFromSystemServer();
13046        }
13047    }
13048
13049    @Override
13050    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13051            int userId) {
13052        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13053        PackageSetting pkgSetting;
13054        final int uid = Binder.getCallingUid();
13055        enforceCrossUserPermission(uid, userId,
13056                true /* requireFullPermission */, true /* checkShell */,
13057                "setApplicationHiddenSetting for user " + userId);
13058
13059        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13060            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13061            return false;
13062        }
13063
13064        long callingId = Binder.clearCallingIdentity();
13065        try {
13066            boolean sendAdded = false;
13067            boolean sendRemoved = false;
13068            // writer
13069            synchronized (mPackages) {
13070                pkgSetting = mSettings.mPackages.get(packageName);
13071                if (pkgSetting == null) {
13072                    return false;
13073                }
13074                // Do not allow "android" is being disabled
13075                if ("android".equals(packageName)) {
13076                    Slog.w(TAG, "Cannot hide package: android");
13077                    return false;
13078                }
13079                // Cannot hide static shared libs as they are considered
13080                // a part of the using app (emulating static linking). Also
13081                // static libs are installed always on internal storage.
13082                PackageParser.Package pkg = mPackages.get(packageName);
13083                if (pkg != null && pkg.staticSharedLibName != null) {
13084                    Slog.w(TAG, "Cannot hide package: " + packageName
13085                            + " providing static shared library: "
13086                            + pkg.staticSharedLibName);
13087                    return false;
13088                }
13089                // Only allow protected packages to hide themselves.
13090                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13091                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13092                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13093                    return false;
13094                }
13095
13096                if (pkgSetting.getHidden(userId) != hidden) {
13097                    pkgSetting.setHidden(hidden, userId);
13098                    mSettings.writePackageRestrictionsLPr(userId);
13099                    if (hidden) {
13100                        sendRemoved = true;
13101                    } else {
13102                        sendAdded = true;
13103                    }
13104                }
13105            }
13106            if (sendAdded) {
13107                sendPackageAddedForUser(packageName, pkgSetting, userId);
13108                return true;
13109            }
13110            if (sendRemoved) {
13111                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13112                        "hiding pkg");
13113                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13114                return true;
13115            }
13116        } finally {
13117            Binder.restoreCallingIdentity(callingId);
13118        }
13119        return false;
13120    }
13121
13122    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13123            int userId) {
13124        final PackageRemovedInfo info = new PackageRemovedInfo();
13125        info.removedPackage = packageName;
13126        info.removedUsers = new int[] {userId};
13127        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13128        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13129    }
13130
13131    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13132        if (pkgList.length > 0) {
13133            Bundle extras = new Bundle(1);
13134            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13135
13136            sendPackageBroadcast(
13137                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13138                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13139                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13140                    new int[] {userId});
13141        }
13142    }
13143
13144    /**
13145     * Returns true if application is not found or there was an error. Otherwise it returns
13146     * the hidden state of the package for the given user.
13147     */
13148    @Override
13149    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13150        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13152                true /* requireFullPermission */, false /* checkShell */,
13153                "getApplicationHidden for user " + userId);
13154        PackageSetting pkgSetting;
13155        long callingId = Binder.clearCallingIdentity();
13156        try {
13157            // writer
13158            synchronized (mPackages) {
13159                pkgSetting = mSettings.mPackages.get(packageName);
13160                if (pkgSetting == null) {
13161                    return true;
13162                }
13163                return pkgSetting.getHidden(userId);
13164            }
13165        } finally {
13166            Binder.restoreCallingIdentity(callingId);
13167        }
13168    }
13169
13170    /**
13171     * @hide
13172     */
13173    @Override
13174    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13175        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13176                null);
13177        PackageSetting pkgSetting;
13178        final int uid = Binder.getCallingUid();
13179        enforceCrossUserPermission(uid, userId,
13180                true /* requireFullPermission */, true /* checkShell */,
13181                "installExistingPackage for user " + userId);
13182        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13183            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13184        }
13185
13186        long callingId = Binder.clearCallingIdentity();
13187        try {
13188            boolean installed = false;
13189
13190            // writer
13191            synchronized (mPackages) {
13192                pkgSetting = mSettings.mPackages.get(packageName);
13193                if (pkgSetting == null) {
13194                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13195                }
13196                if (!pkgSetting.getInstalled(userId)) {
13197                    pkgSetting.setInstalled(true, userId);
13198                    pkgSetting.setHidden(false, userId);
13199                    pkgSetting.setInstallReason(installReason, userId);
13200                    mSettings.writePackageRestrictionsLPr(userId);
13201                    installed = true;
13202                }
13203            }
13204
13205            if (installed) {
13206                if (pkgSetting.pkg != null) {
13207                    synchronized (mInstallLock) {
13208                        // We don't need to freeze for a brand new install
13209                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13210                    }
13211                }
13212                sendPackageAddedForUser(packageName, pkgSetting, userId);
13213            }
13214        } finally {
13215            Binder.restoreCallingIdentity(callingId);
13216        }
13217
13218        return PackageManager.INSTALL_SUCCEEDED;
13219    }
13220
13221    boolean isUserRestricted(int userId, String restrictionKey) {
13222        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13223        if (restrictions.getBoolean(restrictionKey, false)) {
13224            Log.w(TAG, "User is restricted: " + restrictionKey);
13225            return true;
13226        }
13227        return false;
13228    }
13229
13230    @Override
13231    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13232            int userId) {
13233        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13235                true /* requireFullPermission */, true /* checkShell */,
13236                "setPackagesSuspended for user " + userId);
13237
13238        if (ArrayUtils.isEmpty(packageNames)) {
13239            return packageNames;
13240        }
13241
13242        // List of package names for whom the suspended state has changed.
13243        List<String> changedPackages = new ArrayList<>(packageNames.length);
13244        // List of package names for whom the suspended state is not set as requested in this
13245        // method.
13246        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13247        long callingId = Binder.clearCallingIdentity();
13248        try {
13249            for (int i = 0; i < packageNames.length; i++) {
13250                String packageName = packageNames[i];
13251                boolean changed = false;
13252                final int appId;
13253                synchronized (mPackages) {
13254                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13255                    if (pkgSetting == null) {
13256                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13257                                + "\". Skipping suspending/un-suspending.");
13258                        unactionedPackages.add(packageName);
13259                        continue;
13260                    }
13261                    appId = pkgSetting.appId;
13262                    if (pkgSetting.getSuspended(userId) != suspended) {
13263                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13264                            unactionedPackages.add(packageName);
13265                            continue;
13266                        }
13267                        pkgSetting.setSuspended(suspended, userId);
13268                        mSettings.writePackageRestrictionsLPr(userId);
13269                        changed = true;
13270                        changedPackages.add(packageName);
13271                    }
13272                }
13273
13274                if (changed && suspended) {
13275                    killApplication(packageName, UserHandle.getUid(userId, appId),
13276                            "suspending package");
13277                }
13278            }
13279        } finally {
13280            Binder.restoreCallingIdentity(callingId);
13281        }
13282
13283        if (!changedPackages.isEmpty()) {
13284            sendPackagesSuspendedForUser(changedPackages.toArray(
13285                    new String[changedPackages.size()]), userId, suspended);
13286        }
13287
13288        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13289    }
13290
13291    @Override
13292    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13294                true /* requireFullPermission */, false /* checkShell */,
13295                "isPackageSuspendedForUser for user " + userId);
13296        synchronized (mPackages) {
13297            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13298            if (pkgSetting == null) {
13299                throw new IllegalArgumentException("Unknown target package: " + packageName);
13300            }
13301            return pkgSetting.getSuspended(userId);
13302        }
13303    }
13304
13305    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13306        if (isPackageDeviceAdmin(packageName, userId)) {
13307            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13308                    + "\": has an active device admin");
13309            return false;
13310        }
13311
13312        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13313        if (packageName.equals(activeLauncherPackageName)) {
13314            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13315                    + "\": contains the active launcher");
13316            return false;
13317        }
13318
13319        if (packageName.equals(mRequiredInstallerPackage)) {
13320            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13321                    + "\": required for package installation");
13322            return false;
13323        }
13324
13325        if (packageName.equals(mRequiredUninstallerPackage)) {
13326            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13327                    + "\": required for package uninstallation");
13328            return false;
13329        }
13330
13331        if (packageName.equals(mRequiredVerifierPackage)) {
13332            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13333                    + "\": required for package verification");
13334            return false;
13335        }
13336
13337        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13338            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13339                    + "\": is the default dialer");
13340            return false;
13341        }
13342
13343        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13344            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13345                    + "\": protected package");
13346            return false;
13347        }
13348
13349        // Cannot suspend static shared libs as they are considered
13350        // a part of the using app (emulating static linking). Also
13351        // static libs are installed always on internal storage.
13352        PackageParser.Package pkg = mPackages.get(packageName);
13353        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13354            Slog.w(TAG, "Cannot suspend package: " + packageName
13355                    + " providing static shared library: "
13356                    + pkg.staticSharedLibName);
13357            return false;
13358        }
13359
13360        return true;
13361    }
13362
13363    private String getActiveLauncherPackageName(int userId) {
13364        Intent intent = new Intent(Intent.ACTION_MAIN);
13365        intent.addCategory(Intent.CATEGORY_HOME);
13366        ResolveInfo resolveInfo = resolveIntent(
13367                intent,
13368                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13369                PackageManager.MATCH_DEFAULT_ONLY,
13370                userId);
13371
13372        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13373    }
13374
13375    private String getDefaultDialerPackageName(int userId) {
13376        synchronized (mPackages) {
13377            return mSettings.getDefaultDialerPackageNameLPw(userId);
13378        }
13379    }
13380
13381    @Override
13382    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13383        mContext.enforceCallingOrSelfPermission(
13384                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13385                "Only package verification agents can verify applications");
13386
13387        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13388        final PackageVerificationResponse response = new PackageVerificationResponse(
13389                verificationCode, Binder.getCallingUid());
13390        msg.arg1 = id;
13391        msg.obj = response;
13392        mHandler.sendMessage(msg);
13393    }
13394
13395    @Override
13396    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13397            long millisecondsToDelay) {
13398        mContext.enforceCallingOrSelfPermission(
13399                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13400                "Only package verification agents can extend verification timeouts");
13401
13402        final PackageVerificationState state = mPendingVerification.get(id);
13403        final PackageVerificationResponse response = new PackageVerificationResponse(
13404                verificationCodeAtTimeout, Binder.getCallingUid());
13405
13406        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13407            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13408        }
13409        if (millisecondsToDelay < 0) {
13410            millisecondsToDelay = 0;
13411        }
13412        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13413                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13414            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13415        }
13416
13417        if ((state != null) && !state.timeoutExtended()) {
13418            state.extendTimeout();
13419
13420            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13421            msg.arg1 = id;
13422            msg.obj = response;
13423            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13424        }
13425    }
13426
13427    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13428            int verificationCode, UserHandle user) {
13429        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13430        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13431        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13432        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13433        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13434
13435        mContext.sendBroadcastAsUser(intent, user,
13436                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13437    }
13438
13439    private ComponentName matchComponentForVerifier(String packageName,
13440            List<ResolveInfo> receivers) {
13441        ActivityInfo targetReceiver = null;
13442
13443        final int NR = receivers.size();
13444        for (int i = 0; i < NR; i++) {
13445            final ResolveInfo info = receivers.get(i);
13446            if (info.activityInfo == null) {
13447                continue;
13448            }
13449
13450            if (packageName.equals(info.activityInfo.packageName)) {
13451                targetReceiver = info.activityInfo;
13452                break;
13453            }
13454        }
13455
13456        if (targetReceiver == null) {
13457            return null;
13458        }
13459
13460        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13461    }
13462
13463    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13464            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13465        if (pkgInfo.verifiers.length == 0) {
13466            return null;
13467        }
13468
13469        final int N = pkgInfo.verifiers.length;
13470        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13471        for (int i = 0; i < N; i++) {
13472            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13473
13474            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13475                    receivers);
13476            if (comp == null) {
13477                continue;
13478            }
13479
13480            final int verifierUid = getUidForVerifier(verifierInfo);
13481            if (verifierUid == -1) {
13482                continue;
13483            }
13484
13485            if (DEBUG_VERIFY) {
13486                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13487                        + " with the correct signature");
13488            }
13489            sufficientVerifiers.add(comp);
13490            verificationState.addSufficientVerifier(verifierUid);
13491        }
13492
13493        return sufficientVerifiers;
13494    }
13495
13496    private int getUidForVerifier(VerifierInfo verifierInfo) {
13497        synchronized (mPackages) {
13498            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13499            if (pkg == null) {
13500                return -1;
13501            } else if (pkg.mSignatures.length != 1) {
13502                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13503                        + " has more than one signature; ignoring");
13504                return -1;
13505            }
13506
13507            /*
13508             * If the public key of the package's signature does not match
13509             * our expected public key, then this is a different package and
13510             * we should skip.
13511             */
13512
13513            final byte[] expectedPublicKey;
13514            try {
13515                final Signature verifierSig = pkg.mSignatures[0];
13516                final PublicKey publicKey = verifierSig.getPublicKey();
13517                expectedPublicKey = publicKey.getEncoded();
13518            } catch (CertificateException e) {
13519                return -1;
13520            }
13521
13522            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13523
13524            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13525                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13526                        + " does not have the expected public key; ignoring");
13527                return -1;
13528            }
13529
13530            return pkg.applicationInfo.uid;
13531        }
13532    }
13533
13534    @Override
13535    public void finishPackageInstall(int token, boolean didLaunch) {
13536        enforceSystemOrRoot("Only the system is allowed to finish installs");
13537
13538        if (DEBUG_INSTALL) {
13539            Slog.v(TAG, "BM finishing package install for " + token);
13540        }
13541        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13542
13543        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13544        mHandler.sendMessage(msg);
13545    }
13546
13547    /**
13548     * Get the verification agent timeout.
13549     *
13550     * @return verification timeout in milliseconds
13551     */
13552    private long getVerificationTimeout() {
13553        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13554                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13555                DEFAULT_VERIFICATION_TIMEOUT);
13556    }
13557
13558    /**
13559     * Get the default verification agent response code.
13560     *
13561     * @return default verification response code
13562     */
13563    private int getDefaultVerificationResponse() {
13564        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13565                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13566                DEFAULT_VERIFICATION_RESPONSE);
13567    }
13568
13569    /**
13570     * Check whether or not package verification has been enabled.
13571     *
13572     * @return true if verification should be performed
13573     */
13574    private boolean isVerificationEnabled(int userId, int installFlags) {
13575        if (!DEFAULT_VERIFY_ENABLE) {
13576            return false;
13577        }
13578        // Ephemeral apps don't get the full verification treatment
13579        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13580            if (DEBUG_EPHEMERAL) {
13581                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13582            }
13583            return false;
13584        }
13585
13586        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13587
13588        // Check if installing from ADB
13589        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13590            // Do not run verification in a test harness environment
13591            if (ActivityManager.isRunningInTestHarness()) {
13592                return false;
13593            }
13594            if (ensureVerifyAppsEnabled) {
13595                return true;
13596            }
13597            // Check if the developer does not want package verification for ADB installs
13598            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13599                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13600                return false;
13601            }
13602        }
13603
13604        if (ensureVerifyAppsEnabled) {
13605            return true;
13606        }
13607
13608        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13609                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13610    }
13611
13612    @Override
13613    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13614            throws RemoteException {
13615        mContext.enforceCallingOrSelfPermission(
13616                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13617                "Only intentfilter verification agents can verify applications");
13618
13619        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13620        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13621                Binder.getCallingUid(), verificationCode, failedDomains);
13622        msg.arg1 = id;
13623        msg.obj = response;
13624        mHandler.sendMessage(msg);
13625    }
13626
13627    @Override
13628    public int getIntentVerificationStatus(String packageName, int userId) {
13629        synchronized (mPackages) {
13630            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13631        }
13632    }
13633
13634    @Override
13635    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13636        mContext.enforceCallingOrSelfPermission(
13637                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13638
13639        boolean result = false;
13640        synchronized (mPackages) {
13641            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13642        }
13643        if (result) {
13644            scheduleWritePackageRestrictionsLocked(userId);
13645        }
13646        return result;
13647    }
13648
13649    @Override
13650    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13651            String packageName) {
13652        synchronized (mPackages) {
13653            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13654        }
13655    }
13656
13657    @Override
13658    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13659        if (TextUtils.isEmpty(packageName)) {
13660            return ParceledListSlice.emptyList();
13661        }
13662        synchronized (mPackages) {
13663            PackageParser.Package pkg = mPackages.get(packageName);
13664            if (pkg == null || pkg.activities == null) {
13665                return ParceledListSlice.emptyList();
13666            }
13667            final int count = pkg.activities.size();
13668            ArrayList<IntentFilter> result = new ArrayList<>();
13669            for (int n=0; n<count; n++) {
13670                PackageParser.Activity activity = pkg.activities.get(n);
13671                if (activity.intents != null && activity.intents.size() > 0) {
13672                    result.addAll(activity.intents);
13673                }
13674            }
13675            return new ParceledListSlice<>(result);
13676        }
13677    }
13678
13679    @Override
13680    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13681        mContext.enforceCallingOrSelfPermission(
13682                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13683
13684        synchronized (mPackages) {
13685            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13686            if (packageName != null) {
13687                result |= updateIntentVerificationStatus(packageName,
13688                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13689                        userId);
13690                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13691                        packageName, userId);
13692            }
13693            return result;
13694        }
13695    }
13696
13697    @Override
13698    public String getDefaultBrowserPackageName(int userId) {
13699        synchronized (mPackages) {
13700            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13701        }
13702    }
13703
13704    /**
13705     * Get the "allow unknown sources" setting.
13706     *
13707     * @return the current "allow unknown sources" setting
13708     */
13709    private int getUnknownSourcesSettings() {
13710        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13711                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13712                -1);
13713    }
13714
13715    @Override
13716    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13717        final int uid = Binder.getCallingUid();
13718        // writer
13719        synchronized (mPackages) {
13720            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13721            if (targetPackageSetting == null) {
13722                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13723            }
13724
13725            PackageSetting installerPackageSetting;
13726            if (installerPackageName != null) {
13727                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13728                if (installerPackageSetting == null) {
13729                    throw new IllegalArgumentException("Unknown installer package: "
13730                            + installerPackageName);
13731                }
13732            } else {
13733                installerPackageSetting = null;
13734            }
13735
13736            Signature[] callerSignature;
13737            Object obj = mSettings.getUserIdLPr(uid);
13738            if (obj != null) {
13739                if (obj instanceof SharedUserSetting) {
13740                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13741                } else if (obj instanceof PackageSetting) {
13742                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13743                } else {
13744                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13745                }
13746            } else {
13747                throw new SecurityException("Unknown calling UID: " + uid);
13748            }
13749
13750            // Verify: can't set installerPackageName to a package that is
13751            // not signed with the same cert as the caller.
13752            if (installerPackageSetting != null) {
13753                if (compareSignatures(callerSignature,
13754                        installerPackageSetting.signatures.mSignatures)
13755                        != PackageManager.SIGNATURE_MATCH) {
13756                    throw new SecurityException(
13757                            "Caller does not have same cert as new installer package "
13758                            + installerPackageName);
13759                }
13760            }
13761
13762            // Verify: if target already has an installer package, it must
13763            // be signed with the same cert as the caller.
13764            if (targetPackageSetting.installerPackageName != null) {
13765                PackageSetting setting = mSettings.mPackages.get(
13766                        targetPackageSetting.installerPackageName);
13767                // If the currently set package isn't valid, then it's always
13768                // okay to change it.
13769                if (setting != null) {
13770                    if (compareSignatures(callerSignature,
13771                            setting.signatures.mSignatures)
13772                            != PackageManager.SIGNATURE_MATCH) {
13773                        throw new SecurityException(
13774                                "Caller does not have same cert as old installer package "
13775                                + targetPackageSetting.installerPackageName);
13776                    }
13777                }
13778            }
13779
13780            // Okay!
13781            targetPackageSetting.installerPackageName = installerPackageName;
13782            if (installerPackageName != null) {
13783                mSettings.mInstallerPackages.add(installerPackageName);
13784            }
13785            scheduleWriteSettingsLocked();
13786        }
13787    }
13788
13789    @Override
13790    public void setApplicationCategoryHint(String packageName, int categoryHint,
13791            String callerPackageName) {
13792        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13793                callerPackageName);
13794        synchronized (mPackages) {
13795            PackageSetting ps = mSettings.mPackages.get(packageName);
13796            if (ps == null) {
13797                throw new IllegalArgumentException("Unknown target package " + packageName);
13798            }
13799
13800            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13801                throw new IllegalArgumentException("Calling package " + callerPackageName
13802                        + " is not installer for " + packageName);
13803            }
13804
13805            if (ps.categoryHint != categoryHint) {
13806                ps.categoryHint = categoryHint;
13807                scheduleWriteSettingsLocked();
13808            }
13809        }
13810    }
13811
13812    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13813        // Queue up an async operation since the package installation may take a little while.
13814        mHandler.post(new Runnable() {
13815            public void run() {
13816                mHandler.removeCallbacks(this);
13817                 // Result object to be returned
13818                PackageInstalledInfo res = new PackageInstalledInfo();
13819                res.setReturnCode(currentStatus);
13820                res.uid = -1;
13821                res.pkg = null;
13822                res.removedInfo = null;
13823                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13824                    args.doPreInstall(res.returnCode);
13825                    synchronized (mInstallLock) {
13826                        installPackageTracedLI(args, res);
13827                    }
13828                    args.doPostInstall(res.returnCode, res.uid);
13829                }
13830
13831                // A restore should be performed at this point if (a) the install
13832                // succeeded, (b) the operation is not an update, and (c) the new
13833                // package has not opted out of backup participation.
13834                final boolean update = res.removedInfo != null
13835                        && res.removedInfo.removedPackage != null;
13836                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13837                boolean doRestore = !update
13838                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13839
13840                // Set up the post-install work request bookkeeping.  This will be used
13841                // and cleaned up by the post-install event handling regardless of whether
13842                // there's a restore pass performed.  Token values are >= 1.
13843                int token;
13844                if (mNextInstallToken < 0) mNextInstallToken = 1;
13845                token = mNextInstallToken++;
13846
13847                PostInstallData data = new PostInstallData(args, res);
13848                mRunningInstalls.put(token, data);
13849                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13850
13851                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13852                    // Pass responsibility to the Backup Manager.  It will perform a
13853                    // restore if appropriate, then pass responsibility back to the
13854                    // Package Manager to run the post-install observer callbacks
13855                    // and broadcasts.
13856                    IBackupManager bm = IBackupManager.Stub.asInterface(
13857                            ServiceManager.getService(Context.BACKUP_SERVICE));
13858                    if (bm != null) {
13859                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13860                                + " to BM for possible restore");
13861                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13862                        try {
13863                            // TODO: http://b/22388012
13864                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13865                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13866                            } else {
13867                                doRestore = false;
13868                            }
13869                        } catch (RemoteException e) {
13870                            // can't happen; the backup manager is local
13871                        } catch (Exception e) {
13872                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13873                            doRestore = false;
13874                        }
13875                    } else {
13876                        Slog.e(TAG, "Backup Manager not found!");
13877                        doRestore = false;
13878                    }
13879                }
13880
13881                if (!doRestore) {
13882                    // No restore possible, or the Backup Manager was mysteriously not
13883                    // available -- just fire the post-install work request directly.
13884                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13885
13886                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13887
13888                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13889                    mHandler.sendMessage(msg);
13890                }
13891            }
13892        });
13893    }
13894
13895    /**
13896     * Callback from PackageSettings whenever an app is first transitioned out of the
13897     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13898     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13899     * here whether the app is the target of an ongoing install, and only send the
13900     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13901     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13902     * handling.
13903     */
13904    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13905        // Serialize this with the rest of the install-process message chain.  In the
13906        // restore-at-install case, this Runnable will necessarily run before the
13907        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13908        // are coherent.  In the non-restore case, the app has already completed install
13909        // and been launched through some other means, so it is not in a problematic
13910        // state for observers to see the FIRST_LAUNCH signal.
13911        mHandler.post(new Runnable() {
13912            @Override
13913            public void run() {
13914                for (int i = 0; i < mRunningInstalls.size(); i++) {
13915                    final PostInstallData data = mRunningInstalls.valueAt(i);
13916                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13917                        continue;
13918                    }
13919                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13920                        // right package; but is it for the right user?
13921                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13922                            if (userId == data.res.newUsers[uIndex]) {
13923                                if (DEBUG_BACKUP) {
13924                                    Slog.i(TAG, "Package " + pkgName
13925                                            + " being restored so deferring FIRST_LAUNCH");
13926                                }
13927                                return;
13928                            }
13929                        }
13930                    }
13931                }
13932                // didn't find it, so not being restored
13933                if (DEBUG_BACKUP) {
13934                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13935                }
13936                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13937            }
13938        });
13939    }
13940
13941    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13942        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13943                installerPkg, null, userIds);
13944    }
13945
13946    private abstract class HandlerParams {
13947        private static final int MAX_RETRIES = 4;
13948
13949        /**
13950         * Number of times startCopy() has been attempted and had a non-fatal
13951         * error.
13952         */
13953        private int mRetries = 0;
13954
13955        /** User handle for the user requesting the information or installation. */
13956        private final UserHandle mUser;
13957        String traceMethod;
13958        int traceCookie;
13959
13960        HandlerParams(UserHandle user) {
13961            mUser = user;
13962        }
13963
13964        UserHandle getUser() {
13965            return mUser;
13966        }
13967
13968        HandlerParams setTraceMethod(String traceMethod) {
13969            this.traceMethod = traceMethod;
13970            return this;
13971        }
13972
13973        HandlerParams setTraceCookie(int traceCookie) {
13974            this.traceCookie = traceCookie;
13975            return this;
13976        }
13977
13978        final boolean startCopy() {
13979            boolean res;
13980            try {
13981                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13982
13983                if (++mRetries > MAX_RETRIES) {
13984                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13985                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13986                    handleServiceError();
13987                    return false;
13988                } else {
13989                    handleStartCopy();
13990                    res = true;
13991                }
13992            } catch (RemoteException e) {
13993                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13994                mHandler.sendEmptyMessage(MCS_RECONNECT);
13995                res = false;
13996            }
13997            handleReturnCode();
13998            return res;
13999        }
14000
14001        final void serviceError() {
14002            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14003            handleServiceError();
14004            handleReturnCode();
14005        }
14006
14007        abstract void handleStartCopy() throws RemoteException;
14008        abstract void handleServiceError();
14009        abstract void handleReturnCode();
14010    }
14011
14012    class MeasureParams extends HandlerParams {
14013        private final PackageStats mStats;
14014        private boolean mSuccess;
14015
14016        private final IPackageStatsObserver mObserver;
14017
14018        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14019            super(new UserHandle(stats.userHandle));
14020            mObserver = observer;
14021            mStats = stats;
14022        }
14023
14024        @Override
14025        public String toString() {
14026            return "MeasureParams{"
14027                + Integer.toHexString(System.identityHashCode(this))
14028                + " " + mStats.packageName + "}";
14029        }
14030
14031        @Override
14032        void handleStartCopy() throws RemoteException {
14033            synchronized (mInstallLock) {
14034                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14035            }
14036
14037            if (mSuccess) {
14038                boolean mounted = false;
14039                try {
14040                    final String status = Environment.getExternalStorageState();
14041                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14042                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14043                } catch (Exception e) {
14044                }
14045
14046                if (mounted) {
14047                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14048
14049                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14050                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14051
14052                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14053                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14054
14055                    // Always subtract cache size, since it's a subdirectory
14056                    mStats.externalDataSize -= mStats.externalCacheSize;
14057
14058                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14059                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14060
14061                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14062                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14063                }
14064            }
14065        }
14066
14067        @Override
14068        void handleReturnCode() {
14069            if (mObserver != null) {
14070                try {
14071                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14072                } catch (RemoteException e) {
14073                    Slog.i(TAG, "Observer no longer exists.");
14074                }
14075            }
14076        }
14077
14078        @Override
14079        void handleServiceError() {
14080            Slog.e(TAG, "Could not measure application " + mStats.packageName
14081                            + " external storage");
14082        }
14083    }
14084
14085    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14086            throws RemoteException {
14087        long result = 0;
14088        for (File path : paths) {
14089            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14090        }
14091        return result;
14092    }
14093
14094    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14095        for (File path : paths) {
14096            try {
14097                mcs.clearDirectory(path.getAbsolutePath());
14098            } catch (RemoteException e) {
14099            }
14100        }
14101    }
14102
14103    static class OriginInfo {
14104        /**
14105         * Location where install is coming from, before it has been
14106         * copied/renamed into place. This could be a single monolithic APK
14107         * file, or a cluster directory. This location may be untrusted.
14108         */
14109        final File file;
14110        final String cid;
14111
14112        /**
14113         * Flag indicating that {@link #file} or {@link #cid} has already been
14114         * staged, meaning downstream users don't need to defensively copy the
14115         * contents.
14116         */
14117        final boolean staged;
14118
14119        /**
14120         * Flag indicating that {@link #file} or {@link #cid} is an already
14121         * installed app that is being moved.
14122         */
14123        final boolean existing;
14124
14125        final String resolvedPath;
14126        final File resolvedFile;
14127
14128        static OriginInfo fromNothing() {
14129            return new OriginInfo(null, null, false, false);
14130        }
14131
14132        static OriginInfo fromUntrustedFile(File file) {
14133            return new OriginInfo(file, null, false, false);
14134        }
14135
14136        static OriginInfo fromExistingFile(File file) {
14137            return new OriginInfo(file, null, false, true);
14138        }
14139
14140        static OriginInfo fromStagedFile(File file) {
14141            return new OriginInfo(file, null, true, false);
14142        }
14143
14144        static OriginInfo fromStagedContainer(String cid) {
14145            return new OriginInfo(null, cid, true, false);
14146        }
14147
14148        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14149            this.file = file;
14150            this.cid = cid;
14151            this.staged = staged;
14152            this.existing = existing;
14153
14154            if (cid != null) {
14155                resolvedPath = PackageHelper.getSdDir(cid);
14156                resolvedFile = new File(resolvedPath);
14157            } else if (file != null) {
14158                resolvedPath = file.getAbsolutePath();
14159                resolvedFile = file;
14160            } else {
14161                resolvedPath = null;
14162                resolvedFile = null;
14163            }
14164        }
14165    }
14166
14167    static class MoveInfo {
14168        final int moveId;
14169        final String fromUuid;
14170        final String toUuid;
14171        final String packageName;
14172        final String dataAppName;
14173        final int appId;
14174        final String seinfo;
14175        final int targetSdkVersion;
14176
14177        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14178                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14179            this.moveId = moveId;
14180            this.fromUuid = fromUuid;
14181            this.toUuid = toUuid;
14182            this.packageName = packageName;
14183            this.dataAppName = dataAppName;
14184            this.appId = appId;
14185            this.seinfo = seinfo;
14186            this.targetSdkVersion = targetSdkVersion;
14187        }
14188    }
14189
14190    static class VerificationInfo {
14191        /** A constant used to indicate that a uid value is not present. */
14192        public static final int NO_UID = -1;
14193
14194        /** URI referencing where the package was downloaded from. */
14195        final Uri originatingUri;
14196
14197        /** HTTP referrer URI associated with the originatingURI. */
14198        final Uri referrer;
14199
14200        /** UID of the application that the install request originated from. */
14201        final int originatingUid;
14202
14203        /** UID of application requesting the install */
14204        final int installerUid;
14205
14206        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14207            this.originatingUri = originatingUri;
14208            this.referrer = referrer;
14209            this.originatingUid = originatingUid;
14210            this.installerUid = installerUid;
14211        }
14212    }
14213
14214    class InstallParams extends HandlerParams {
14215        final OriginInfo origin;
14216        final MoveInfo move;
14217        final IPackageInstallObserver2 observer;
14218        int installFlags;
14219        final String installerPackageName;
14220        final String volumeUuid;
14221        private InstallArgs mArgs;
14222        private int mRet;
14223        final String packageAbiOverride;
14224        final String[] grantedRuntimePermissions;
14225        final VerificationInfo verificationInfo;
14226        final Certificate[][] certificates;
14227        final int installReason;
14228
14229        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14230                int installFlags, String installerPackageName, String volumeUuid,
14231                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14232                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14233            super(user);
14234            this.origin = origin;
14235            this.move = move;
14236            this.observer = observer;
14237            this.installFlags = installFlags;
14238            this.installerPackageName = installerPackageName;
14239            this.volumeUuid = volumeUuid;
14240            this.verificationInfo = verificationInfo;
14241            this.packageAbiOverride = packageAbiOverride;
14242            this.grantedRuntimePermissions = grantedPermissions;
14243            this.certificates = certificates;
14244            this.installReason = installReason;
14245        }
14246
14247        @Override
14248        public String toString() {
14249            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14250                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14251        }
14252
14253        private int installLocationPolicy(PackageInfoLite pkgLite) {
14254            String packageName = pkgLite.packageName;
14255            int installLocation = pkgLite.installLocation;
14256            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14257            // reader
14258            synchronized (mPackages) {
14259                // Currently installed package which the new package is attempting to replace or
14260                // null if no such package is installed.
14261                PackageParser.Package installedPkg = mPackages.get(packageName);
14262                // Package which currently owns the data which the new package will own if installed.
14263                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14264                // will be null whereas dataOwnerPkg will contain information about the package
14265                // which was uninstalled while keeping its data.
14266                PackageParser.Package dataOwnerPkg = installedPkg;
14267                if (dataOwnerPkg  == null) {
14268                    PackageSetting ps = mSettings.mPackages.get(packageName);
14269                    if (ps != null) {
14270                        dataOwnerPkg = ps.pkg;
14271                    }
14272                }
14273
14274                if (dataOwnerPkg != null) {
14275                    // If installed, the package will get access to data left on the device by its
14276                    // predecessor. As a security measure, this is permited only if this is not a
14277                    // version downgrade or if the predecessor package is marked as debuggable and
14278                    // a downgrade is explicitly requested.
14279                    //
14280                    // On debuggable platform builds, downgrades are permitted even for
14281                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14282                    // not offer security guarantees and thus it's OK to disable some security
14283                    // mechanisms to make debugging/testing easier on those builds. However, even on
14284                    // debuggable builds downgrades of packages are permitted only if requested via
14285                    // installFlags. This is because we aim to keep the behavior of debuggable
14286                    // platform builds as close as possible to the behavior of non-debuggable
14287                    // platform builds.
14288                    final boolean downgradeRequested =
14289                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14290                    final boolean packageDebuggable =
14291                                (dataOwnerPkg.applicationInfo.flags
14292                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14293                    final boolean downgradePermitted =
14294                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14295                    if (!downgradePermitted) {
14296                        try {
14297                            checkDowngrade(dataOwnerPkg, pkgLite);
14298                        } catch (PackageManagerException e) {
14299                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14300                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14301                        }
14302                    }
14303                }
14304
14305                if (installedPkg != null) {
14306                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14307                        // Check for updated system application.
14308                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14309                            if (onSd) {
14310                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14311                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14312                            }
14313                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14314                        } else {
14315                            if (onSd) {
14316                                // Install flag overrides everything.
14317                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14318                            }
14319                            // If current upgrade specifies particular preference
14320                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14321                                // Application explicitly specified internal.
14322                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14323                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14324                                // App explictly prefers external. Let policy decide
14325                            } else {
14326                                // Prefer previous location
14327                                if (isExternal(installedPkg)) {
14328                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14329                                }
14330                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14331                            }
14332                        }
14333                    } else {
14334                        // Invalid install. Return error code
14335                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14336                    }
14337                }
14338            }
14339            // All the special cases have been taken care of.
14340            // Return result based on recommended install location.
14341            if (onSd) {
14342                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14343            }
14344            return pkgLite.recommendedInstallLocation;
14345        }
14346
14347        /*
14348         * Invoke remote method to get package information and install
14349         * location values. Override install location based on default
14350         * policy if needed and then create install arguments based
14351         * on the install location.
14352         */
14353        public void handleStartCopy() throws RemoteException {
14354            int ret = PackageManager.INSTALL_SUCCEEDED;
14355
14356            // If we're already staged, we've firmly committed to an install location
14357            if (origin.staged) {
14358                if (origin.file != null) {
14359                    installFlags |= PackageManager.INSTALL_INTERNAL;
14360                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14361                } else if (origin.cid != null) {
14362                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14363                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14364                } else {
14365                    throw new IllegalStateException("Invalid stage location");
14366                }
14367            }
14368
14369            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14370            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14371            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14372            PackageInfoLite pkgLite = null;
14373
14374            if (onInt && onSd) {
14375                // Check if both bits are set.
14376                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14377                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14378            } else if (onSd && ephemeral) {
14379                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14380                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14381            } else {
14382                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14383                        packageAbiOverride);
14384
14385                if (DEBUG_EPHEMERAL && ephemeral) {
14386                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14387                }
14388
14389                /*
14390                 * If we have too little free space, try to free cache
14391                 * before giving up.
14392                 */
14393                if (!origin.staged && pkgLite.recommendedInstallLocation
14394                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14395                    // TODO: focus freeing disk space on the target device
14396                    final StorageManager storage = StorageManager.from(mContext);
14397                    final long lowThreshold = storage.getStorageLowBytes(
14398                            Environment.getDataDirectory());
14399
14400                    final long sizeBytes = mContainerService.calculateInstalledSize(
14401                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14402
14403                    try {
14404                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14405                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14406                                installFlags, packageAbiOverride);
14407                    } catch (InstallerException e) {
14408                        Slog.w(TAG, "Failed to free cache", e);
14409                    }
14410
14411                    /*
14412                     * The cache free must have deleted the file we
14413                     * downloaded to install.
14414                     *
14415                     * TODO: fix the "freeCache" call to not delete
14416                     *       the file we care about.
14417                     */
14418                    if (pkgLite.recommendedInstallLocation
14419                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14420                        pkgLite.recommendedInstallLocation
14421                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14422                    }
14423                }
14424            }
14425
14426            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14427                int loc = pkgLite.recommendedInstallLocation;
14428                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14429                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14430                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14431                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14432                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14433                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14434                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14435                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14436                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14437                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14438                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14439                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14440                } else {
14441                    // Override with defaults if needed.
14442                    loc = installLocationPolicy(pkgLite);
14443                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14444                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14445                    } else if (!onSd && !onInt) {
14446                        // Override install location with flags
14447                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14448                            // Set the flag to install on external media.
14449                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14450                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14451                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14452                            if (DEBUG_EPHEMERAL) {
14453                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14454                            }
14455                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14456                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14457                                    |PackageManager.INSTALL_INTERNAL);
14458                        } else {
14459                            // Make sure the flag for installing on external
14460                            // media is unset
14461                            installFlags |= PackageManager.INSTALL_INTERNAL;
14462                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14463                        }
14464                    }
14465                }
14466            }
14467
14468            final InstallArgs args = createInstallArgs(this);
14469            mArgs = args;
14470
14471            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14472                // TODO: http://b/22976637
14473                // Apps installed for "all" users use the device owner to verify the app
14474                UserHandle verifierUser = getUser();
14475                if (verifierUser == UserHandle.ALL) {
14476                    verifierUser = UserHandle.SYSTEM;
14477                }
14478
14479                /*
14480                 * Determine if we have any installed package verifiers. If we
14481                 * do, then we'll defer to them to verify the packages.
14482                 */
14483                final int requiredUid = mRequiredVerifierPackage == null ? -1
14484                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14485                                verifierUser.getIdentifier());
14486                if (!origin.existing && requiredUid != -1
14487                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14488                    final Intent verification = new Intent(
14489                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14490                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14491                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14492                            PACKAGE_MIME_TYPE);
14493                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14494
14495                    // Query all live verifiers based on current user state
14496                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14497                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14498
14499                    if (DEBUG_VERIFY) {
14500                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14501                                + verification.toString() + " with " + pkgLite.verifiers.length
14502                                + " optional verifiers");
14503                    }
14504
14505                    final int verificationId = mPendingVerificationToken++;
14506
14507                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14508
14509                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14510                            installerPackageName);
14511
14512                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14513                            installFlags);
14514
14515                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14516                            pkgLite.packageName);
14517
14518                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14519                            pkgLite.versionCode);
14520
14521                    if (verificationInfo != null) {
14522                        if (verificationInfo.originatingUri != null) {
14523                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14524                                    verificationInfo.originatingUri);
14525                        }
14526                        if (verificationInfo.referrer != null) {
14527                            verification.putExtra(Intent.EXTRA_REFERRER,
14528                                    verificationInfo.referrer);
14529                        }
14530                        if (verificationInfo.originatingUid >= 0) {
14531                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14532                                    verificationInfo.originatingUid);
14533                        }
14534                        if (verificationInfo.installerUid >= 0) {
14535                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14536                                    verificationInfo.installerUid);
14537                        }
14538                    }
14539
14540                    final PackageVerificationState verificationState = new PackageVerificationState(
14541                            requiredUid, args);
14542
14543                    mPendingVerification.append(verificationId, verificationState);
14544
14545                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14546                            receivers, verificationState);
14547
14548                    /*
14549                     * If any sufficient verifiers were listed in the package
14550                     * manifest, attempt to ask them.
14551                     */
14552                    if (sufficientVerifiers != null) {
14553                        final int N = sufficientVerifiers.size();
14554                        if (N == 0) {
14555                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14556                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14557                        } else {
14558                            for (int i = 0; i < N; i++) {
14559                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14560
14561                                final Intent sufficientIntent = new Intent(verification);
14562                                sufficientIntent.setComponent(verifierComponent);
14563                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14564                            }
14565                        }
14566                    }
14567
14568                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14569                            mRequiredVerifierPackage, receivers);
14570                    if (ret == PackageManager.INSTALL_SUCCEEDED
14571                            && mRequiredVerifierPackage != null) {
14572                        Trace.asyncTraceBegin(
14573                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14574                        /*
14575                         * Send the intent to the required verification agent,
14576                         * but only start the verification timeout after the
14577                         * target BroadcastReceivers have run.
14578                         */
14579                        verification.setComponent(requiredVerifierComponent);
14580                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14581                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14582                                new BroadcastReceiver() {
14583                                    @Override
14584                                    public void onReceive(Context context, Intent intent) {
14585                                        final Message msg = mHandler
14586                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14587                                        msg.arg1 = verificationId;
14588                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14589                                    }
14590                                }, null, 0, null, null);
14591
14592                        /*
14593                         * We don't want the copy to proceed until verification
14594                         * succeeds, so null out this field.
14595                         */
14596                        mArgs = null;
14597                    }
14598                } else {
14599                    /*
14600                     * No package verification is enabled, so immediately start
14601                     * the remote call to initiate copy using temporary file.
14602                     */
14603                    ret = args.copyApk(mContainerService, true);
14604                }
14605            }
14606
14607            mRet = ret;
14608        }
14609
14610        @Override
14611        void handleReturnCode() {
14612            // If mArgs is null, then MCS couldn't be reached. When it
14613            // reconnects, it will try again to install. At that point, this
14614            // will succeed.
14615            if (mArgs != null) {
14616                processPendingInstall(mArgs, mRet);
14617            }
14618        }
14619
14620        @Override
14621        void handleServiceError() {
14622            mArgs = createInstallArgs(this);
14623            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14624        }
14625
14626        public boolean isForwardLocked() {
14627            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14628        }
14629    }
14630
14631    /**
14632     * Used during creation of InstallArgs
14633     *
14634     * @param installFlags package installation flags
14635     * @return true if should be installed on external storage
14636     */
14637    private static boolean installOnExternalAsec(int installFlags) {
14638        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14639            return false;
14640        }
14641        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14642            return true;
14643        }
14644        return false;
14645    }
14646
14647    /**
14648     * Used during creation of InstallArgs
14649     *
14650     * @param installFlags package installation flags
14651     * @return true if should be installed as forward locked
14652     */
14653    private static boolean installForwardLocked(int installFlags) {
14654        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14655    }
14656
14657    private InstallArgs createInstallArgs(InstallParams params) {
14658        if (params.move != null) {
14659            return new MoveInstallArgs(params);
14660        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14661            return new AsecInstallArgs(params);
14662        } else {
14663            return new FileInstallArgs(params);
14664        }
14665    }
14666
14667    /**
14668     * Create args that describe an existing installed package. Typically used
14669     * when cleaning up old installs, or used as a move source.
14670     */
14671    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14672            String resourcePath, String[] instructionSets) {
14673        final boolean isInAsec;
14674        if (installOnExternalAsec(installFlags)) {
14675            /* Apps on SD card are always in ASEC containers. */
14676            isInAsec = true;
14677        } else if (installForwardLocked(installFlags)
14678                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14679            /*
14680             * Forward-locked apps are only in ASEC containers if they're the
14681             * new style
14682             */
14683            isInAsec = true;
14684        } else {
14685            isInAsec = false;
14686        }
14687
14688        if (isInAsec) {
14689            return new AsecInstallArgs(codePath, instructionSets,
14690                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14691        } else {
14692            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14693        }
14694    }
14695
14696    static abstract class InstallArgs {
14697        /** @see InstallParams#origin */
14698        final OriginInfo origin;
14699        /** @see InstallParams#move */
14700        final MoveInfo move;
14701
14702        final IPackageInstallObserver2 observer;
14703        // Always refers to PackageManager flags only
14704        final int installFlags;
14705        final String installerPackageName;
14706        final String volumeUuid;
14707        final UserHandle user;
14708        final String abiOverride;
14709        final String[] installGrantPermissions;
14710        /** If non-null, drop an async trace when the install completes */
14711        final String traceMethod;
14712        final int traceCookie;
14713        final Certificate[][] certificates;
14714        final int installReason;
14715
14716        // The list of instruction sets supported by this app. This is currently
14717        // only used during the rmdex() phase to clean up resources. We can get rid of this
14718        // if we move dex files under the common app path.
14719        /* nullable */ String[] instructionSets;
14720
14721        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14722                int installFlags, String installerPackageName, String volumeUuid,
14723                UserHandle user, String[] instructionSets,
14724                String abiOverride, String[] installGrantPermissions,
14725                String traceMethod, int traceCookie, Certificate[][] certificates,
14726                int installReason) {
14727            this.origin = origin;
14728            this.move = move;
14729            this.installFlags = installFlags;
14730            this.observer = observer;
14731            this.installerPackageName = installerPackageName;
14732            this.volumeUuid = volumeUuid;
14733            this.user = user;
14734            this.instructionSets = instructionSets;
14735            this.abiOverride = abiOverride;
14736            this.installGrantPermissions = installGrantPermissions;
14737            this.traceMethod = traceMethod;
14738            this.traceCookie = traceCookie;
14739            this.certificates = certificates;
14740            this.installReason = installReason;
14741        }
14742
14743        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14744        abstract int doPreInstall(int status);
14745
14746        /**
14747         * Rename package into final resting place. All paths on the given
14748         * scanned package should be updated to reflect the rename.
14749         */
14750        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14751        abstract int doPostInstall(int status, int uid);
14752
14753        /** @see PackageSettingBase#codePathString */
14754        abstract String getCodePath();
14755        /** @see PackageSettingBase#resourcePathString */
14756        abstract String getResourcePath();
14757
14758        // Need installer lock especially for dex file removal.
14759        abstract void cleanUpResourcesLI();
14760        abstract boolean doPostDeleteLI(boolean delete);
14761
14762        /**
14763         * Called before the source arguments are copied. This is used mostly
14764         * for MoveParams when it needs to read the source file to put it in the
14765         * destination.
14766         */
14767        int doPreCopy() {
14768            return PackageManager.INSTALL_SUCCEEDED;
14769        }
14770
14771        /**
14772         * Called after the source arguments are copied. This is used mostly for
14773         * MoveParams when it needs to read the source file to put it in the
14774         * destination.
14775         */
14776        int doPostCopy(int uid) {
14777            return PackageManager.INSTALL_SUCCEEDED;
14778        }
14779
14780        protected boolean isFwdLocked() {
14781            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14782        }
14783
14784        protected boolean isExternalAsec() {
14785            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14786        }
14787
14788        protected boolean isEphemeral() {
14789            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14790        }
14791
14792        UserHandle getUser() {
14793            return user;
14794        }
14795    }
14796
14797    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14798        if (!allCodePaths.isEmpty()) {
14799            if (instructionSets == null) {
14800                throw new IllegalStateException("instructionSet == null");
14801            }
14802            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14803            for (String codePath : allCodePaths) {
14804                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14805                    try {
14806                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14807                    } catch (InstallerException ignored) {
14808                    }
14809                }
14810            }
14811        }
14812    }
14813
14814    /**
14815     * Logic to handle installation of non-ASEC applications, including copying
14816     * and renaming logic.
14817     */
14818    class FileInstallArgs extends InstallArgs {
14819        private File codeFile;
14820        private File resourceFile;
14821
14822        // Example topology:
14823        // /data/app/com.example/base.apk
14824        // /data/app/com.example/split_foo.apk
14825        // /data/app/com.example/lib/arm/libfoo.so
14826        // /data/app/com.example/lib/arm64/libfoo.so
14827        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14828
14829        /** New install */
14830        FileInstallArgs(InstallParams params) {
14831            super(params.origin, params.move, params.observer, params.installFlags,
14832                    params.installerPackageName, params.volumeUuid,
14833                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14834                    params.grantedRuntimePermissions,
14835                    params.traceMethod, params.traceCookie, params.certificates,
14836                    params.installReason);
14837            if (isFwdLocked()) {
14838                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14839            }
14840        }
14841
14842        /** Existing install */
14843        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14844            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14845                    null, null, null, 0, null /*certificates*/,
14846                    PackageManager.INSTALL_REASON_UNKNOWN);
14847            this.codeFile = (codePath != null) ? new File(codePath) : null;
14848            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14849        }
14850
14851        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14853            try {
14854                return doCopyApk(imcs, temp);
14855            } finally {
14856                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14857            }
14858        }
14859
14860        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14861            if (origin.staged) {
14862                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14863                codeFile = origin.file;
14864                resourceFile = origin.file;
14865                return PackageManager.INSTALL_SUCCEEDED;
14866            }
14867
14868            try {
14869                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14870                final File tempDir =
14871                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14872                codeFile = tempDir;
14873                resourceFile = tempDir;
14874            } catch (IOException e) {
14875                Slog.w(TAG, "Failed to create copy file: " + e);
14876                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14877            }
14878
14879            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14880                @Override
14881                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14882                    if (!FileUtils.isValidExtFilename(name)) {
14883                        throw new IllegalArgumentException("Invalid filename: " + name);
14884                    }
14885                    try {
14886                        final File file = new File(codeFile, name);
14887                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14888                                O_RDWR | O_CREAT, 0644);
14889                        Os.chmod(file.getAbsolutePath(), 0644);
14890                        return new ParcelFileDescriptor(fd);
14891                    } catch (ErrnoException e) {
14892                        throw new RemoteException("Failed to open: " + e.getMessage());
14893                    }
14894                }
14895            };
14896
14897            int ret = PackageManager.INSTALL_SUCCEEDED;
14898            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14899            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14900                Slog.e(TAG, "Failed to copy package");
14901                return ret;
14902            }
14903
14904            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14905            NativeLibraryHelper.Handle handle = null;
14906            try {
14907                handle = NativeLibraryHelper.Handle.create(codeFile);
14908                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14909                        abiOverride);
14910            } catch (IOException e) {
14911                Slog.e(TAG, "Copying native libraries failed", e);
14912                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14913            } finally {
14914                IoUtils.closeQuietly(handle);
14915            }
14916
14917            return ret;
14918        }
14919
14920        int doPreInstall(int status) {
14921            if (status != PackageManager.INSTALL_SUCCEEDED) {
14922                cleanUp();
14923            }
14924            return status;
14925        }
14926
14927        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14928            if (status != PackageManager.INSTALL_SUCCEEDED) {
14929                cleanUp();
14930                return false;
14931            }
14932
14933            final File targetDir = codeFile.getParentFile();
14934            final File beforeCodeFile = codeFile;
14935            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14936
14937            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14938            try {
14939                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14940            } catch (ErrnoException e) {
14941                Slog.w(TAG, "Failed to rename", e);
14942                return false;
14943            }
14944
14945            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14946                Slog.w(TAG, "Failed to restorecon");
14947                return false;
14948            }
14949
14950            // Reflect the rename internally
14951            codeFile = afterCodeFile;
14952            resourceFile = afterCodeFile;
14953
14954            // Reflect the rename in scanned details
14955            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14956            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14957                    afterCodeFile, pkg.baseCodePath));
14958            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14959                    afterCodeFile, pkg.splitCodePaths));
14960
14961            // Reflect the rename in app info
14962            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14963            pkg.setApplicationInfoCodePath(pkg.codePath);
14964            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14965            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14966            pkg.setApplicationInfoResourcePath(pkg.codePath);
14967            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14968            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14969
14970            return true;
14971        }
14972
14973        int doPostInstall(int status, int uid) {
14974            if (status != PackageManager.INSTALL_SUCCEEDED) {
14975                cleanUp();
14976            }
14977            return status;
14978        }
14979
14980        @Override
14981        String getCodePath() {
14982            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14983        }
14984
14985        @Override
14986        String getResourcePath() {
14987            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14988        }
14989
14990        private boolean cleanUp() {
14991            if (codeFile == null || !codeFile.exists()) {
14992                return false;
14993            }
14994
14995            removeCodePathLI(codeFile);
14996
14997            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14998                resourceFile.delete();
14999            }
15000
15001            return true;
15002        }
15003
15004        void cleanUpResourcesLI() {
15005            // Try enumerating all code paths before deleting
15006            List<String> allCodePaths = Collections.EMPTY_LIST;
15007            if (codeFile != null && codeFile.exists()) {
15008                try {
15009                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15010                    allCodePaths = pkg.getAllCodePaths();
15011                } catch (PackageParserException e) {
15012                    // Ignored; we tried our best
15013                }
15014            }
15015
15016            cleanUp();
15017            removeDexFiles(allCodePaths, instructionSets);
15018        }
15019
15020        boolean doPostDeleteLI(boolean delete) {
15021            // XXX err, shouldn't we respect the delete flag?
15022            cleanUpResourcesLI();
15023            return true;
15024        }
15025    }
15026
15027    private boolean isAsecExternal(String cid) {
15028        final String asecPath = PackageHelper.getSdFilesystem(cid);
15029        return !asecPath.startsWith(mAsecInternalPath);
15030    }
15031
15032    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15033            PackageManagerException {
15034        if (copyRet < 0) {
15035            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15036                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15037                throw new PackageManagerException(copyRet, message);
15038            }
15039        }
15040    }
15041
15042    /**
15043     * Extract the StorageManagerService "container ID" from the full code path of an
15044     * .apk.
15045     */
15046    static String cidFromCodePath(String fullCodePath) {
15047        int eidx = fullCodePath.lastIndexOf("/");
15048        String subStr1 = fullCodePath.substring(0, eidx);
15049        int sidx = subStr1.lastIndexOf("/");
15050        return subStr1.substring(sidx+1, eidx);
15051    }
15052
15053    /**
15054     * Logic to handle installation of ASEC applications, including copying and
15055     * renaming logic.
15056     */
15057    class AsecInstallArgs extends InstallArgs {
15058        static final String RES_FILE_NAME = "pkg.apk";
15059        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15060
15061        String cid;
15062        String packagePath;
15063        String resourcePath;
15064
15065        /** New install */
15066        AsecInstallArgs(InstallParams params) {
15067            super(params.origin, params.move, params.observer, params.installFlags,
15068                    params.installerPackageName, params.volumeUuid,
15069                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15070                    params.grantedRuntimePermissions,
15071                    params.traceMethod, params.traceCookie, params.certificates,
15072                    params.installReason);
15073        }
15074
15075        /** Existing install */
15076        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15077                        boolean isExternal, boolean isForwardLocked) {
15078            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15079                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15080                    instructionSets, null, null, null, 0, null /*certificates*/,
15081                    PackageManager.INSTALL_REASON_UNKNOWN);
15082            // Hackily pretend we're still looking at a full code path
15083            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15084                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15085            }
15086
15087            // Extract cid from fullCodePath
15088            int eidx = fullCodePath.lastIndexOf("/");
15089            String subStr1 = fullCodePath.substring(0, eidx);
15090            int sidx = subStr1.lastIndexOf("/");
15091            cid = subStr1.substring(sidx+1, eidx);
15092            setMountPath(subStr1);
15093        }
15094
15095        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15096            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15097                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15098                    instructionSets, null, null, null, 0, null /*certificates*/,
15099                    PackageManager.INSTALL_REASON_UNKNOWN);
15100            this.cid = cid;
15101            setMountPath(PackageHelper.getSdDir(cid));
15102        }
15103
15104        void createCopyFile() {
15105            cid = mInstallerService.allocateExternalStageCidLegacy();
15106        }
15107
15108        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15109            if (origin.staged && origin.cid != null) {
15110                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15111                cid = origin.cid;
15112                setMountPath(PackageHelper.getSdDir(cid));
15113                return PackageManager.INSTALL_SUCCEEDED;
15114            }
15115
15116            if (temp) {
15117                createCopyFile();
15118            } else {
15119                /*
15120                 * Pre-emptively destroy the container since it's destroyed if
15121                 * copying fails due to it existing anyway.
15122                 */
15123                PackageHelper.destroySdDir(cid);
15124            }
15125
15126            final String newMountPath = imcs.copyPackageToContainer(
15127                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15128                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15129
15130            if (newMountPath != null) {
15131                setMountPath(newMountPath);
15132                return PackageManager.INSTALL_SUCCEEDED;
15133            } else {
15134                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15135            }
15136        }
15137
15138        @Override
15139        String getCodePath() {
15140            return packagePath;
15141        }
15142
15143        @Override
15144        String getResourcePath() {
15145            return resourcePath;
15146        }
15147
15148        int doPreInstall(int status) {
15149            if (status != PackageManager.INSTALL_SUCCEEDED) {
15150                // Destroy container
15151                PackageHelper.destroySdDir(cid);
15152            } else {
15153                boolean mounted = PackageHelper.isContainerMounted(cid);
15154                if (!mounted) {
15155                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15156                            Process.SYSTEM_UID);
15157                    if (newMountPath != null) {
15158                        setMountPath(newMountPath);
15159                    } else {
15160                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15161                    }
15162                }
15163            }
15164            return status;
15165        }
15166
15167        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15168            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15169            String newMountPath = null;
15170            if (PackageHelper.isContainerMounted(cid)) {
15171                // Unmount the container
15172                if (!PackageHelper.unMountSdDir(cid)) {
15173                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15174                    return false;
15175                }
15176            }
15177            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15178                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15179                        " which might be stale. Will try to clean up.");
15180                // Clean up the stale container and proceed to recreate.
15181                if (!PackageHelper.destroySdDir(newCacheId)) {
15182                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15183                    return false;
15184                }
15185                // Successfully cleaned up stale container. Try to rename again.
15186                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15187                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15188                            + " inspite of cleaning it up.");
15189                    return false;
15190                }
15191            }
15192            if (!PackageHelper.isContainerMounted(newCacheId)) {
15193                Slog.w(TAG, "Mounting container " + newCacheId);
15194                newMountPath = PackageHelper.mountSdDir(newCacheId,
15195                        getEncryptKey(), Process.SYSTEM_UID);
15196            } else {
15197                newMountPath = PackageHelper.getSdDir(newCacheId);
15198            }
15199            if (newMountPath == null) {
15200                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15201                return false;
15202            }
15203            Log.i(TAG, "Succesfully renamed " + cid +
15204                    " to " + newCacheId +
15205                    " at new path: " + newMountPath);
15206            cid = newCacheId;
15207
15208            final File beforeCodeFile = new File(packagePath);
15209            setMountPath(newMountPath);
15210            final File afterCodeFile = new File(packagePath);
15211
15212            // Reflect the rename in scanned details
15213            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15214            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15215                    afterCodeFile, pkg.baseCodePath));
15216            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15217                    afterCodeFile, pkg.splitCodePaths));
15218
15219            // Reflect the rename in app info
15220            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15221            pkg.setApplicationInfoCodePath(pkg.codePath);
15222            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15223            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15224            pkg.setApplicationInfoResourcePath(pkg.codePath);
15225            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15226            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15227
15228            return true;
15229        }
15230
15231        private void setMountPath(String mountPath) {
15232            final File mountFile = new File(mountPath);
15233
15234            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15235            if (monolithicFile.exists()) {
15236                packagePath = monolithicFile.getAbsolutePath();
15237                if (isFwdLocked()) {
15238                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15239                } else {
15240                    resourcePath = packagePath;
15241                }
15242            } else {
15243                packagePath = mountFile.getAbsolutePath();
15244                resourcePath = packagePath;
15245            }
15246        }
15247
15248        int doPostInstall(int status, int uid) {
15249            if (status != PackageManager.INSTALL_SUCCEEDED) {
15250                cleanUp();
15251            } else {
15252                final int groupOwner;
15253                final String protectedFile;
15254                if (isFwdLocked()) {
15255                    groupOwner = UserHandle.getSharedAppGid(uid);
15256                    protectedFile = RES_FILE_NAME;
15257                } else {
15258                    groupOwner = -1;
15259                    protectedFile = null;
15260                }
15261
15262                if (uid < Process.FIRST_APPLICATION_UID
15263                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15264                    Slog.e(TAG, "Failed to finalize " + cid);
15265                    PackageHelper.destroySdDir(cid);
15266                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15267                }
15268
15269                boolean mounted = PackageHelper.isContainerMounted(cid);
15270                if (!mounted) {
15271                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15272                }
15273            }
15274            return status;
15275        }
15276
15277        private void cleanUp() {
15278            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15279
15280            // Destroy secure container
15281            PackageHelper.destroySdDir(cid);
15282        }
15283
15284        private List<String> getAllCodePaths() {
15285            final File codeFile = new File(getCodePath());
15286            if (codeFile != null && codeFile.exists()) {
15287                try {
15288                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15289                    return pkg.getAllCodePaths();
15290                } catch (PackageParserException e) {
15291                    // Ignored; we tried our best
15292                }
15293            }
15294            return Collections.EMPTY_LIST;
15295        }
15296
15297        void cleanUpResourcesLI() {
15298            // Enumerate all code paths before deleting
15299            cleanUpResourcesLI(getAllCodePaths());
15300        }
15301
15302        private void cleanUpResourcesLI(List<String> allCodePaths) {
15303            cleanUp();
15304            removeDexFiles(allCodePaths, instructionSets);
15305        }
15306
15307        String getPackageName() {
15308            return getAsecPackageName(cid);
15309        }
15310
15311        boolean doPostDeleteLI(boolean delete) {
15312            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15313            final List<String> allCodePaths = getAllCodePaths();
15314            boolean mounted = PackageHelper.isContainerMounted(cid);
15315            if (mounted) {
15316                // Unmount first
15317                if (PackageHelper.unMountSdDir(cid)) {
15318                    mounted = false;
15319                }
15320            }
15321            if (!mounted && delete) {
15322                cleanUpResourcesLI(allCodePaths);
15323            }
15324            return !mounted;
15325        }
15326
15327        @Override
15328        int doPreCopy() {
15329            if (isFwdLocked()) {
15330                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15331                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15332                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15333                }
15334            }
15335
15336            return PackageManager.INSTALL_SUCCEEDED;
15337        }
15338
15339        @Override
15340        int doPostCopy(int uid) {
15341            if (isFwdLocked()) {
15342                if (uid < Process.FIRST_APPLICATION_UID
15343                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15344                                RES_FILE_NAME)) {
15345                    Slog.e(TAG, "Failed to finalize " + cid);
15346                    PackageHelper.destroySdDir(cid);
15347                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15348                }
15349            }
15350
15351            return PackageManager.INSTALL_SUCCEEDED;
15352        }
15353    }
15354
15355    /**
15356     * Logic to handle movement of existing installed applications.
15357     */
15358    class MoveInstallArgs extends InstallArgs {
15359        private File codeFile;
15360        private File resourceFile;
15361
15362        /** New install */
15363        MoveInstallArgs(InstallParams params) {
15364            super(params.origin, params.move, params.observer, params.installFlags,
15365                    params.installerPackageName, params.volumeUuid,
15366                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15367                    params.grantedRuntimePermissions,
15368                    params.traceMethod, params.traceCookie, params.certificates,
15369                    params.installReason);
15370        }
15371
15372        int copyApk(IMediaContainerService imcs, boolean temp) {
15373            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15374                    + move.fromUuid + " to " + move.toUuid);
15375            synchronized (mInstaller) {
15376                try {
15377                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15378                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15379                } catch (InstallerException e) {
15380                    Slog.w(TAG, "Failed to move app", e);
15381                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15382                }
15383            }
15384
15385            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15386            resourceFile = codeFile;
15387            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15388
15389            return PackageManager.INSTALL_SUCCEEDED;
15390        }
15391
15392        int doPreInstall(int status) {
15393            if (status != PackageManager.INSTALL_SUCCEEDED) {
15394                cleanUp(move.toUuid);
15395            }
15396            return status;
15397        }
15398
15399        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15400            if (status != PackageManager.INSTALL_SUCCEEDED) {
15401                cleanUp(move.toUuid);
15402                return false;
15403            }
15404
15405            // Reflect the move in app info
15406            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15407            pkg.setApplicationInfoCodePath(pkg.codePath);
15408            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15409            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15410            pkg.setApplicationInfoResourcePath(pkg.codePath);
15411            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15412            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15413
15414            return true;
15415        }
15416
15417        int doPostInstall(int status, int uid) {
15418            if (status == PackageManager.INSTALL_SUCCEEDED) {
15419                cleanUp(move.fromUuid);
15420            } else {
15421                cleanUp(move.toUuid);
15422            }
15423            return status;
15424        }
15425
15426        @Override
15427        String getCodePath() {
15428            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15429        }
15430
15431        @Override
15432        String getResourcePath() {
15433            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15434        }
15435
15436        private boolean cleanUp(String volumeUuid) {
15437            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15438                    move.dataAppName);
15439            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15440            final int[] userIds = sUserManager.getUserIds();
15441            synchronized (mInstallLock) {
15442                // Clean up both app data and code
15443                // All package moves are frozen until finished
15444                for (int userId : userIds) {
15445                    try {
15446                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15447                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15448                    } catch (InstallerException e) {
15449                        Slog.w(TAG, String.valueOf(e));
15450                    }
15451                }
15452                removeCodePathLI(codeFile);
15453            }
15454            return true;
15455        }
15456
15457        void cleanUpResourcesLI() {
15458            throw new UnsupportedOperationException();
15459        }
15460
15461        boolean doPostDeleteLI(boolean delete) {
15462            throw new UnsupportedOperationException();
15463        }
15464    }
15465
15466    static String getAsecPackageName(String packageCid) {
15467        int idx = packageCid.lastIndexOf("-");
15468        if (idx == -1) {
15469            return packageCid;
15470        }
15471        return packageCid.substring(0, idx);
15472    }
15473
15474    // Utility method used to create code paths based on package name and available index.
15475    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15476        String idxStr = "";
15477        int idx = 1;
15478        // Fall back to default value of idx=1 if prefix is not
15479        // part of oldCodePath
15480        if (oldCodePath != null) {
15481            String subStr = oldCodePath;
15482            // Drop the suffix right away
15483            if (suffix != null && subStr.endsWith(suffix)) {
15484                subStr = subStr.substring(0, subStr.length() - suffix.length());
15485            }
15486            // If oldCodePath already contains prefix find out the
15487            // ending index to either increment or decrement.
15488            int sidx = subStr.lastIndexOf(prefix);
15489            if (sidx != -1) {
15490                subStr = subStr.substring(sidx + prefix.length());
15491                if (subStr != null) {
15492                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15493                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15494                    }
15495                    try {
15496                        idx = Integer.parseInt(subStr);
15497                        if (idx <= 1) {
15498                            idx++;
15499                        } else {
15500                            idx--;
15501                        }
15502                    } catch(NumberFormatException e) {
15503                    }
15504                }
15505            }
15506        }
15507        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15508        return prefix + idxStr;
15509    }
15510
15511    private File getNextCodePath(File targetDir, String packageName) {
15512        File result;
15513        SecureRandom random = new SecureRandom();
15514        byte[] bytes = new byte[16];
15515        do {
15516            random.nextBytes(bytes);
15517            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15518            result = new File(targetDir, packageName + "-" + suffix);
15519        } while (result.exists());
15520        return result;
15521    }
15522
15523    // Utility method that returns the relative package path with respect
15524    // to the installation directory. Like say for /data/data/com.test-1.apk
15525    // string com.test-1 is returned.
15526    static String deriveCodePathName(String codePath) {
15527        if (codePath == null) {
15528            return null;
15529        }
15530        final File codeFile = new File(codePath);
15531        final String name = codeFile.getName();
15532        if (codeFile.isDirectory()) {
15533            return name;
15534        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15535            final int lastDot = name.lastIndexOf('.');
15536            return name.substring(0, lastDot);
15537        } else {
15538            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15539            return null;
15540        }
15541    }
15542
15543    static class PackageInstalledInfo {
15544        String name;
15545        int uid;
15546        // The set of users that originally had this package installed.
15547        int[] origUsers;
15548        // The set of users that now have this package installed.
15549        int[] newUsers;
15550        PackageParser.Package pkg;
15551        int returnCode;
15552        String returnMsg;
15553        PackageRemovedInfo removedInfo;
15554        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15555
15556        public void setError(int code, String msg) {
15557            setReturnCode(code);
15558            setReturnMessage(msg);
15559            Slog.w(TAG, msg);
15560        }
15561
15562        public void setError(String msg, PackageParserException e) {
15563            setReturnCode(e.error);
15564            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15565            Slog.w(TAG, msg, e);
15566        }
15567
15568        public void setError(String msg, PackageManagerException e) {
15569            returnCode = e.error;
15570            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15571            Slog.w(TAG, msg, e);
15572        }
15573
15574        public void setReturnCode(int returnCode) {
15575            this.returnCode = returnCode;
15576            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15577            for (int i = 0; i < childCount; i++) {
15578                addedChildPackages.valueAt(i).returnCode = returnCode;
15579            }
15580        }
15581
15582        private void setReturnMessage(String returnMsg) {
15583            this.returnMsg = returnMsg;
15584            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15585            for (int i = 0; i < childCount; i++) {
15586                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15587            }
15588        }
15589
15590        // In some error cases we want to convey more info back to the observer
15591        String origPackage;
15592        String origPermission;
15593    }
15594
15595    /*
15596     * Install a non-existing package.
15597     */
15598    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15599            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15600            PackageInstalledInfo res, int installReason) {
15601        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15602
15603        // Remember this for later, in case we need to rollback this install
15604        String pkgName = pkg.packageName;
15605
15606        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15607
15608        synchronized(mPackages) {
15609            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15610            if (renamedPackage != null) {
15611                // A package with the same name is already installed, though
15612                // it has been renamed to an older name.  The package we
15613                // are trying to install should be installed as an update to
15614                // the existing one, but that has not been requested, so bail.
15615                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15616                        + " without first uninstalling package running as "
15617                        + renamedPackage);
15618                return;
15619            }
15620            if (mPackages.containsKey(pkgName)) {
15621                // Don't allow installation over an existing package with the same name.
15622                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15623                        + " without first uninstalling.");
15624                return;
15625            }
15626        }
15627
15628        try {
15629            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15630                    System.currentTimeMillis(), user);
15631
15632            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15633
15634            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15635                prepareAppDataAfterInstallLIF(newPackage);
15636
15637            } else {
15638                // Remove package from internal structures, but keep around any
15639                // data that might have already existed
15640                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15641                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15642            }
15643        } catch (PackageManagerException e) {
15644            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15645        }
15646
15647        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15648    }
15649
15650    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15651        // Can't rotate keys during boot or if sharedUser.
15652        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15653                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15654            return false;
15655        }
15656        // app is using upgradeKeySets; make sure all are valid
15657        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15658        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15659        for (int i = 0; i < upgradeKeySets.length; i++) {
15660            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15661                Slog.wtf(TAG, "Package "
15662                         + (oldPs.name != null ? oldPs.name : "<null>")
15663                         + " contains upgrade-key-set reference to unknown key-set: "
15664                         + upgradeKeySets[i]
15665                         + " reverting to signatures check.");
15666                return false;
15667            }
15668        }
15669        return true;
15670    }
15671
15672    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15673        // Upgrade keysets are being used.  Determine if new package has a superset of the
15674        // required keys.
15675        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15676        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15677        for (int i = 0; i < upgradeKeySets.length; i++) {
15678            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15679            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15680                return true;
15681            }
15682        }
15683        return false;
15684    }
15685
15686    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15687        try (DigestInputStream digestStream =
15688                new DigestInputStream(new FileInputStream(file), digest)) {
15689            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15690        }
15691    }
15692
15693    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15694            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15695            int installReason) {
15696        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15697
15698        final PackageParser.Package oldPackage;
15699        final String pkgName = pkg.packageName;
15700        final int[] allUsers;
15701        final int[] installedUsers;
15702
15703        synchronized(mPackages) {
15704            oldPackage = mPackages.get(pkgName);
15705            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15706
15707            // don't allow upgrade to target a release SDK from a pre-release SDK
15708            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15709                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15710            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15711                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15712            if (oldTargetsPreRelease
15713                    && !newTargetsPreRelease
15714                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15715                Slog.w(TAG, "Can't install package targeting released sdk");
15716                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15717                return;
15718            }
15719
15720            // don't allow an upgrade from full to ephemeral
15721            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
15722            if (isEphemeral && !oldIsEphemeral) {
15723                // can't downgrade from full to ephemeral
15724                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15725                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15726                return;
15727            }
15728
15729            // verify signatures are valid
15730            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15731            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15732                if (!checkUpgradeKeySetLP(ps, pkg)) {
15733                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15734                            "New package not signed by keys specified by upgrade-keysets: "
15735                                    + pkgName);
15736                    return;
15737                }
15738            } else {
15739                // default to original signature matching
15740                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15741                        != PackageManager.SIGNATURE_MATCH) {
15742                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15743                            "New package has a different signature: " + pkgName);
15744                    return;
15745                }
15746            }
15747
15748            // don't allow a system upgrade unless the upgrade hash matches
15749            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15750                byte[] digestBytes = null;
15751                try {
15752                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15753                    updateDigest(digest, new File(pkg.baseCodePath));
15754                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15755                        for (String path : pkg.splitCodePaths) {
15756                            updateDigest(digest, new File(path));
15757                        }
15758                    }
15759                    digestBytes = digest.digest();
15760                } catch (NoSuchAlgorithmException | IOException e) {
15761                    res.setError(INSTALL_FAILED_INVALID_APK,
15762                            "Could not compute hash: " + pkgName);
15763                    return;
15764                }
15765                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15766                    res.setError(INSTALL_FAILED_INVALID_APK,
15767                            "New package fails restrict-update check: " + pkgName);
15768                    return;
15769                }
15770                // retain upgrade restriction
15771                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15772            }
15773
15774            // Check for shared user id changes
15775            String invalidPackageName =
15776                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15777            if (invalidPackageName != null) {
15778                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15779                        "Package " + invalidPackageName + " tried to change user "
15780                                + oldPackage.mSharedUserId);
15781                return;
15782            }
15783
15784            // In case of rollback, remember per-user/profile install state
15785            allUsers = sUserManager.getUserIds();
15786            installedUsers = ps.queryInstalledUsers(allUsers, true);
15787        }
15788
15789        // Update what is removed
15790        res.removedInfo = new PackageRemovedInfo();
15791        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15792        res.removedInfo.removedPackage = oldPackage.packageName;
15793        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15794        res.removedInfo.isUpdate = true;
15795        res.removedInfo.origUsers = installedUsers;
15796        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15797        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15798        for (int i = 0; i < installedUsers.length; i++) {
15799            final int userId = installedUsers[i];
15800            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15801        }
15802
15803        final int childCount = (oldPackage.childPackages != null)
15804                ? oldPackage.childPackages.size() : 0;
15805        for (int i = 0; i < childCount; i++) {
15806            boolean childPackageUpdated = false;
15807            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15808            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15809            if (res.addedChildPackages != null) {
15810                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15811                if (childRes != null) {
15812                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15813                    childRes.removedInfo.removedPackage = childPkg.packageName;
15814                    childRes.removedInfo.isUpdate = true;
15815                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15816                    childPackageUpdated = true;
15817                }
15818            }
15819            if (!childPackageUpdated) {
15820                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15821                childRemovedRes.removedPackage = childPkg.packageName;
15822                childRemovedRes.isUpdate = false;
15823                childRemovedRes.dataRemoved = true;
15824                synchronized (mPackages) {
15825                    if (childPs != null) {
15826                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15827                    }
15828                }
15829                if (res.removedInfo.removedChildPackages == null) {
15830                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15831                }
15832                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15833            }
15834        }
15835
15836        boolean sysPkg = (isSystemApp(oldPackage));
15837        if (sysPkg) {
15838            // Set the system/privileged flags as needed
15839            final boolean privileged =
15840                    (oldPackage.applicationInfo.privateFlags
15841                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15842            final int systemPolicyFlags = policyFlags
15843                    | PackageParser.PARSE_IS_SYSTEM
15844                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15845
15846            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15847                    user, allUsers, installerPackageName, res, installReason);
15848        } else {
15849            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15850                    user, allUsers, installerPackageName, res, installReason);
15851        }
15852    }
15853
15854    public List<String> getPreviousCodePaths(String packageName) {
15855        final PackageSetting ps = mSettings.mPackages.get(packageName);
15856        final List<String> result = new ArrayList<String>();
15857        if (ps != null && ps.oldCodePaths != null) {
15858            result.addAll(ps.oldCodePaths);
15859        }
15860        return result;
15861    }
15862
15863    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15864            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15865            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15866            int installReason) {
15867        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15868                + deletedPackage);
15869
15870        String pkgName = deletedPackage.packageName;
15871        boolean deletedPkg = true;
15872        boolean addedPkg = false;
15873        boolean updatedSettings = false;
15874        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15875        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15876                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15877
15878        final long origUpdateTime = (pkg.mExtras != null)
15879                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15880
15881        // First delete the existing package while retaining the data directory
15882        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15883                res.removedInfo, true, pkg)) {
15884            // If the existing package wasn't successfully deleted
15885            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15886            deletedPkg = false;
15887        } else {
15888            // Successfully deleted the old package; proceed with replace.
15889
15890            // If deleted package lived in a container, give users a chance to
15891            // relinquish resources before killing.
15892            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15893                if (DEBUG_INSTALL) {
15894                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15895                }
15896                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15897                final ArrayList<String> pkgList = new ArrayList<String>(1);
15898                pkgList.add(deletedPackage.applicationInfo.packageName);
15899                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15900            }
15901
15902            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15903                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15904            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15905
15906            try {
15907                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15908                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15909                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15910                        installReason);
15911
15912                // Update the in-memory copy of the previous code paths.
15913                PackageSetting ps = mSettings.mPackages.get(pkgName);
15914                if (!killApp) {
15915                    if (ps.oldCodePaths == null) {
15916                        ps.oldCodePaths = new ArraySet<>();
15917                    }
15918                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15919                    if (deletedPackage.splitCodePaths != null) {
15920                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15921                    }
15922                } else {
15923                    ps.oldCodePaths = null;
15924                }
15925                if (ps.childPackageNames != null) {
15926                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15927                        final String childPkgName = ps.childPackageNames.get(i);
15928                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15929                        childPs.oldCodePaths = ps.oldCodePaths;
15930                    }
15931                }
15932                prepareAppDataAfterInstallLIF(newPackage);
15933                addedPkg = true;
15934            } catch (PackageManagerException e) {
15935                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15936            }
15937        }
15938
15939        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15940            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15941
15942            // Revert all internal state mutations and added folders for the failed install
15943            if (addedPkg) {
15944                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15945                        res.removedInfo, true, null);
15946            }
15947
15948            // Restore the old package
15949            if (deletedPkg) {
15950                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15951                File restoreFile = new File(deletedPackage.codePath);
15952                // Parse old package
15953                boolean oldExternal = isExternal(deletedPackage);
15954                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15955                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15956                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15957                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15958                try {
15959                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15960                            null);
15961                } catch (PackageManagerException e) {
15962                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15963                            + e.getMessage());
15964                    return;
15965                }
15966
15967                synchronized (mPackages) {
15968                    // Ensure the installer package name up to date
15969                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15970
15971                    // Update permissions for restored package
15972                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15973
15974                    mSettings.writeLPr();
15975                }
15976
15977                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15978            }
15979        } else {
15980            synchronized (mPackages) {
15981                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15982                if (ps != null) {
15983                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15984                    if (res.removedInfo.removedChildPackages != null) {
15985                        final int childCount = res.removedInfo.removedChildPackages.size();
15986                        // Iterate in reverse as we may modify the collection
15987                        for (int i = childCount - 1; i >= 0; i--) {
15988                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15989                            if (res.addedChildPackages.containsKey(childPackageName)) {
15990                                res.removedInfo.removedChildPackages.removeAt(i);
15991                            } else {
15992                                PackageRemovedInfo childInfo = res.removedInfo
15993                                        .removedChildPackages.valueAt(i);
15994                                childInfo.removedForAllUsers = mPackages.get(
15995                                        childInfo.removedPackage) == null;
15996                            }
15997                        }
15998                    }
15999                }
16000            }
16001        }
16002    }
16003
16004    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16005            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16006            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16007            int installReason) {
16008        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16009                + ", old=" + deletedPackage);
16010
16011        final boolean disabledSystem;
16012
16013        // Remove existing system package
16014        removePackageLI(deletedPackage, true);
16015
16016        synchronized (mPackages) {
16017            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16018        }
16019        if (!disabledSystem) {
16020            // We didn't need to disable the .apk as a current system package,
16021            // which means we are replacing another update that is already
16022            // installed.  We need to make sure to delete the older one's .apk.
16023            res.removedInfo.args = createInstallArgsForExisting(0,
16024                    deletedPackage.applicationInfo.getCodePath(),
16025                    deletedPackage.applicationInfo.getResourcePath(),
16026                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16027        } else {
16028            res.removedInfo.args = null;
16029        }
16030
16031        // Successfully disabled the old package. Now proceed with re-installation
16032        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16033                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16034        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16035
16036        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16037        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16038                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16039
16040        PackageParser.Package newPackage = null;
16041        try {
16042            // Add the package to the internal data structures
16043            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16044
16045            // Set the update and install times
16046            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16047            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16048                    System.currentTimeMillis());
16049
16050            // Update the package dynamic state if succeeded
16051            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16052                // Now that the install succeeded make sure we remove data
16053                // directories for any child package the update removed.
16054                final int deletedChildCount = (deletedPackage.childPackages != null)
16055                        ? deletedPackage.childPackages.size() : 0;
16056                final int newChildCount = (newPackage.childPackages != null)
16057                        ? newPackage.childPackages.size() : 0;
16058                for (int i = 0; i < deletedChildCount; i++) {
16059                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16060                    boolean childPackageDeleted = true;
16061                    for (int j = 0; j < newChildCount; j++) {
16062                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16063                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16064                            childPackageDeleted = false;
16065                            break;
16066                        }
16067                    }
16068                    if (childPackageDeleted) {
16069                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16070                                deletedChildPkg.packageName);
16071                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16072                            PackageRemovedInfo removedChildRes = res.removedInfo
16073                                    .removedChildPackages.get(deletedChildPkg.packageName);
16074                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16075                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16076                        }
16077                    }
16078                }
16079
16080                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16081                        installReason);
16082                prepareAppDataAfterInstallLIF(newPackage);
16083            }
16084        } catch (PackageManagerException e) {
16085            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16086            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16087        }
16088
16089        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16090            // Re installation failed. Restore old information
16091            // Remove new pkg information
16092            if (newPackage != null) {
16093                removeInstalledPackageLI(newPackage, true);
16094            }
16095            // Add back the old system package
16096            try {
16097                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16098            } catch (PackageManagerException e) {
16099                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16100            }
16101
16102            synchronized (mPackages) {
16103                if (disabledSystem) {
16104                    enableSystemPackageLPw(deletedPackage);
16105                }
16106
16107                // Ensure the installer package name up to date
16108                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16109
16110                // Update permissions for restored package
16111                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16112
16113                mSettings.writeLPr();
16114            }
16115
16116            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16117                    + " after failed upgrade");
16118        }
16119    }
16120
16121    /**
16122     * Checks whether the parent or any of the child packages have a change shared
16123     * user. For a package to be a valid update the shred users of the parent and
16124     * the children should match. We may later support changing child shared users.
16125     * @param oldPkg The updated package.
16126     * @param newPkg The update package.
16127     * @return The shared user that change between the versions.
16128     */
16129    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16130            PackageParser.Package newPkg) {
16131        // Check parent shared user
16132        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16133            return newPkg.packageName;
16134        }
16135        // Check child shared users
16136        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16137        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16138        for (int i = 0; i < newChildCount; i++) {
16139            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16140            // If this child was present, did it have the same shared user?
16141            for (int j = 0; j < oldChildCount; j++) {
16142                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16143                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16144                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16145                    return newChildPkg.packageName;
16146                }
16147            }
16148        }
16149        return null;
16150    }
16151
16152    private void removeNativeBinariesLI(PackageSetting ps) {
16153        // Remove the lib path for the parent package
16154        if (ps != null) {
16155            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16156            // Remove the lib path for the child packages
16157            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16158            for (int i = 0; i < childCount; i++) {
16159                PackageSetting childPs = null;
16160                synchronized (mPackages) {
16161                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16162                }
16163                if (childPs != null) {
16164                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16165                            .legacyNativeLibraryPathString);
16166                }
16167            }
16168        }
16169    }
16170
16171    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16172        // Enable the parent package
16173        mSettings.enableSystemPackageLPw(pkg.packageName);
16174        // Enable the child packages
16175        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16176        for (int i = 0; i < childCount; i++) {
16177            PackageParser.Package childPkg = pkg.childPackages.get(i);
16178            mSettings.enableSystemPackageLPw(childPkg.packageName);
16179        }
16180    }
16181
16182    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16183            PackageParser.Package newPkg) {
16184        // Disable the parent package (parent always replaced)
16185        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16186        // Disable the child packages
16187        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16188        for (int i = 0; i < childCount; i++) {
16189            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16190            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16191            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16192        }
16193        return disabled;
16194    }
16195
16196    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16197            String installerPackageName) {
16198        // Enable the parent package
16199        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16200        // Enable the child packages
16201        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16202        for (int i = 0; i < childCount; i++) {
16203            PackageParser.Package childPkg = pkg.childPackages.get(i);
16204            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16205        }
16206    }
16207
16208    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16209        // Collect all used permissions in the UID
16210        ArraySet<String> usedPermissions = new ArraySet<>();
16211        final int packageCount = su.packages.size();
16212        for (int i = 0; i < packageCount; i++) {
16213            PackageSetting ps = su.packages.valueAt(i);
16214            if (ps.pkg == null) {
16215                continue;
16216            }
16217            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16218            for (int j = 0; j < requestedPermCount; j++) {
16219                String permission = ps.pkg.requestedPermissions.get(j);
16220                BasePermission bp = mSettings.mPermissions.get(permission);
16221                if (bp != null) {
16222                    usedPermissions.add(permission);
16223                }
16224            }
16225        }
16226
16227        PermissionsState permissionsState = su.getPermissionsState();
16228        // Prune install permissions
16229        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16230        final int installPermCount = installPermStates.size();
16231        for (int i = installPermCount - 1; i >= 0;  i--) {
16232            PermissionState permissionState = installPermStates.get(i);
16233            if (!usedPermissions.contains(permissionState.getName())) {
16234                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16235                if (bp != null) {
16236                    permissionsState.revokeInstallPermission(bp);
16237                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16238                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16239                }
16240            }
16241        }
16242
16243        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16244
16245        // Prune runtime permissions
16246        for (int userId : allUserIds) {
16247            List<PermissionState> runtimePermStates = permissionsState
16248                    .getRuntimePermissionStates(userId);
16249            final int runtimePermCount = runtimePermStates.size();
16250            for (int i = runtimePermCount - 1; i >= 0; i--) {
16251                PermissionState permissionState = runtimePermStates.get(i);
16252                if (!usedPermissions.contains(permissionState.getName())) {
16253                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16254                    if (bp != null) {
16255                        permissionsState.revokeRuntimePermission(bp, userId);
16256                        permissionsState.updatePermissionFlags(bp, userId,
16257                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16258                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16259                                runtimePermissionChangedUserIds, userId);
16260                    }
16261                }
16262            }
16263        }
16264
16265        return runtimePermissionChangedUserIds;
16266    }
16267
16268    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16269            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16270        // Update the parent package setting
16271        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16272                res, user, installReason);
16273        // Update the child packages setting
16274        final int childCount = (newPackage.childPackages != null)
16275                ? newPackage.childPackages.size() : 0;
16276        for (int i = 0; i < childCount; i++) {
16277            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16278            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16279            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16280                    childRes.origUsers, childRes, user, installReason);
16281        }
16282    }
16283
16284    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16285            String installerPackageName, int[] allUsers, int[] installedForUsers,
16286            PackageInstalledInfo res, UserHandle user, int installReason) {
16287        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16288
16289        String pkgName = newPackage.packageName;
16290        synchronized (mPackages) {
16291            //write settings. the installStatus will be incomplete at this stage.
16292            //note that the new package setting would have already been
16293            //added to mPackages. It hasn't been persisted yet.
16294            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16295            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16296            mSettings.writeLPr();
16297            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16298        }
16299
16300        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16301        synchronized (mPackages) {
16302            updatePermissionsLPw(newPackage.packageName, newPackage,
16303                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16304                            ? UPDATE_PERMISSIONS_ALL : 0));
16305            // For system-bundled packages, we assume that installing an upgraded version
16306            // of the package implies that the user actually wants to run that new code,
16307            // so we enable the package.
16308            PackageSetting ps = mSettings.mPackages.get(pkgName);
16309            final int userId = user.getIdentifier();
16310            if (ps != null) {
16311                if (isSystemApp(newPackage)) {
16312                    if (DEBUG_INSTALL) {
16313                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16314                    }
16315                    // Enable system package for requested users
16316                    if (res.origUsers != null) {
16317                        for (int origUserId : res.origUsers) {
16318                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16319                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16320                                        origUserId, installerPackageName);
16321                            }
16322                        }
16323                    }
16324                    // Also convey the prior install/uninstall state
16325                    if (allUsers != null && installedForUsers != null) {
16326                        for (int currentUserId : allUsers) {
16327                            final boolean installed = ArrayUtils.contains(
16328                                    installedForUsers, currentUserId);
16329                            if (DEBUG_INSTALL) {
16330                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16331                            }
16332                            ps.setInstalled(installed, currentUserId);
16333                        }
16334                        // these install state changes will be persisted in the
16335                        // upcoming call to mSettings.writeLPr().
16336                    }
16337                }
16338                // It's implied that when a user requests installation, they want the app to be
16339                // installed and enabled.
16340                if (userId != UserHandle.USER_ALL) {
16341                    ps.setInstalled(true, userId);
16342                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16343                }
16344
16345                // When replacing an existing package, preserve the original install reason for all
16346                // users that had the package installed before.
16347                final Set<Integer> previousUserIds = new ArraySet<>();
16348                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16349                    final int installReasonCount = res.removedInfo.installReasons.size();
16350                    for (int i = 0; i < installReasonCount; i++) {
16351                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16352                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16353                        ps.setInstallReason(previousInstallReason, previousUserId);
16354                        previousUserIds.add(previousUserId);
16355                    }
16356                }
16357
16358                // Set install reason for users that are having the package newly installed.
16359                if (userId == UserHandle.USER_ALL) {
16360                    for (int currentUserId : sUserManager.getUserIds()) {
16361                        if (!previousUserIds.contains(currentUserId)) {
16362                            ps.setInstallReason(installReason, currentUserId);
16363                        }
16364                    }
16365                } else if (!previousUserIds.contains(userId)) {
16366                    ps.setInstallReason(installReason, userId);
16367                }
16368            }
16369            res.name = pkgName;
16370            res.uid = newPackage.applicationInfo.uid;
16371            res.pkg = newPackage;
16372            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16373            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16374            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16375            //to update install status
16376            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16377            mSettings.writeLPr();
16378            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16379        }
16380
16381        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16382    }
16383
16384    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16385        try {
16386            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16387            installPackageLI(args, res);
16388        } finally {
16389            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16390        }
16391    }
16392
16393    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16394        final int installFlags = args.installFlags;
16395        final String installerPackageName = args.installerPackageName;
16396        final String volumeUuid = args.volumeUuid;
16397        final File tmpPackageFile = new File(args.getCodePath());
16398        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16399        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16400                || (args.volumeUuid != null));
16401        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16402        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16403        boolean replace = false;
16404        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16405        if (args.move != null) {
16406            // moving a complete application; perform an initial scan on the new install location
16407            scanFlags |= SCAN_INITIAL;
16408        }
16409        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16410            scanFlags |= SCAN_DONT_KILL_APP;
16411        }
16412
16413        // Result object to be returned
16414        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16415
16416        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16417
16418        // Sanity check
16419        if (ephemeral && (forwardLocked || onExternal)) {
16420            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16421                    + " external=" + onExternal);
16422            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16423            return;
16424        }
16425
16426        // Retrieve PackageSettings and parse package
16427        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16428                | PackageParser.PARSE_ENFORCE_CODE
16429                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16430                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16431                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16432                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16433        PackageParser pp = new PackageParser();
16434        pp.setSeparateProcesses(mSeparateProcesses);
16435        pp.setDisplayMetrics(mMetrics);
16436
16437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16438        final PackageParser.Package pkg;
16439        try {
16440            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16441        } catch (PackageParserException e) {
16442            res.setError("Failed parse during installPackageLI", e);
16443            return;
16444        } finally {
16445            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16446        }
16447
16448        // Ephemeral apps must have target SDK >= O.
16449        // TODO: Update conditional and error message when O gets locked down
16450        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16451            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16452                    "Ephemeral apps must have target SDK version of at least O");
16453            return;
16454        }
16455
16456        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16457            // Static shared libraries have synthetic package names
16458            renameStaticSharedLibraryPackage(pkg);
16459
16460            // No static shared libs on external storage
16461            if (onExternal) {
16462                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16463                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16464                        "Packages declaring static-shared libs cannot be updated");
16465                return;
16466            }
16467        }
16468
16469        // If we are installing a clustered package add results for the children
16470        if (pkg.childPackages != null) {
16471            synchronized (mPackages) {
16472                final int childCount = pkg.childPackages.size();
16473                for (int i = 0; i < childCount; i++) {
16474                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16475                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16476                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16477                    childRes.pkg = childPkg;
16478                    childRes.name = childPkg.packageName;
16479                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16480                    if (childPs != null) {
16481                        childRes.origUsers = childPs.queryInstalledUsers(
16482                                sUserManager.getUserIds(), true);
16483                    }
16484                    if ((mPackages.containsKey(childPkg.packageName))) {
16485                        childRes.removedInfo = new PackageRemovedInfo();
16486                        childRes.removedInfo.removedPackage = childPkg.packageName;
16487                    }
16488                    if (res.addedChildPackages == null) {
16489                        res.addedChildPackages = new ArrayMap<>();
16490                    }
16491                    res.addedChildPackages.put(childPkg.packageName, childRes);
16492                }
16493            }
16494        }
16495
16496        // If package doesn't declare API override, mark that we have an install
16497        // time CPU ABI override.
16498        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16499            pkg.cpuAbiOverride = args.abiOverride;
16500        }
16501
16502        String pkgName = res.name = pkg.packageName;
16503        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16504            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16505                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16506                return;
16507            }
16508        }
16509
16510        try {
16511            // either use what we've been given or parse directly from the APK
16512            if (args.certificates != null) {
16513                try {
16514                    PackageParser.populateCertificates(pkg, args.certificates);
16515                } catch (PackageParserException e) {
16516                    // there was something wrong with the certificates we were given;
16517                    // try to pull them from the APK
16518                    PackageParser.collectCertificates(pkg, parseFlags);
16519                }
16520            } else {
16521                PackageParser.collectCertificates(pkg, parseFlags);
16522            }
16523        } catch (PackageParserException e) {
16524            res.setError("Failed collect during installPackageLI", e);
16525            return;
16526        }
16527
16528        // Get rid of all references to package scan path via parser.
16529        pp = null;
16530        String oldCodePath = null;
16531        boolean systemApp = false;
16532        synchronized (mPackages) {
16533            // Check if installing already existing package
16534            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16535                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16536                if (pkg.mOriginalPackages != null
16537                        && pkg.mOriginalPackages.contains(oldName)
16538                        && mPackages.containsKey(oldName)) {
16539                    // This package is derived from an original package,
16540                    // and this device has been updating from that original
16541                    // name.  We must continue using the original name, so
16542                    // rename the new package here.
16543                    pkg.setPackageName(oldName);
16544                    pkgName = pkg.packageName;
16545                    replace = true;
16546                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16547                            + oldName + " pkgName=" + pkgName);
16548                } else if (mPackages.containsKey(pkgName)) {
16549                    // This package, under its official name, already exists
16550                    // on the device; we should replace it.
16551                    replace = true;
16552                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16553                }
16554
16555                // Child packages are installed through the parent package
16556                if (pkg.parentPackage != null) {
16557                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16558                            "Package " + pkg.packageName + " is child of package "
16559                                    + pkg.parentPackage.parentPackage + ". Child packages "
16560                                    + "can be updated only through the parent package.");
16561                    return;
16562                }
16563
16564                if (replace) {
16565                    // Prevent apps opting out from runtime permissions
16566                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16567                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16568                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16569                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16570                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16571                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16572                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16573                                        + " doesn't support runtime permissions but the old"
16574                                        + " target SDK " + oldTargetSdk + " does.");
16575                        return;
16576                    }
16577
16578                    // Prevent installing of child packages
16579                    if (oldPackage.parentPackage != null) {
16580                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16581                                "Package " + pkg.packageName + " is child of package "
16582                                        + oldPackage.parentPackage + ". Child packages "
16583                                        + "can be updated only through the parent package.");
16584                        return;
16585                    }
16586                }
16587            }
16588
16589            PackageSetting ps = mSettings.mPackages.get(pkgName);
16590            if (ps != null) {
16591                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16592
16593                // Static shared libs have same package with different versions where
16594                // we internally use a synthetic package name to allow multiple versions
16595                // of the same package, therefore we need to compare signatures against
16596                // the package setting for the latest library version.
16597                PackageSetting signatureCheckPs = ps;
16598                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16599                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16600                    if (libraryEntry != null) {
16601                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16602                    }
16603                }
16604
16605                // Quick sanity check that we're signed correctly if updating;
16606                // we'll check this again later when scanning, but we want to
16607                // bail early here before tripping over redefined permissions.
16608                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16609                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16610                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16611                                + pkg.packageName + " upgrade keys do not match the "
16612                                + "previously installed version");
16613                        return;
16614                    }
16615                } else {
16616                    try {
16617                        verifySignaturesLP(signatureCheckPs, pkg);
16618                    } catch (PackageManagerException e) {
16619                        res.setError(e.error, e.getMessage());
16620                        return;
16621                    }
16622                }
16623
16624                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16625                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16626                    systemApp = (ps.pkg.applicationInfo.flags &
16627                            ApplicationInfo.FLAG_SYSTEM) != 0;
16628                }
16629                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16630            }
16631
16632            // Check whether the newly-scanned package wants to define an already-defined perm
16633            int N = pkg.permissions.size();
16634            for (int i = N-1; i >= 0; i--) {
16635                PackageParser.Permission perm = pkg.permissions.get(i);
16636                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16637                if (bp != null) {
16638                    // If the defining package is signed with our cert, it's okay.  This
16639                    // also includes the "updating the same package" case, of course.
16640                    // "updating same package" could also involve key-rotation.
16641                    final boolean sigsOk;
16642                    if (bp.sourcePackage.equals(pkg.packageName)
16643                            && (bp.packageSetting instanceof PackageSetting)
16644                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16645                                    scanFlags))) {
16646                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16647                    } else {
16648                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16649                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16650                    }
16651                    if (!sigsOk) {
16652                        // If the owning package is the system itself, we log but allow
16653                        // install to proceed; we fail the install on all other permission
16654                        // redefinitions.
16655                        if (!bp.sourcePackage.equals("android")) {
16656                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16657                                    + pkg.packageName + " attempting to redeclare permission "
16658                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16659                            res.origPermission = perm.info.name;
16660                            res.origPackage = bp.sourcePackage;
16661                            return;
16662                        } else {
16663                            Slog.w(TAG, "Package " + pkg.packageName
16664                                    + " attempting to redeclare system permission "
16665                                    + perm.info.name + "; ignoring new declaration");
16666                            pkg.permissions.remove(i);
16667                        }
16668                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16669                        // Prevent apps to change protection level to dangerous from any other
16670                        // type as this would allow a privilege escalation where an app adds a
16671                        // normal/signature permission in other app's group and later redefines
16672                        // it as dangerous leading to the group auto-grant.
16673                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16674                                == PermissionInfo.PROTECTION_DANGEROUS) {
16675                            if (bp != null && !bp.isRuntime()) {
16676                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16677                                        + "non-runtime permission " + perm.info.name
16678                                        + " to runtime; keeping old protection level");
16679                                perm.info.protectionLevel = bp.protectionLevel;
16680                            }
16681                        }
16682                    }
16683                }
16684            }
16685        }
16686
16687        if (systemApp) {
16688            if (onExternal) {
16689                // Abort update; system app can't be replaced with app on sdcard
16690                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16691                        "Cannot install updates to system apps on sdcard");
16692                return;
16693            } else if (ephemeral) {
16694                // Abort update; system app can't be replaced with an ephemeral app
16695                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16696                        "Cannot update a system app with an ephemeral app");
16697                return;
16698            }
16699        }
16700
16701        if (args.move != null) {
16702            // We did an in-place move, so dex is ready to roll
16703            scanFlags |= SCAN_NO_DEX;
16704            scanFlags |= SCAN_MOVE;
16705
16706            synchronized (mPackages) {
16707                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16708                if (ps == null) {
16709                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16710                            "Missing settings for moved package " + pkgName);
16711                }
16712
16713                // We moved the entire application as-is, so bring over the
16714                // previously derived ABI information.
16715                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16716                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16717            }
16718
16719        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16720            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16721            scanFlags |= SCAN_NO_DEX;
16722
16723            try {
16724                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16725                    args.abiOverride : pkg.cpuAbiOverride);
16726                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16727                        true /*extractLibs*/, mAppLib32InstallDir);
16728            } catch (PackageManagerException pme) {
16729                Slog.e(TAG, "Error deriving application ABI", pme);
16730                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16731                return;
16732            }
16733
16734            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16735            // Do not run PackageDexOptimizer through the local performDexOpt
16736            // method because `pkg` may not be in `mPackages` yet.
16737            //
16738            // Also, don't fail application installs if the dexopt step fails.
16739            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16740                    null /* instructionSets */, false /* checkProfiles */,
16741                    getCompilerFilterForReason(REASON_INSTALL),
16742                    getOrCreateCompilerPackageStats(pkg));
16743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16744
16745            // Notify BackgroundDexOptService that the package has been changed.
16746            // If this is an update of a package which used to fail to compile,
16747            // BDOS will remove it from its blacklist.
16748            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16749        }
16750
16751        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16752            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16753            return;
16754        }
16755
16756        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16757
16758        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16759                "installPackageLI")) {
16760            if (replace) {
16761                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16762                    // Static libs have a synthetic package name containing the version
16763                    // and cannot be updated as an update would get a new package name,
16764                    // unless this is the exact same version code which is useful for
16765                    // development.
16766                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16767                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16768                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16769                                + "static-shared libs cannot be updated");
16770                        return;
16771                    }
16772                }
16773                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16774                        installerPackageName, res, args.installReason);
16775            } else {
16776                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16777                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16778            }
16779        }
16780        synchronized (mPackages) {
16781            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16782            if (ps != null) {
16783                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16784            }
16785
16786            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16787            for (int i = 0; i < childCount; i++) {
16788                PackageParser.Package childPkg = pkg.childPackages.get(i);
16789                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16790                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16791                if (childPs != null) {
16792                    childRes.newUsers = childPs.queryInstalledUsers(
16793                            sUserManager.getUserIds(), true);
16794                }
16795            }
16796        }
16797    }
16798
16799    private void startIntentFilterVerifications(int userId, boolean replacing,
16800            PackageParser.Package pkg) {
16801        if (mIntentFilterVerifierComponent == null) {
16802            Slog.w(TAG, "No IntentFilter verification will not be done as "
16803                    + "there is no IntentFilterVerifier available!");
16804            return;
16805        }
16806
16807        final int verifierUid = getPackageUid(
16808                mIntentFilterVerifierComponent.getPackageName(),
16809                MATCH_DEBUG_TRIAGED_MISSING,
16810                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16811
16812        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16813        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16814        mHandler.sendMessage(msg);
16815
16816        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16817        for (int i = 0; i < childCount; i++) {
16818            PackageParser.Package childPkg = pkg.childPackages.get(i);
16819            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16820            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16821            mHandler.sendMessage(msg);
16822        }
16823    }
16824
16825    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16826            PackageParser.Package pkg) {
16827        int size = pkg.activities.size();
16828        if (size == 0) {
16829            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16830                    "No activity, so no need to verify any IntentFilter!");
16831            return;
16832        }
16833
16834        final boolean hasDomainURLs = hasDomainURLs(pkg);
16835        if (!hasDomainURLs) {
16836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16837                    "No domain URLs, so no need to verify any IntentFilter!");
16838            return;
16839        }
16840
16841        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16842                + " if any IntentFilter from the " + size
16843                + " Activities needs verification ...");
16844
16845        int count = 0;
16846        final String packageName = pkg.packageName;
16847
16848        synchronized (mPackages) {
16849            // If this is a new install and we see that we've already run verification for this
16850            // package, we have nothing to do: it means the state was restored from backup.
16851            if (!replacing) {
16852                IntentFilterVerificationInfo ivi =
16853                        mSettings.getIntentFilterVerificationLPr(packageName);
16854                if (ivi != null) {
16855                    if (DEBUG_DOMAIN_VERIFICATION) {
16856                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16857                                + ivi.getStatusString());
16858                    }
16859                    return;
16860                }
16861            }
16862
16863            // If any filters need to be verified, then all need to be.
16864            boolean needToVerify = false;
16865            for (PackageParser.Activity a : pkg.activities) {
16866                for (ActivityIntentInfo filter : a.intents) {
16867                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16868                        if (DEBUG_DOMAIN_VERIFICATION) {
16869                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16870                        }
16871                        needToVerify = true;
16872                        break;
16873                    }
16874                }
16875            }
16876
16877            if (needToVerify) {
16878                final int verificationId = mIntentFilterVerificationToken++;
16879                for (PackageParser.Activity a : pkg.activities) {
16880                    for (ActivityIntentInfo filter : a.intents) {
16881                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16882                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16883                                    "Verification needed for IntentFilter:" + filter.toString());
16884                            mIntentFilterVerifier.addOneIntentFilterVerification(
16885                                    verifierUid, userId, verificationId, filter, packageName);
16886                            count++;
16887                        }
16888                    }
16889                }
16890            }
16891        }
16892
16893        if (count > 0) {
16894            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16895                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16896                    +  " for userId:" + userId);
16897            mIntentFilterVerifier.startVerifications(userId);
16898        } else {
16899            if (DEBUG_DOMAIN_VERIFICATION) {
16900                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16901            }
16902        }
16903    }
16904
16905    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16906        final ComponentName cn  = filter.activity.getComponentName();
16907        final String packageName = cn.getPackageName();
16908
16909        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16910                packageName);
16911        if (ivi == null) {
16912            return true;
16913        }
16914        int status = ivi.getStatus();
16915        switch (status) {
16916            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16917            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16918                return true;
16919
16920            default:
16921                // Nothing to do
16922                return false;
16923        }
16924    }
16925
16926    private static boolean isMultiArch(ApplicationInfo info) {
16927        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16928    }
16929
16930    private static boolean isExternal(PackageParser.Package pkg) {
16931        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16932    }
16933
16934    private static boolean isExternal(PackageSetting ps) {
16935        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16936    }
16937
16938    private static boolean isEphemeral(PackageParser.Package pkg) {
16939        return pkg.applicationInfo.isEphemeralApp();
16940    }
16941
16942    private static boolean isEphemeral(PackageSetting ps) {
16943        return ps.pkg != null && isEphemeral(ps.pkg);
16944    }
16945
16946    private static boolean isSystemApp(PackageParser.Package pkg) {
16947        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16948    }
16949
16950    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16951        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16952    }
16953
16954    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16955        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16956    }
16957
16958    private static boolean isSystemApp(PackageSetting ps) {
16959        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16960    }
16961
16962    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16963        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16964    }
16965
16966    private int packageFlagsToInstallFlags(PackageSetting ps) {
16967        int installFlags = 0;
16968        if (isEphemeral(ps)) {
16969            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16970        }
16971        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16972            // This existing package was an external ASEC install when we have
16973            // the external flag without a UUID
16974            installFlags |= PackageManager.INSTALL_EXTERNAL;
16975        }
16976        if (ps.isForwardLocked()) {
16977            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16978        }
16979        return installFlags;
16980    }
16981
16982    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16983        if (isExternal(pkg)) {
16984            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16985                return StorageManager.UUID_PRIMARY_PHYSICAL;
16986            } else {
16987                return pkg.volumeUuid;
16988            }
16989        } else {
16990            return StorageManager.UUID_PRIVATE_INTERNAL;
16991        }
16992    }
16993
16994    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16995        if (isExternal(pkg)) {
16996            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16997                return mSettings.getExternalVersion();
16998            } else {
16999                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17000            }
17001        } else {
17002            return mSettings.getInternalVersion();
17003        }
17004    }
17005
17006    private void deleteTempPackageFiles() {
17007        final FilenameFilter filter = new FilenameFilter() {
17008            public boolean accept(File dir, String name) {
17009                return name.startsWith("vmdl") && name.endsWith(".tmp");
17010            }
17011        };
17012        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17013            file.delete();
17014        }
17015    }
17016
17017    @Override
17018    public void deletePackageAsUser(String packageName, int versionCode,
17019            IPackageDeleteObserver observer, int userId, int flags) {
17020        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17021                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17022    }
17023
17024    @Override
17025    public void deletePackageVersioned(VersionedPackage versionedPackage,
17026            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17027        mContext.enforceCallingOrSelfPermission(
17028                android.Manifest.permission.DELETE_PACKAGES, null);
17029        Preconditions.checkNotNull(versionedPackage);
17030        Preconditions.checkNotNull(observer);
17031        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17032                PackageManager.VERSION_CODE_HIGHEST,
17033                Integer.MAX_VALUE, "versionCode must be >= -1");
17034
17035        final String packageName = versionedPackage.getPackageName();
17036        // TODO: We will change version code to long, so in the new API it is long
17037        final int versionCode = (int) versionedPackage.getVersionCode();
17038        final String internalPackageName;
17039        synchronized (mPackages) {
17040            // Normalize package name to handle renamed packages and static libs
17041            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17042                    // TODO: We will change version code to long, so in the new API it is long
17043                    (int) versionedPackage.getVersionCode());
17044        }
17045
17046        final int uid = Binder.getCallingUid();
17047        if (!isOrphaned(internalPackageName)
17048                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17049            try {
17050                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17051                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17052                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17053                observer.onUserActionRequired(intent);
17054            } catch (RemoteException re) {
17055            }
17056            return;
17057        }
17058        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17059        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17060        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17061            mContext.enforceCallingOrSelfPermission(
17062                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17063                    "deletePackage for user " + userId);
17064        }
17065
17066        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17067            try {
17068                observer.onPackageDeleted(packageName,
17069                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17070            } catch (RemoteException re) {
17071            }
17072            return;
17073        }
17074
17075        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17076            try {
17077                observer.onPackageDeleted(packageName,
17078                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17079            } catch (RemoteException re) {
17080            }
17081            return;
17082        }
17083
17084        if (DEBUG_REMOVE) {
17085            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17086                    + " deleteAllUsers: " + deleteAllUsers + " version="
17087                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17088                    ? "VERSION_CODE_HIGHEST" : versionCode));
17089        }
17090        // Queue up an async operation since the package deletion may take a little while.
17091        mHandler.post(new Runnable() {
17092            public void run() {
17093                mHandler.removeCallbacks(this);
17094                int returnCode;
17095                if (!deleteAllUsers) {
17096                    returnCode = deletePackageX(internalPackageName, versionCode,
17097                            userId, deleteFlags);
17098                } else {
17099                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17100                            internalPackageName, users);
17101                    // If nobody is blocking uninstall, proceed with delete for all users
17102                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17103                        returnCode = deletePackageX(internalPackageName, versionCode,
17104                                userId, deleteFlags);
17105                    } else {
17106                        // Otherwise uninstall individually for users with blockUninstalls=false
17107                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17108                        for (int userId : users) {
17109                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17110                                returnCode = deletePackageX(internalPackageName, versionCode,
17111                                        userId, userFlags);
17112                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17113                                    Slog.w(TAG, "Package delete failed for user " + userId
17114                                            + ", returnCode " + returnCode);
17115                                }
17116                            }
17117                        }
17118                        // The app has only been marked uninstalled for certain users.
17119                        // We still need to report that delete was blocked
17120                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17121                    }
17122                }
17123                try {
17124                    observer.onPackageDeleted(packageName, returnCode, null);
17125                } catch (RemoteException e) {
17126                    Log.i(TAG, "Observer no longer exists.");
17127                } //end catch
17128            } //end run
17129        });
17130    }
17131
17132    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17133        if (pkg.staticSharedLibName != null) {
17134            return pkg.manifestPackageName;
17135        }
17136        return pkg.packageName;
17137    }
17138
17139    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17140        // Handle renamed packages
17141        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17142        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17143
17144        // Is this a static library?
17145        SparseArray<SharedLibraryEntry> versionedLib =
17146                mStaticLibsByDeclaringPackage.get(packageName);
17147        if (versionedLib == null || versionedLib.size() <= 0) {
17148            return packageName;
17149        }
17150
17151        // Figure out which lib versions the caller can see
17152        SparseIntArray versionsCallerCanSee = null;
17153        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17154        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17155                && callingAppId != Process.ROOT_UID) {
17156            versionsCallerCanSee = new SparseIntArray();
17157            String libName = versionedLib.valueAt(0).info.getName();
17158            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17159            if (uidPackages != null) {
17160                for (String uidPackage : uidPackages) {
17161                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17162                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17163                    if (libIdx >= 0) {
17164                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17165                        versionsCallerCanSee.append(libVersion, libVersion);
17166                    }
17167                }
17168            }
17169        }
17170
17171        // Caller can see nothing - done
17172        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17173            return packageName;
17174        }
17175
17176        // Find the version the caller can see and the app version code
17177        SharedLibraryEntry highestVersion = null;
17178        final int versionCount = versionedLib.size();
17179        for (int i = 0; i < versionCount; i++) {
17180            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17181            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17182                    libEntry.info.getVersion()) < 0) {
17183                continue;
17184            }
17185            // TODO: We will change version code to long, so in the new API it is long
17186            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17187            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17188                if (libVersionCode == versionCode) {
17189                    return libEntry.apk;
17190                }
17191            } else if (highestVersion == null) {
17192                highestVersion = libEntry;
17193            } else if (libVersionCode  > highestVersion.info
17194                    .getDeclaringPackage().getVersionCode()) {
17195                highestVersion = libEntry;
17196            }
17197        }
17198
17199        if (highestVersion != null) {
17200            return highestVersion.apk;
17201        }
17202
17203        return packageName;
17204    }
17205
17206    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17207        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17208              || callingUid == Process.SYSTEM_UID) {
17209            return true;
17210        }
17211        final int callingUserId = UserHandle.getUserId(callingUid);
17212        // If the caller installed the pkgName, then allow it to silently uninstall.
17213        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17214            return true;
17215        }
17216
17217        // Allow package verifier to silently uninstall.
17218        if (mRequiredVerifierPackage != null &&
17219                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17220            return true;
17221        }
17222
17223        // Allow package uninstaller to silently uninstall.
17224        if (mRequiredUninstallerPackage != null &&
17225                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17226            return true;
17227        }
17228
17229        // Allow storage manager to silently uninstall.
17230        if (mStorageManagerPackage != null &&
17231                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17232            return true;
17233        }
17234        return false;
17235    }
17236
17237    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17238        int[] result = EMPTY_INT_ARRAY;
17239        for (int userId : userIds) {
17240            if (getBlockUninstallForUser(packageName, userId)) {
17241                result = ArrayUtils.appendInt(result, userId);
17242            }
17243        }
17244        return result;
17245    }
17246
17247    @Override
17248    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17249        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17250    }
17251
17252    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17253        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17254                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17255        try {
17256            if (dpm != null) {
17257                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17258                        /* callingUserOnly =*/ false);
17259                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17260                        : deviceOwnerComponentName.getPackageName();
17261                // Does the package contains the device owner?
17262                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17263                // this check is probably not needed, since DO should be registered as a device
17264                // admin on some user too. (Original bug for this: b/17657954)
17265                if (packageName.equals(deviceOwnerPackageName)) {
17266                    return true;
17267                }
17268                // Does it contain a device admin for any user?
17269                int[] users;
17270                if (userId == UserHandle.USER_ALL) {
17271                    users = sUserManager.getUserIds();
17272                } else {
17273                    users = new int[]{userId};
17274                }
17275                for (int i = 0; i < users.length; ++i) {
17276                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17277                        return true;
17278                    }
17279                }
17280            }
17281        } catch (RemoteException e) {
17282        }
17283        return false;
17284    }
17285
17286    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17287        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17288    }
17289
17290    /**
17291     *  This method is an internal method that could be get invoked either
17292     *  to delete an installed package or to clean up a failed installation.
17293     *  After deleting an installed package, a broadcast is sent to notify any
17294     *  listeners that the package has been removed. For cleaning up a failed
17295     *  installation, the broadcast is not necessary since the package's
17296     *  installation wouldn't have sent the initial broadcast either
17297     *  The key steps in deleting a package are
17298     *  deleting the package information in internal structures like mPackages,
17299     *  deleting the packages base directories through installd
17300     *  updating mSettings to reflect current status
17301     *  persisting settings for later use
17302     *  sending a broadcast if necessary
17303     */
17304    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17305        final PackageRemovedInfo info = new PackageRemovedInfo();
17306        final boolean res;
17307
17308        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17309                ? UserHandle.USER_ALL : userId;
17310
17311        if (isPackageDeviceAdmin(packageName, removeUser)) {
17312            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17313            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17314        }
17315
17316        PackageSetting uninstalledPs = null;
17317
17318        // for the uninstall-updates case and restricted profiles, remember the per-
17319        // user handle installed state
17320        int[] allUsers;
17321        synchronized (mPackages) {
17322            uninstalledPs = mSettings.mPackages.get(packageName);
17323            if (uninstalledPs == null) {
17324                Slog.w(TAG, "Not removing non-existent package " + packageName);
17325                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17326            }
17327
17328            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17329                    && uninstalledPs.versionCode != versionCode) {
17330                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17331                        + uninstalledPs.versionCode + " != " + versionCode);
17332                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17333            }
17334
17335            // Static shared libs can be declared by any package, so let us not
17336            // allow removing a package if it provides a lib others depend on.
17337            PackageParser.Package pkg = mPackages.get(packageName);
17338            if (pkg != null && pkg.staticSharedLibName != null) {
17339                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17340                        pkg.staticSharedLibVersion);
17341                if (libEntry != null) {
17342                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17343                            libEntry.info, 0, userId);
17344                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17345                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17346                                + " hosting lib " + libEntry.info.getName() + " version "
17347                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17348                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17349                    }
17350                }
17351            }
17352
17353            allUsers = sUserManager.getUserIds();
17354            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17355        }
17356
17357        final int freezeUser;
17358        if (isUpdatedSystemApp(uninstalledPs)
17359                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17360            // We're downgrading a system app, which will apply to all users, so
17361            // freeze them all during the downgrade
17362            freezeUser = UserHandle.USER_ALL;
17363        } else {
17364            freezeUser = removeUser;
17365        }
17366
17367        synchronized (mInstallLock) {
17368            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17369            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17370                    deleteFlags, "deletePackageX")) {
17371                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17372                        deleteFlags | REMOVE_CHATTY, info, true, null);
17373            }
17374            synchronized (mPackages) {
17375                if (res) {
17376                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
17377                }
17378            }
17379        }
17380
17381        if (res) {
17382            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17383            info.sendPackageRemovedBroadcasts(killApp);
17384            info.sendSystemPackageUpdatedBroadcasts();
17385            info.sendSystemPackageAppearedBroadcasts();
17386        }
17387        // Force a gc here.
17388        Runtime.getRuntime().gc();
17389        // Delete the resources here after sending the broadcast to let
17390        // other processes clean up before deleting resources.
17391        if (info.args != null) {
17392            synchronized (mInstallLock) {
17393                info.args.doPostDeleteLI(true);
17394            }
17395        }
17396
17397        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17398    }
17399
17400    class PackageRemovedInfo {
17401        String removedPackage;
17402        int uid = -1;
17403        int removedAppId = -1;
17404        int[] origUsers;
17405        int[] removedUsers = null;
17406        SparseArray<Integer> installReasons;
17407        boolean isRemovedPackageSystemUpdate = false;
17408        boolean isUpdate;
17409        boolean dataRemoved;
17410        boolean removedForAllUsers;
17411        boolean isStaticSharedLib;
17412        // Clean up resources deleted packages.
17413        InstallArgs args = null;
17414        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17415        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17416
17417        void sendPackageRemovedBroadcasts(boolean killApp) {
17418            sendPackageRemovedBroadcastInternal(killApp);
17419            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17420            for (int i = 0; i < childCount; i++) {
17421                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17422                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17423            }
17424        }
17425
17426        void sendSystemPackageUpdatedBroadcasts() {
17427            if (isRemovedPackageSystemUpdate) {
17428                sendSystemPackageUpdatedBroadcastsInternal();
17429                final int childCount = (removedChildPackages != null)
17430                        ? removedChildPackages.size() : 0;
17431                for (int i = 0; i < childCount; i++) {
17432                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17433                    if (childInfo.isRemovedPackageSystemUpdate) {
17434                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17435                    }
17436                }
17437            }
17438        }
17439
17440        void sendSystemPackageAppearedBroadcasts() {
17441            final int packageCount = (appearedChildPackages != null)
17442                    ? appearedChildPackages.size() : 0;
17443            for (int i = 0; i < packageCount; i++) {
17444                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17445                sendPackageAddedForNewUsers(installedInfo.name, true,
17446                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17447            }
17448        }
17449
17450        private void sendSystemPackageUpdatedBroadcastsInternal() {
17451            Bundle extras = new Bundle(2);
17452            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17453            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17454            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17455                    extras, 0, null, null, null);
17456            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17457                    extras, 0, null, null, null);
17458            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17459                    null, 0, removedPackage, null, null);
17460        }
17461
17462        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17463            // Don't send static shared library removal broadcasts as these
17464            // libs are visible only the the apps that depend on them an one
17465            // cannot remove the library if it has a dependency.
17466            if (isStaticSharedLib) {
17467                return;
17468            }
17469            Bundle extras = new Bundle(2);
17470            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17471            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17472            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17473            if (isUpdate || isRemovedPackageSystemUpdate) {
17474                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17475            }
17476            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17477            if (removedPackage != null) {
17478                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17479                        extras, 0, null, null, removedUsers);
17480                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17481                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17482                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17483                            null, null, removedUsers);
17484                }
17485            }
17486            if (removedAppId >= 0) {
17487                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17488                        removedUsers);
17489            }
17490        }
17491    }
17492
17493    /*
17494     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17495     * flag is not set, the data directory is removed as well.
17496     * make sure this flag is set for partially installed apps. If not its meaningless to
17497     * delete a partially installed application.
17498     */
17499    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17500            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17501        String packageName = ps.name;
17502        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17503        // Retrieve object to delete permissions for shared user later on
17504        final PackageParser.Package deletedPkg;
17505        final PackageSetting deletedPs;
17506        // reader
17507        synchronized (mPackages) {
17508            deletedPkg = mPackages.get(packageName);
17509            deletedPs = mSettings.mPackages.get(packageName);
17510            if (outInfo != null) {
17511                outInfo.removedPackage = packageName;
17512                outInfo.isStaticSharedLib = deletedPkg != null
17513                        && deletedPkg.staticSharedLibName != null;
17514                outInfo.removedUsers = deletedPs != null
17515                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17516                        : null;
17517            }
17518        }
17519
17520        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17521
17522        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17523            final PackageParser.Package resolvedPkg;
17524            if (deletedPkg != null) {
17525                resolvedPkg = deletedPkg;
17526            } else {
17527                // We don't have a parsed package when it lives on an ejected
17528                // adopted storage device, so fake something together
17529                resolvedPkg = new PackageParser.Package(ps.name);
17530                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17531            }
17532            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17533                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17534            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17535            if (outInfo != null) {
17536                outInfo.dataRemoved = true;
17537            }
17538            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17539        }
17540
17541        int removedAppId = -1;
17542
17543        // writer
17544        synchronized (mPackages) {
17545            if (deletedPs != null) {
17546                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17547                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17548                    clearDefaultBrowserIfNeeded(packageName);
17549                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17550                    removedAppId = mSettings.removePackageLPw(packageName);
17551                    if (outInfo != null) {
17552                        outInfo.removedAppId = removedAppId;
17553                    }
17554                    updatePermissionsLPw(deletedPs.name, null, 0);
17555                    if (deletedPs.sharedUser != null) {
17556                        // Remove permissions associated with package. Since runtime
17557                        // permissions are per user we have to kill the removed package
17558                        // or packages running under the shared user of the removed
17559                        // package if revoking the permissions requested only by the removed
17560                        // package is successful and this causes a change in gids.
17561                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17562                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17563                                    userId);
17564                            if (userIdToKill == UserHandle.USER_ALL
17565                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17566                                // If gids changed for this user, kill all affected packages.
17567                                mHandler.post(new Runnable() {
17568                                    @Override
17569                                    public void run() {
17570                                        // This has to happen with no lock held.
17571                                        killApplication(deletedPs.name, deletedPs.appId,
17572                                                KILL_APP_REASON_GIDS_CHANGED);
17573                                    }
17574                                });
17575                                break;
17576                            }
17577                        }
17578                    }
17579                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17580                }
17581                // make sure to preserve per-user disabled state if this removal was just
17582                // a downgrade of a system app to the factory package
17583                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17584                    if (DEBUG_REMOVE) {
17585                        Slog.d(TAG, "Propagating install state across downgrade");
17586                    }
17587                    for (int userId : allUserHandles) {
17588                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17589                        if (DEBUG_REMOVE) {
17590                            Slog.d(TAG, "    user " + userId + " => " + installed);
17591                        }
17592                        ps.setInstalled(installed, userId);
17593                    }
17594                }
17595            }
17596            // can downgrade to reader
17597            if (writeSettings) {
17598                // Save settings now
17599                mSettings.writeLPr();
17600            }
17601        }
17602        if (removedAppId != -1) {
17603            // A user ID was deleted here. Go through all users and remove it
17604            // from KeyStore.
17605            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17606        }
17607    }
17608
17609    static boolean locationIsPrivileged(File path) {
17610        try {
17611            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17612                    .getCanonicalPath();
17613            return path.getCanonicalPath().startsWith(privilegedAppDir);
17614        } catch (IOException e) {
17615            Slog.e(TAG, "Unable to access code path " + path);
17616        }
17617        return false;
17618    }
17619
17620    /*
17621     * Tries to delete system package.
17622     */
17623    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17624            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17625            boolean writeSettings) {
17626        if (deletedPs.parentPackageName != null) {
17627            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17628            return false;
17629        }
17630
17631        final boolean applyUserRestrictions
17632                = (allUserHandles != null) && (outInfo.origUsers != null);
17633        final PackageSetting disabledPs;
17634        // Confirm if the system package has been updated
17635        // An updated system app can be deleted. This will also have to restore
17636        // the system pkg from system partition
17637        // reader
17638        synchronized (mPackages) {
17639            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17640        }
17641
17642        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17643                + " disabledPs=" + disabledPs);
17644
17645        if (disabledPs == null) {
17646            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17647            return false;
17648        } else if (DEBUG_REMOVE) {
17649            Slog.d(TAG, "Deleting system pkg from data partition");
17650        }
17651
17652        if (DEBUG_REMOVE) {
17653            if (applyUserRestrictions) {
17654                Slog.d(TAG, "Remembering install states:");
17655                for (int userId : allUserHandles) {
17656                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17657                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17658                }
17659            }
17660        }
17661
17662        // Delete the updated package
17663        outInfo.isRemovedPackageSystemUpdate = true;
17664        if (outInfo.removedChildPackages != null) {
17665            final int childCount = (deletedPs.childPackageNames != null)
17666                    ? deletedPs.childPackageNames.size() : 0;
17667            for (int i = 0; i < childCount; i++) {
17668                String childPackageName = deletedPs.childPackageNames.get(i);
17669                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17670                        .contains(childPackageName)) {
17671                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17672                            childPackageName);
17673                    if (childInfo != null) {
17674                        childInfo.isRemovedPackageSystemUpdate = true;
17675                    }
17676                }
17677            }
17678        }
17679
17680        if (disabledPs.versionCode < deletedPs.versionCode) {
17681            // Delete data for downgrades
17682            flags &= ~PackageManager.DELETE_KEEP_DATA;
17683        } else {
17684            // Preserve data by setting flag
17685            flags |= PackageManager.DELETE_KEEP_DATA;
17686        }
17687
17688        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17689                outInfo, writeSettings, disabledPs.pkg);
17690        if (!ret) {
17691            return false;
17692        }
17693
17694        // writer
17695        synchronized (mPackages) {
17696            // Reinstate the old system package
17697            enableSystemPackageLPw(disabledPs.pkg);
17698            // Remove any native libraries from the upgraded package.
17699            removeNativeBinariesLI(deletedPs);
17700        }
17701
17702        // Install the system package
17703        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17704        int parseFlags = mDefParseFlags
17705                | PackageParser.PARSE_MUST_BE_APK
17706                | PackageParser.PARSE_IS_SYSTEM
17707                | PackageParser.PARSE_IS_SYSTEM_DIR;
17708        if (locationIsPrivileged(disabledPs.codePath)) {
17709            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17710        }
17711
17712        final PackageParser.Package newPkg;
17713        try {
17714            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17715                0 /* currentTime */, null);
17716        } catch (PackageManagerException e) {
17717            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17718                    + e.getMessage());
17719            return false;
17720        }
17721
17722        try {
17723            // update shared libraries for the newly re-installed system package
17724            updateSharedLibrariesLPr(newPkg, null);
17725        } catch (PackageManagerException e) {
17726            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17727        }
17728
17729        prepareAppDataAfterInstallLIF(newPkg);
17730
17731        // writer
17732        synchronized (mPackages) {
17733            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17734
17735            // Propagate the permissions state as we do not want to drop on the floor
17736            // runtime permissions. The update permissions method below will take
17737            // care of removing obsolete permissions and grant install permissions.
17738            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17739            updatePermissionsLPw(newPkg.packageName, newPkg,
17740                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17741
17742            if (applyUserRestrictions) {
17743                if (DEBUG_REMOVE) {
17744                    Slog.d(TAG, "Propagating install state across reinstall");
17745                }
17746                for (int userId : allUserHandles) {
17747                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17748                    if (DEBUG_REMOVE) {
17749                        Slog.d(TAG, "    user " + userId + " => " + installed);
17750                    }
17751                    ps.setInstalled(installed, userId);
17752
17753                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17754                }
17755                // Regardless of writeSettings we need to ensure that this restriction
17756                // state propagation is persisted
17757                mSettings.writeAllUsersPackageRestrictionsLPr();
17758            }
17759            // can downgrade to reader here
17760            if (writeSettings) {
17761                mSettings.writeLPr();
17762            }
17763        }
17764        return true;
17765    }
17766
17767    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17768            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17769            PackageRemovedInfo outInfo, boolean writeSettings,
17770            PackageParser.Package replacingPackage) {
17771        synchronized (mPackages) {
17772            if (outInfo != null) {
17773                outInfo.uid = ps.appId;
17774            }
17775
17776            if (outInfo != null && outInfo.removedChildPackages != null) {
17777                final int childCount = (ps.childPackageNames != null)
17778                        ? ps.childPackageNames.size() : 0;
17779                for (int i = 0; i < childCount; i++) {
17780                    String childPackageName = ps.childPackageNames.get(i);
17781                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17782                    if (childPs == null) {
17783                        return false;
17784                    }
17785                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17786                            childPackageName);
17787                    if (childInfo != null) {
17788                        childInfo.uid = childPs.appId;
17789                    }
17790                }
17791            }
17792        }
17793
17794        // Delete package data from internal structures and also remove data if flag is set
17795        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17796
17797        // Delete the child packages data
17798        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17799        for (int i = 0; i < childCount; i++) {
17800            PackageSetting childPs;
17801            synchronized (mPackages) {
17802                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17803            }
17804            if (childPs != null) {
17805                PackageRemovedInfo childOutInfo = (outInfo != null
17806                        && outInfo.removedChildPackages != null)
17807                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17808                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17809                        && (replacingPackage != null
17810                        && !replacingPackage.hasChildPackage(childPs.name))
17811                        ? flags & ~DELETE_KEEP_DATA : flags;
17812                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17813                        deleteFlags, writeSettings);
17814            }
17815        }
17816
17817        // Delete application code and resources only for parent packages
17818        if (ps.parentPackageName == null) {
17819            if (deleteCodeAndResources && (outInfo != null)) {
17820                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17821                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17822                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17823            }
17824        }
17825
17826        return true;
17827    }
17828
17829    @Override
17830    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17831            int userId) {
17832        mContext.enforceCallingOrSelfPermission(
17833                android.Manifest.permission.DELETE_PACKAGES, null);
17834        synchronized (mPackages) {
17835            PackageSetting ps = mSettings.mPackages.get(packageName);
17836            if (ps == null) {
17837                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17838                return false;
17839            }
17840            // Cannot block uninstall of static shared libs as they are
17841            // considered a part of the using app (emulating static linking).
17842            // Also static libs are installed always on internal storage.
17843            PackageParser.Package pkg = mPackages.get(packageName);
17844            if (pkg != null && pkg.staticSharedLibName != null) {
17845                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17846                        + " providing static shared library: " + pkg.staticSharedLibName);
17847                return false;
17848            }
17849            if (!ps.getInstalled(userId)) {
17850                // Can't block uninstall for an app that is not installed or enabled.
17851                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17852                return false;
17853            }
17854            ps.setBlockUninstall(blockUninstall, userId);
17855            mSettings.writePackageRestrictionsLPr(userId);
17856        }
17857        return true;
17858    }
17859
17860    @Override
17861    public boolean getBlockUninstallForUser(String packageName, int userId) {
17862        synchronized (mPackages) {
17863            PackageSetting ps = mSettings.mPackages.get(packageName);
17864            if (ps == null) {
17865                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17866                return false;
17867            }
17868            return ps.getBlockUninstall(userId);
17869        }
17870    }
17871
17872    @Override
17873    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17874        int callingUid = Binder.getCallingUid();
17875        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17876            throw new SecurityException(
17877                    "setRequiredForSystemUser can only be run by the system or root");
17878        }
17879        synchronized (mPackages) {
17880            PackageSetting ps = mSettings.mPackages.get(packageName);
17881            if (ps == null) {
17882                Log.w(TAG, "Package doesn't exist: " + packageName);
17883                return false;
17884            }
17885            if (systemUserApp) {
17886                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17887            } else {
17888                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17889            }
17890            mSettings.writeLPr();
17891        }
17892        return true;
17893    }
17894
17895    /*
17896     * This method handles package deletion in general
17897     */
17898    private boolean deletePackageLIF(String packageName, UserHandle user,
17899            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17900            PackageRemovedInfo outInfo, boolean writeSettings,
17901            PackageParser.Package replacingPackage) {
17902        if (packageName == null) {
17903            Slog.w(TAG, "Attempt to delete null packageName.");
17904            return false;
17905        }
17906
17907        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17908
17909        PackageSetting ps;
17910        synchronized (mPackages) {
17911            ps = mSettings.mPackages.get(packageName);
17912            if (ps == null) {
17913                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17914                return false;
17915            }
17916
17917            if (ps.parentPackageName != null && (!isSystemApp(ps)
17918                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17919                if (DEBUG_REMOVE) {
17920                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17921                            + ((user == null) ? UserHandle.USER_ALL : user));
17922                }
17923                final int removedUserId = (user != null) ? user.getIdentifier()
17924                        : UserHandle.USER_ALL;
17925                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17926                    return false;
17927                }
17928                markPackageUninstalledForUserLPw(ps, user);
17929                scheduleWritePackageRestrictionsLocked(user);
17930                return true;
17931            }
17932        }
17933
17934        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17935                && user.getIdentifier() != UserHandle.USER_ALL)) {
17936            // The caller is asking that the package only be deleted for a single
17937            // user.  To do this, we just mark its uninstalled state and delete
17938            // its data. If this is a system app, we only allow this to happen if
17939            // they have set the special DELETE_SYSTEM_APP which requests different
17940            // semantics than normal for uninstalling system apps.
17941            markPackageUninstalledForUserLPw(ps, user);
17942
17943            if (!isSystemApp(ps)) {
17944                // Do not uninstall the APK if an app should be cached
17945                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17946                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17947                    // Other user still have this package installed, so all
17948                    // we need to do is clear this user's data and save that
17949                    // it is uninstalled.
17950                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17951                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17952                        return false;
17953                    }
17954                    scheduleWritePackageRestrictionsLocked(user);
17955                    return true;
17956                } else {
17957                    // We need to set it back to 'installed' so the uninstall
17958                    // broadcasts will be sent correctly.
17959                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17960                    ps.setInstalled(true, user.getIdentifier());
17961                }
17962            } else {
17963                // This is a system app, so we assume that the
17964                // other users still have this package installed, so all
17965                // we need to do is clear this user's data and save that
17966                // it is uninstalled.
17967                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17968                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17969                    return false;
17970                }
17971                scheduleWritePackageRestrictionsLocked(user);
17972                return true;
17973            }
17974        }
17975
17976        // If we are deleting a composite package for all users, keep track
17977        // of result for each child.
17978        if (ps.childPackageNames != null && outInfo != null) {
17979            synchronized (mPackages) {
17980                final int childCount = ps.childPackageNames.size();
17981                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17982                for (int i = 0; i < childCount; i++) {
17983                    String childPackageName = ps.childPackageNames.get(i);
17984                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17985                    childInfo.removedPackage = childPackageName;
17986                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17987                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17988                    if (childPs != null) {
17989                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17990                    }
17991                }
17992            }
17993        }
17994
17995        boolean ret = false;
17996        if (isSystemApp(ps)) {
17997            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17998            // When an updated system application is deleted we delete the existing resources
17999            // as well and fall back to existing code in system partition
18000            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18001        } else {
18002            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18003            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18004                    outInfo, writeSettings, replacingPackage);
18005        }
18006
18007        // Take a note whether we deleted the package for all users
18008        if (outInfo != null) {
18009            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18010            if (outInfo.removedChildPackages != null) {
18011                synchronized (mPackages) {
18012                    final int childCount = outInfo.removedChildPackages.size();
18013                    for (int i = 0; i < childCount; i++) {
18014                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18015                        if (childInfo != null) {
18016                            childInfo.removedForAllUsers = mPackages.get(
18017                                    childInfo.removedPackage) == null;
18018                        }
18019                    }
18020                }
18021            }
18022            // If we uninstalled an update to a system app there may be some
18023            // child packages that appeared as they are declared in the system
18024            // app but were not declared in the update.
18025            if (isSystemApp(ps)) {
18026                synchronized (mPackages) {
18027                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18028                    final int childCount = (updatedPs.childPackageNames != null)
18029                            ? updatedPs.childPackageNames.size() : 0;
18030                    for (int i = 0; i < childCount; i++) {
18031                        String childPackageName = updatedPs.childPackageNames.get(i);
18032                        if (outInfo.removedChildPackages == null
18033                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18034                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18035                            if (childPs == null) {
18036                                continue;
18037                            }
18038                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18039                            installRes.name = childPackageName;
18040                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18041                            installRes.pkg = mPackages.get(childPackageName);
18042                            installRes.uid = childPs.pkg.applicationInfo.uid;
18043                            if (outInfo.appearedChildPackages == null) {
18044                                outInfo.appearedChildPackages = new ArrayMap<>();
18045                            }
18046                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18047                        }
18048                    }
18049                }
18050            }
18051        }
18052
18053        return ret;
18054    }
18055
18056    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18057        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18058                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18059        for (int nextUserId : userIds) {
18060            if (DEBUG_REMOVE) {
18061                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18062            }
18063            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18064                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18065                    false /*hidden*/, false /*suspended*/, null, null, null,
18066                    false /*blockUninstall*/,
18067                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18068                    PackageManager.INSTALL_REASON_UNKNOWN);
18069        }
18070    }
18071
18072    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18073            PackageRemovedInfo outInfo) {
18074        final PackageParser.Package pkg;
18075        synchronized (mPackages) {
18076            pkg = mPackages.get(ps.name);
18077        }
18078
18079        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18080                : new int[] {userId};
18081        for (int nextUserId : userIds) {
18082            if (DEBUG_REMOVE) {
18083                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18084                        + nextUserId);
18085            }
18086
18087            destroyAppDataLIF(pkg, userId,
18088                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18089            destroyAppProfilesLIF(pkg, userId);
18090            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18091            schedulePackageCleaning(ps.name, nextUserId, false);
18092            synchronized (mPackages) {
18093                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18094                    scheduleWritePackageRestrictionsLocked(nextUserId);
18095                }
18096                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18097            }
18098        }
18099
18100        if (outInfo != null) {
18101            outInfo.removedPackage = ps.name;
18102            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18103            outInfo.removedAppId = ps.appId;
18104            outInfo.removedUsers = userIds;
18105        }
18106
18107        return true;
18108    }
18109
18110    private final class ClearStorageConnection implements ServiceConnection {
18111        IMediaContainerService mContainerService;
18112
18113        @Override
18114        public void onServiceConnected(ComponentName name, IBinder service) {
18115            synchronized (this) {
18116                mContainerService = IMediaContainerService.Stub
18117                        .asInterface(Binder.allowBlocking(service));
18118                notifyAll();
18119            }
18120        }
18121
18122        @Override
18123        public void onServiceDisconnected(ComponentName name) {
18124        }
18125    }
18126
18127    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18128        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18129
18130        final boolean mounted;
18131        if (Environment.isExternalStorageEmulated()) {
18132            mounted = true;
18133        } else {
18134            final String status = Environment.getExternalStorageState();
18135
18136            mounted = status.equals(Environment.MEDIA_MOUNTED)
18137                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18138        }
18139
18140        if (!mounted) {
18141            return;
18142        }
18143
18144        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18145        int[] users;
18146        if (userId == UserHandle.USER_ALL) {
18147            users = sUserManager.getUserIds();
18148        } else {
18149            users = new int[] { userId };
18150        }
18151        final ClearStorageConnection conn = new ClearStorageConnection();
18152        if (mContext.bindServiceAsUser(
18153                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18154            try {
18155                for (int curUser : users) {
18156                    long timeout = SystemClock.uptimeMillis() + 5000;
18157                    synchronized (conn) {
18158                        long now;
18159                        while (conn.mContainerService == null &&
18160                                (now = SystemClock.uptimeMillis()) < timeout) {
18161                            try {
18162                                conn.wait(timeout - now);
18163                            } catch (InterruptedException e) {
18164                            }
18165                        }
18166                    }
18167                    if (conn.mContainerService == null) {
18168                        return;
18169                    }
18170
18171                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18172                    clearDirectory(conn.mContainerService,
18173                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18174                    if (allData) {
18175                        clearDirectory(conn.mContainerService,
18176                                userEnv.buildExternalStorageAppDataDirs(packageName));
18177                        clearDirectory(conn.mContainerService,
18178                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18179                    }
18180                }
18181            } finally {
18182                mContext.unbindService(conn);
18183            }
18184        }
18185    }
18186
18187    @Override
18188    public void clearApplicationProfileData(String packageName) {
18189        enforceSystemOrRoot("Only the system can clear all profile data");
18190
18191        final PackageParser.Package pkg;
18192        synchronized (mPackages) {
18193            pkg = mPackages.get(packageName);
18194        }
18195
18196        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18197            synchronized (mInstallLock) {
18198                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18199                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18200                        true /* removeBaseMarker */);
18201            }
18202        }
18203    }
18204
18205    @Override
18206    public void clearApplicationUserData(final String packageName,
18207            final IPackageDataObserver observer, final int userId) {
18208        mContext.enforceCallingOrSelfPermission(
18209                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18210
18211        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18212                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18213
18214        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18215            throw new SecurityException("Cannot clear data for a protected package: "
18216                    + packageName);
18217        }
18218        // Queue up an async operation since the package deletion may take a little while.
18219        mHandler.post(new Runnable() {
18220            public void run() {
18221                mHandler.removeCallbacks(this);
18222                final boolean succeeded;
18223                try (PackageFreezer freezer = freezePackage(packageName,
18224                        "clearApplicationUserData")) {
18225                    synchronized (mInstallLock) {
18226                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18227                    }
18228                    clearExternalStorageDataSync(packageName, userId, true);
18229                }
18230                if (succeeded) {
18231                    // invoke DeviceStorageMonitor's update method to clear any notifications
18232                    DeviceStorageMonitorInternal dsm = LocalServices
18233                            .getService(DeviceStorageMonitorInternal.class);
18234                    if (dsm != null) {
18235                        dsm.checkMemory();
18236                    }
18237                }
18238                if(observer != null) {
18239                    try {
18240                        observer.onRemoveCompleted(packageName, succeeded);
18241                    } catch (RemoteException e) {
18242                        Log.i(TAG, "Observer no longer exists.");
18243                    }
18244                } //end if observer
18245            } //end run
18246        });
18247    }
18248
18249    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18250        if (packageName == null) {
18251            Slog.w(TAG, "Attempt to delete null packageName.");
18252            return false;
18253        }
18254
18255        // Try finding details about the requested package
18256        PackageParser.Package pkg;
18257        synchronized (mPackages) {
18258            pkg = mPackages.get(packageName);
18259            if (pkg == null) {
18260                final PackageSetting ps = mSettings.mPackages.get(packageName);
18261                if (ps != null) {
18262                    pkg = ps.pkg;
18263                }
18264            }
18265
18266            if (pkg == null) {
18267                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18268                return false;
18269            }
18270
18271            PackageSetting ps = (PackageSetting) pkg.mExtras;
18272            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18273        }
18274
18275        clearAppDataLIF(pkg, userId,
18276                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18277
18278        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18279        removeKeystoreDataIfNeeded(userId, appId);
18280
18281        UserManagerInternal umInternal = getUserManagerInternal();
18282        final int flags;
18283        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18284            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18285        } else if (umInternal.isUserRunning(userId)) {
18286            flags = StorageManager.FLAG_STORAGE_DE;
18287        } else {
18288            flags = 0;
18289        }
18290        prepareAppDataContentsLIF(pkg, userId, flags);
18291
18292        return true;
18293    }
18294
18295    /**
18296     * Reverts user permission state changes (permissions and flags) in
18297     * all packages for a given user.
18298     *
18299     * @param userId The device user for which to do a reset.
18300     */
18301    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18302        final int packageCount = mPackages.size();
18303        for (int i = 0; i < packageCount; i++) {
18304            PackageParser.Package pkg = mPackages.valueAt(i);
18305            PackageSetting ps = (PackageSetting) pkg.mExtras;
18306            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18307        }
18308    }
18309
18310    private void resetNetworkPolicies(int userId) {
18311        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18312    }
18313
18314    /**
18315     * Reverts user permission state changes (permissions and flags).
18316     *
18317     * @param ps The package for which to reset.
18318     * @param userId The device user for which to do a reset.
18319     */
18320    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18321            final PackageSetting ps, final int userId) {
18322        if (ps.pkg == null) {
18323            return;
18324        }
18325
18326        // These are flags that can change base on user actions.
18327        final int userSettableMask = FLAG_PERMISSION_USER_SET
18328                | FLAG_PERMISSION_USER_FIXED
18329                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18330                | FLAG_PERMISSION_REVIEW_REQUIRED;
18331
18332        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18333                | FLAG_PERMISSION_POLICY_FIXED;
18334
18335        boolean writeInstallPermissions = false;
18336        boolean writeRuntimePermissions = false;
18337
18338        final int permissionCount = ps.pkg.requestedPermissions.size();
18339        for (int i = 0; i < permissionCount; i++) {
18340            String permission = ps.pkg.requestedPermissions.get(i);
18341
18342            BasePermission bp = mSettings.mPermissions.get(permission);
18343            if (bp == null) {
18344                continue;
18345            }
18346
18347            // If shared user we just reset the state to which only this app contributed.
18348            if (ps.sharedUser != null) {
18349                boolean used = false;
18350                final int packageCount = ps.sharedUser.packages.size();
18351                for (int j = 0; j < packageCount; j++) {
18352                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18353                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18354                            && pkg.pkg.requestedPermissions.contains(permission)) {
18355                        used = true;
18356                        break;
18357                    }
18358                }
18359                if (used) {
18360                    continue;
18361                }
18362            }
18363
18364            PermissionsState permissionsState = ps.getPermissionsState();
18365
18366            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18367
18368            // Always clear the user settable flags.
18369            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18370                    bp.name) != null;
18371            // If permission review is enabled and this is a legacy app, mark the
18372            // permission as requiring a review as this is the initial state.
18373            int flags = 0;
18374            if (mPermissionReviewRequired
18375                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18376                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18377            }
18378            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18379                if (hasInstallState) {
18380                    writeInstallPermissions = true;
18381                } else {
18382                    writeRuntimePermissions = true;
18383                }
18384            }
18385
18386            // Below is only runtime permission handling.
18387            if (!bp.isRuntime()) {
18388                continue;
18389            }
18390
18391            // Never clobber system or policy.
18392            if ((oldFlags & policyOrSystemFlags) != 0) {
18393                continue;
18394            }
18395
18396            // If this permission was granted by default, make sure it is.
18397            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18398                if (permissionsState.grantRuntimePermission(bp, userId)
18399                        != PERMISSION_OPERATION_FAILURE) {
18400                    writeRuntimePermissions = true;
18401                }
18402            // If permission review is enabled the permissions for a legacy apps
18403            // are represented as constantly granted runtime ones, so don't revoke.
18404            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18405                // Otherwise, reset the permission.
18406                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18407                switch (revokeResult) {
18408                    case PERMISSION_OPERATION_SUCCESS:
18409                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18410                        writeRuntimePermissions = true;
18411                        final int appId = ps.appId;
18412                        mHandler.post(new Runnable() {
18413                            @Override
18414                            public void run() {
18415                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18416                            }
18417                        });
18418                    } break;
18419                }
18420            }
18421        }
18422
18423        // Synchronously write as we are taking permissions away.
18424        if (writeRuntimePermissions) {
18425            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18426        }
18427
18428        // Synchronously write as we are taking permissions away.
18429        if (writeInstallPermissions) {
18430            mSettings.writeLPr();
18431        }
18432    }
18433
18434    /**
18435     * Remove entries from the keystore daemon. Will only remove it if the
18436     * {@code appId} is valid.
18437     */
18438    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18439        if (appId < 0) {
18440            return;
18441        }
18442
18443        final KeyStore keyStore = KeyStore.getInstance();
18444        if (keyStore != null) {
18445            if (userId == UserHandle.USER_ALL) {
18446                for (final int individual : sUserManager.getUserIds()) {
18447                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18448                }
18449            } else {
18450                keyStore.clearUid(UserHandle.getUid(userId, appId));
18451            }
18452        } else {
18453            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18454        }
18455    }
18456
18457    @Override
18458    public void deleteApplicationCacheFiles(final String packageName,
18459            final IPackageDataObserver observer) {
18460        final int userId = UserHandle.getCallingUserId();
18461        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18462    }
18463
18464    @Override
18465    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18466            final IPackageDataObserver observer) {
18467        mContext.enforceCallingOrSelfPermission(
18468                android.Manifest.permission.DELETE_CACHE_FILES, null);
18469        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18470                /* requireFullPermission= */ true, /* checkShell= */ false,
18471                "delete application cache files");
18472
18473        final PackageParser.Package pkg;
18474        synchronized (mPackages) {
18475            pkg = mPackages.get(packageName);
18476        }
18477
18478        // Queue up an async operation since the package deletion may take a little while.
18479        mHandler.post(new Runnable() {
18480            public void run() {
18481                synchronized (mInstallLock) {
18482                    final int flags = StorageManager.FLAG_STORAGE_DE
18483                            | StorageManager.FLAG_STORAGE_CE;
18484                    // We're only clearing cache files, so we don't care if the
18485                    // app is unfrozen and still able to run
18486                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18487                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18488                }
18489                clearExternalStorageDataSync(packageName, userId, false);
18490                if (observer != null) {
18491                    try {
18492                        observer.onRemoveCompleted(packageName, true);
18493                    } catch (RemoteException e) {
18494                        Log.i(TAG, "Observer no longer exists.");
18495                    }
18496                }
18497            }
18498        });
18499    }
18500
18501    @Override
18502    public void getPackageSizeInfo(final String packageName, int userHandle,
18503            final IPackageStatsObserver observer) {
18504        mContext.enforceCallingOrSelfPermission(
18505                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18506        if (packageName == null) {
18507            throw new IllegalArgumentException("Attempt to get size of null packageName");
18508        }
18509
18510        PackageStats stats = new PackageStats(packageName, userHandle);
18511
18512        /*
18513         * Queue up an async operation since the package measurement may take a
18514         * little while.
18515         */
18516        Message msg = mHandler.obtainMessage(INIT_COPY);
18517        msg.obj = new MeasureParams(stats, observer);
18518        mHandler.sendMessage(msg);
18519    }
18520
18521    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18522        final PackageSetting ps;
18523        synchronized (mPackages) {
18524            ps = mSettings.mPackages.get(packageName);
18525            if (ps == null) {
18526                Slog.w(TAG, "Failed to find settings for " + packageName);
18527                return false;
18528            }
18529        }
18530
18531        final String[] packageNames = { packageName };
18532        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18533        final String[] codePaths = { ps.codePathString };
18534
18535        try {
18536            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18537                    ps.appId, ceDataInodes, codePaths, stats);
18538
18539            // For now, ignore code size of packages on system partition
18540            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18541                stats.codeSize = 0;
18542            }
18543
18544            // External clients expect these to be tracked separately
18545            stats.dataSize -= stats.cacheSize;
18546
18547        } catch (InstallerException e) {
18548            Slog.w(TAG, String.valueOf(e));
18549            return false;
18550        }
18551
18552        return true;
18553    }
18554
18555    private int getUidTargetSdkVersionLockedLPr(int uid) {
18556        Object obj = mSettings.getUserIdLPr(uid);
18557        if (obj instanceof SharedUserSetting) {
18558            final SharedUserSetting sus = (SharedUserSetting) obj;
18559            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18560            final Iterator<PackageSetting> it = sus.packages.iterator();
18561            while (it.hasNext()) {
18562                final PackageSetting ps = it.next();
18563                if (ps.pkg != null) {
18564                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18565                    if (v < vers) vers = v;
18566                }
18567            }
18568            return vers;
18569        } else if (obj instanceof PackageSetting) {
18570            final PackageSetting ps = (PackageSetting) obj;
18571            if (ps.pkg != null) {
18572                return ps.pkg.applicationInfo.targetSdkVersion;
18573            }
18574        }
18575        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18576    }
18577
18578    @Override
18579    public void addPreferredActivity(IntentFilter filter, int match,
18580            ComponentName[] set, ComponentName activity, int userId) {
18581        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18582                "Adding preferred");
18583    }
18584
18585    private void addPreferredActivityInternal(IntentFilter filter, int match,
18586            ComponentName[] set, ComponentName activity, boolean always, int userId,
18587            String opname) {
18588        // writer
18589        int callingUid = Binder.getCallingUid();
18590        enforceCrossUserPermission(callingUid, userId,
18591                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18592        if (filter.countActions() == 0) {
18593            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18594            return;
18595        }
18596        synchronized (mPackages) {
18597            if (mContext.checkCallingOrSelfPermission(
18598                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18599                    != PackageManager.PERMISSION_GRANTED) {
18600                if (getUidTargetSdkVersionLockedLPr(callingUid)
18601                        < Build.VERSION_CODES.FROYO) {
18602                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18603                            + callingUid);
18604                    return;
18605                }
18606                mContext.enforceCallingOrSelfPermission(
18607                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18608            }
18609
18610            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18611            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18612                    + userId + ":");
18613            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18614            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18615            scheduleWritePackageRestrictionsLocked(userId);
18616            postPreferredActivityChangedBroadcast(userId);
18617        }
18618    }
18619
18620    private void postPreferredActivityChangedBroadcast(int userId) {
18621        mHandler.post(() -> {
18622            final IActivityManager am = ActivityManager.getService();
18623            if (am == null) {
18624                return;
18625            }
18626
18627            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18628            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18629            try {
18630                am.broadcastIntent(null, intent, null, null,
18631                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18632                        null, false, false, userId);
18633            } catch (RemoteException e) {
18634            }
18635        });
18636    }
18637
18638    @Override
18639    public void replacePreferredActivity(IntentFilter filter, int match,
18640            ComponentName[] set, ComponentName activity, int userId) {
18641        if (filter.countActions() != 1) {
18642            throw new IllegalArgumentException(
18643                    "replacePreferredActivity expects filter to have only 1 action.");
18644        }
18645        if (filter.countDataAuthorities() != 0
18646                || filter.countDataPaths() != 0
18647                || filter.countDataSchemes() > 1
18648                || filter.countDataTypes() != 0) {
18649            throw new IllegalArgumentException(
18650                    "replacePreferredActivity expects filter to have no data authorities, " +
18651                    "paths, or types; and at most one scheme.");
18652        }
18653
18654        final int callingUid = Binder.getCallingUid();
18655        enforceCrossUserPermission(callingUid, userId,
18656                true /* requireFullPermission */, false /* checkShell */,
18657                "replace preferred activity");
18658        synchronized (mPackages) {
18659            if (mContext.checkCallingOrSelfPermission(
18660                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18661                    != PackageManager.PERMISSION_GRANTED) {
18662                if (getUidTargetSdkVersionLockedLPr(callingUid)
18663                        < Build.VERSION_CODES.FROYO) {
18664                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18665                            + Binder.getCallingUid());
18666                    return;
18667                }
18668                mContext.enforceCallingOrSelfPermission(
18669                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18670            }
18671
18672            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18673            if (pir != null) {
18674                // Get all of the existing entries that exactly match this filter.
18675                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18676                if (existing != null && existing.size() == 1) {
18677                    PreferredActivity cur = existing.get(0);
18678                    if (DEBUG_PREFERRED) {
18679                        Slog.i(TAG, "Checking replace of preferred:");
18680                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18681                        if (!cur.mPref.mAlways) {
18682                            Slog.i(TAG, "  -- CUR; not mAlways!");
18683                        } else {
18684                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18685                            Slog.i(TAG, "  -- CUR: mSet="
18686                                    + Arrays.toString(cur.mPref.mSetComponents));
18687                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18688                            Slog.i(TAG, "  -- NEW: mMatch="
18689                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18690                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18691                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18692                        }
18693                    }
18694                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18695                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18696                            && cur.mPref.sameSet(set)) {
18697                        // Setting the preferred activity to what it happens to be already
18698                        if (DEBUG_PREFERRED) {
18699                            Slog.i(TAG, "Replacing with same preferred activity "
18700                                    + cur.mPref.mShortComponent + " for user "
18701                                    + userId + ":");
18702                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18703                        }
18704                        return;
18705                    }
18706                }
18707
18708                if (existing != null) {
18709                    if (DEBUG_PREFERRED) {
18710                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18711                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18712                    }
18713                    for (int i = 0; i < existing.size(); i++) {
18714                        PreferredActivity pa = existing.get(i);
18715                        if (DEBUG_PREFERRED) {
18716                            Slog.i(TAG, "Removing existing preferred activity "
18717                                    + pa.mPref.mComponent + ":");
18718                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18719                        }
18720                        pir.removeFilter(pa);
18721                    }
18722                }
18723            }
18724            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18725                    "Replacing preferred");
18726        }
18727    }
18728
18729    @Override
18730    public void clearPackagePreferredActivities(String packageName) {
18731        final int uid = Binder.getCallingUid();
18732        // writer
18733        synchronized (mPackages) {
18734            PackageParser.Package pkg = mPackages.get(packageName);
18735            if (pkg == null || pkg.applicationInfo.uid != uid) {
18736                if (mContext.checkCallingOrSelfPermission(
18737                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18738                        != PackageManager.PERMISSION_GRANTED) {
18739                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18740                            < Build.VERSION_CODES.FROYO) {
18741                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18742                                + Binder.getCallingUid());
18743                        return;
18744                    }
18745                    mContext.enforceCallingOrSelfPermission(
18746                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18747                }
18748            }
18749
18750            int user = UserHandle.getCallingUserId();
18751            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18752                scheduleWritePackageRestrictionsLocked(user);
18753            }
18754        }
18755    }
18756
18757    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18758    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18759        ArrayList<PreferredActivity> removed = null;
18760        boolean changed = false;
18761        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18762            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18763            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18764            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18765                continue;
18766            }
18767            Iterator<PreferredActivity> it = pir.filterIterator();
18768            while (it.hasNext()) {
18769                PreferredActivity pa = it.next();
18770                // Mark entry for removal only if it matches the package name
18771                // and the entry is of type "always".
18772                if (packageName == null ||
18773                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18774                                && pa.mPref.mAlways)) {
18775                    if (removed == null) {
18776                        removed = new ArrayList<PreferredActivity>();
18777                    }
18778                    removed.add(pa);
18779                }
18780            }
18781            if (removed != null) {
18782                for (int j=0; j<removed.size(); j++) {
18783                    PreferredActivity pa = removed.get(j);
18784                    pir.removeFilter(pa);
18785                }
18786                changed = true;
18787            }
18788        }
18789        if (changed) {
18790            postPreferredActivityChangedBroadcast(userId);
18791        }
18792        return changed;
18793    }
18794
18795    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18796    private void clearIntentFilterVerificationsLPw(int userId) {
18797        final int packageCount = mPackages.size();
18798        for (int i = 0; i < packageCount; i++) {
18799            PackageParser.Package pkg = mPackages.valueAt(i);
18800            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18801        }
18802    }
18803
18804    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18805    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18806        if (userId == UserHandle.USER_ALL) {
18807            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18808                    sUserManager.getUserIds())) {
18809                for (int oneUserId : sUserManager.getUserIds()) {
18810                    scheduleWritePackageRestrictionsLocked(oneUserId);
18811                }
18812            }
18813        } else {
18814            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18815                scheduleWritePackageRestrictionsLocked(userId);
18816            }
18817        }
18818    }
18819
18820    void clearDefaultBrowserIfNeeded(String packageName) {
18821        for (int oneUserId : sUserManager.getUserIds()) {
18822            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18823            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18824            if (packageName.equals(defaultBrowserPackageName)) {
18825                setDefaultBrowserPackageName(null, oneUserId);
18826            }
18827        }
18828    }
18829
18830    @Override
18831    public void resetApplicationPreferences(int userId) {
18832        mContext.enforceCallingOrSelfPermission(
18833                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18834        final long identity = Binder.clearCallingIdentity();
18835        // writer
18836        try {
18837            synchronized (mPackages) {
18838                clearPackagePreferredActivitiesLPw(null, userId);
18839                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18840                // TODO: We have to reset the default SMS and Phone. This requires
18841                // significant refactoring to keep all default apps in the package
18842                // manager (cleaner but more work) or have the services provide
18843                // callbacks to the package manager to request a default app reset.
18844                applyFactoryDefaultBrowserLPw(userId);
18845                clearIntentFilterVerificationsLPw(userId);
18846                primeDomainVerificationsLPw(userId);
18847                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18848                scheduleWritePackageRestrictionsLocked(userId);
18849            }
18850            resetNetworkPolicies(userId);
18851        } finally {
18852            Binder.restoreCallingIdentity(identity);
18853        }
18854    }
18855
18856    @Override
18857    public int getPreferredActivities(List<IntentFilter> outFilters,
18858            List<ComponentName> outActivities, String packageName) {
18859
18860        int num = 0;
18861        final int userId = UserHandle.getCallingUserId();
18862        // reader
18863        synchronized (mPackages) {
18864            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18865            if (pir != null) {
18866                final Iterator<PreferredActivity> it = pir.filterIterator();
18867                while (it.hasNext()) {
18868                    final PreferredActivity pa = it.next();
18869                    if (packageName == null
18870                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18871                                    && pa.mPref.mAlways)) {
18872                        if (outFilters != null) {
18873                            outFilters.add(new IntentFilter(pa));
18874                        }
18875                        if (outActivities != null) {
18876                            outActivities.add(pa.mPref.mComponent);
18877                        }
18878                    }
18879                }
18880            }
18881        }
18882
18883        return num;
18884    }
18885
18886    @Override
18887    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18888            int userId) {
18889        int callingUid = Binder.getCallingUid();
18890        if (callingUid != Process.SYSTEM_UID) {
18891            throw new SecurityException(
18892                    "addPersistentPreferredActivity can only be run by the system");
18893        }
18894        if (filter.countActions() == 0) {
18895            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18896            return;
18897        }
18898        synchronized (mPackages) {
18899            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18900                    ":");
18901            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18902            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18903                    new PersistentPreferredActivity(filter, activity));
18904            scheduleWritePackageRestrictionsLocked(userId);
18905            postPreferredActivityChangedBroadcast(userId);
18906        }
18907    }
18908
18909    @Override
18910    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18911        int callingUid = Binder.getCallingUid();
18912        if (callingUid != Process.SYSTEM_UID) {
18913            throw new SecurityException(
18914                    "clearPackagePersistentPreferredActivities can only be run by the system");
18915        }
18916        ArrayList<PersistentPreferredActivity> removed = null;
18917        boolean changed = false;
18918        synchronized (mPackages) {
18919            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18920                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18921                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18922                        .valueAt(i);
18923                if (userId != thisUserId) {
18924                    continue;
18925                }
18926                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18927                while (it.hasNext()) {
18928                    PersistentPreferredActivity ppa = it.next();
18929                    // Mark entry for removal only if it matches the package name.
18930                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18931                        if (removed == null) {
18932                            removed = new ArrayList<PersistentPreferredActivity>();
18933                        }
18934                        removed.add(ppa);
18935                    }
18936                }
18937                if (removed != null) {
18938                    for (int j=0; j<removed.size(); j++) {
18939                        PersistentPreferredActivity ppa = removed.get(j);
18940                        ppir.removeFilter(ppa);
18941                    }
18942                    changed = true;
18943                }
18944            }
18945
18946            if (changed) {
18947                scheduleWritePackageRestrictionsLocked(userId);
18948                postPreferredActivityChangedBroadcast(userId);
18949            }
18950        }
18951    }
18952
18953    /**
18954     * Common machinery for picking apart a restored XML blob and passing
18955     * it to a caller-supplied functor to be applied to the running system.
18956     */
18957    private void restoreFromXml(XmlPullParser parser, int userId,
18958            String expectedStartTag, BlobXmlRestorer functor)
18959            throws IOException, XmlPullParserException {
18960        int type;
18961        while ((type = parser.next()) != XmlPullParser.START_TAG
18962                && type != XmlPullParser.END_DOCUMENT) {
18963        }
18964        if (type != XmlPullParser.START_TAG) {
18965            // oops didn't find a start tag?!
18966            if (DEBUG_BACKUP) {
18967                Slog.e(TAG, "Didn't find start tag during restore");
18968            }
18969            return;
18970        }
18971Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18972        // this is supposed to be TAG_PREFERRED_BACKUP
18973        if (!expectedStartTag.equals(parser.getName())) {
18974            if (DEBUG_BACKUP) {
18975                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18976            }
18977            return;
18978        }
18979
18980        // skip interfering stuff, then we're aligned with the backing implementation
18981        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18982Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18983        functor.apply(parser, userId);
18984    }
18985
18986    private interface BlobXmlRestorer {
18987        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18988    }
18989
18990    /**
18991     * Non-Binder method, support for the backup/restore mechanism: write the
18992     * full set of preferred activities in its canonical XML format.  Returns the
18993     * XML output as a byte array, or null if there is none.
18994     */
18995    @Override
18996    public byte[] getPreferredActivityBackup(int userId) {
18997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18998            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18999        }
19000
19001        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19002        try {
19003            final XmlSerializer serializer = new FastXmlSerializer();
19004            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19005            serializer.startDocument(null, true);
19006            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19007
19008            synchronized (mPackages) {
19009                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19010            }
19011
19012            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19013            serializer.endDocument();
19014            serializer.flush();
19015        } catch (Exception e) {
19016            if (DEBUG_BACKUP) {
19017                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19018            }
19019            return null;
19020        }
19021
19022        return dataStream.toByteArray();
19023    }
19024
19025    @Override
19026    public void restorePreferredActivities(byte[] backup, int userId) {
19027        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19028            throw new SecurityException("Only the system may call restorePreferredActivities()");
19029        }
19030
19031        try {
19032            final XmlPullParser parser = Xml.newPullParser();
19033            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19034            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19035                    new BlobXmlRestorer() {
19036                        @Override
19037                        public void apply(XmlPullParser parser, int userId)
19038                                throws XmlPullParserException, IOException {
19039                            synchronized (mPackages) {
19040                                mSettings.readPreferredActivitiesLPw(parser, userId);
19041                            }
19042                        }
19043                    } );
19044        } catch (Exception e) {
19045            if (DEBUG_BACKUP) {
19046                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19047            }
19048        }
19049    }
19050
19051    /**
19052     * Non-Binder method, support for the backup/restore mechanism: write the
19053     * default browser (etc) settings in its canonical XML format.  Returns the default
19054     * browser XML representation as a byte array, or null if there is none.
19055     */
19056    @Override
19057    public byte[] getDefaultAppsBackup(int userId) {
19058        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19059            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19060        }
19061
19062        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19063        try {
19064            final XmlSerializer serializer = new FastXmlSerializer();
19065            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19066            serializer.startDocument(null, true);
19067            serializer.startTag(null, TAG_DEFAULT_APPS);
19068
19069            synchronized (mPackages) {
19070                mSettings.writeDefaultAppsLPr(serializer, userId);
19071            }
19072
19073            serializer.endTag(null, TAG_DEFAULT_APPS);
19074            serializer.endDocument();
19075            serializer.flush();
19076        } catch (Exception e) {
19077            if (DEBUG_BACKUP) {
19078                Slog.e(TAG, "Unable to write default apps for backup", e);
19079            }
19080            return null;
19081        }
19082
19083        return dataStream.toByteArray();
19084    }
19085
19086    @Override
19087    public void restoreDefaultApps(byte[] backup, int userId) {
19088        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19089            throw new SecurityException("Only the system may call restoreDefaultApps()");
19090        }
19091
19092        try {
19093            final XmlPullParser parser = Xml.newPullParser();
19094            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19095            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19096                    new BlobXmlRestorer() {
19097                        @Override
19098                        public void apply(XmlPullParser parser, int userId)
19099                                throws XmlPullParserException, IOException {
19100                            synchronized (mPackages) {
19101                                mSettings.readDefaultAppsLPw(parser, userId);
19102                            }
19103                        }
19104                    } );
19105        } catch (Exception e) {
19106            if (DEBUG_BACKUP) {
19107                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19108            }
19109        }
19110    }
19111
19112    @Override
19113    public byte[] getIntentFilterVerificationBackup(int userId) {
19114        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19115            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19116        }
19117
19118        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19119        try {
19120            final XmlSerializer serializer = new FastXmlSerializer();
19121            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19122            serializer.startDocument(null, true);
19123            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19124
19125            synchronized (mPackages) {
19126                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19127            }
19128
19129            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19130            serializer.endDocument();
19131            serializer.flush();
19132        } catch (Exception e) {
19133            if (DEBUG_BACKUP) {
19134                Slog.e(TAG, "Unable to write default apps for backup", e);
19135            }
19136            return null;
19137        }
19138
19139        return dataStream.toByteArray();
19140    }
19141
19142    @Override
19143    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19144        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19145            throw new SecurityException("Only the system may call restorePreferredActivities()");
19146        }
19147
19148        try {
19149            final XmlPullParser parser = Xml.newPullParser();
19150            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19151            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19152                    new BlobXmlRestorer() {
19153                        @Override
19154                        public void apply(XmlPullParser parser, int userId)
19155                                throws XmlPullParserException, IOException {
19156                            synchronized (mPackages) {
19157                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19158                                mSettings.writeLPr();
19159                            }
19160                        }
19161                    } );
19162        } catch (Exception e) {
19163            if (DEBUG_BACKUP) {
19164                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19165            }
19166        }
19167    }
19168
19169    @Override
19170    public byte[] getPermissionGrantBackup(int userId) {
19171        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19172            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19173        }
19174
19175        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19176        try {
19177            final XmlSerializer serializer = new FastXmlSerializer();
19178            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19179            serializer.startDocument(null, true);
19180            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19181
19182            synchronized (mPackages) {
19183                serializeRuntimePermissionGrantsLPr(serializer, userId);
19184            }
19185
19186            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19187            serializer.endDocument();
19188            serializer.flush();
19189        } catch (Exception e) {
19190            if (DEBUG_BACKUP) {
19191                Slog.e(TAG, "Unable to write default apps for backup", e);
19192            }
19193            return null;
19194        }
19195
19196        return dataStream.toByteArray();
19197    }
19198
19199    @Override
19200    public void restorePermissionGrants(byte[] backup, int userId) {
19201        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19202            throw new SecurityException("Only the system may call restorePermissionGrants()");
19203        }
19204
19205        try {
19206            final XmlPullParser parser = Xml.newPullParser();
19207            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19208            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19209                    new BlobXmlRestorer() {
19210                        @Override
19211                        public void apply(XmlPullParser parser, int userId)
19212                                throws XmlPullParserException, IOException {
19213                            synchronized (mPackages) {
19214                                processRestoredPermissionGrantsLPr(parser, userId);
19215                            }
19216                        }
19217                    } );
19218        } catch (Exception e) {
19219            if (DEBUG_BACKUP) {
19220                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19221            }
19222        }
19223    }
19224
19225    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19226            throws IOException {
19227        serializer.startTag(null, TAG_ALL_GRANTS);
19228
19229        final int N = mSettings.mPackages.size();
19230        for (int i = 0; i < N; i++) {
19231            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19232            boolean pkgGrantsKnown = false;
19233
19234            PermissionsState packagePerms = ps.getPermissionsState();
19235
19236            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19237                final int grantFlags = state.getFlags();
19238                // only look at grants that are not system/policy fixed
19239                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19240                    final boolean isGranted = state.isGranted();
19241                    // And only back up the user-twiddled state bits
19242                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19243                        final String packageName = mSettings.mPackages.keyAt(i);
19244                        if (!pkgGrantsKnown) {
19245                            serializer.startTag(null, TAG_GRANT);
19246                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19247                            pkgGrantsKnown = true;
19248                        }
19249
19250                        final boolean userSet =
19251                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19252                        final boolean userFixed =
19253                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19254                        final boolean revoke =
19255                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19256
19257                        serializer.startTag(null, TAG_PERMISSION);
19258                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19259                        if (isGranted) {
19260                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19261                        }
19262                        if (userSet) {
19263                            serializer.attribute(null, ATTR_USER_SET, "true");
19264                        }
19265                        if (userFixed) {
19266                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19267                        }
19268                        if (revoke) {
19269                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19270                        }
19271                        serializer.endTag(null, TAG_PERMISSION);
19272                    }
19273                }
19274            }
19275
19276            if (pkgGrantsKnown) {
19277                serializer.endTag(null, TAG_GRANT);
19278            }
19279        }
19280
19281        serializer.endTag(null, TAG_ALL_GRANTS);
19282    }
19283
19284    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19285            throws XmlPullParserException, IOException {
19286        String pkgName = null;
19287        int outerDepth = parser.getDepth();
19288        int type;
19289        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19290                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19291            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19292                continue;
19293            }
19294
19295            final String tagName = parser.getName();
19296            if (tagName.equals(TAG_GRANT)) {
19297                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19298                if (DEBUG_BACKUP) {
19299                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19300                }
19301            } else if (tagName.equals(TAG_PERMISSION)) {
19302
19303                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19304                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19305
19306                int newFlagSet = 0;
19307                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19308                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19309                }
19310                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19311                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19312                }
19313                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19314                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19315                }
19316                if (DEBUG_BACKUP) {
19317                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19318                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19319                }
19320                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19321                if (ps != null) {
19322                    // Already installed so we apply the grant immediately
19323                    if (DEBUG_BACKUP) {
19324                        Slog.v(TAG, "        + already installed; applying");
19325                    }
19326                    PermissionsState perms = ps.getPermissionsState();
19327                    BasePermission bp = mSettings.mPermissions.get(permName);
19328                    if (bp != null) {
19329                        if (isGranted) {
19330                            perms.grantRuntimePermission(bp, userId);
19331                        }
19332                        if (newFlagSet != 0) {
19333                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19334                        }
19335                    }
19336                } else {
19337                    // Need to wait for post-restore install to apply the grant
19338                    if (DEBUG_BACKUP) {
19339                        Slog.v(TAG, "        - not yet installed; saving for later");
19340                    }
19341                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19342                            isGranted, newFlagSet, userId);
19343                }
19344            } else {
19345                PackageManagerService.reportSettingsProblem(Log.WARN,
19346                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19347                XmlUtils.skipCurrentTag(parser);
19348            }
19349        }
19350
19351        scheduleWriteSettingsLocked();
19352        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19353    }
19354
19355    @Override
19356    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19357            int sourceUserId, int targetUserId, int flags) {
19358        mContext.enforceCallingOrSelfPermission(
19359                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19360        int callingUid = Binder.getCallingUid();
19361        enforceOwnerRights(ownerPackage, callingUid);
19362        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19363        if (intentFilter.countActions() == 0) {
19364            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19365            return;
19366        }
19367        synchronized (mPackages) {
19368            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19369                    ownerPackage, targetUserId, flags);
19370            CrossProfileIntentResolver resolver =
19371                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19372            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19373            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19374            if (existing != null) {
19375                int size = existing.size();
19376                for (int i = 0; i < size; i++) {
19377                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19378                        return;
19379                    }
19380                }
19381            }
19382            resolver.addFilter(newFilter);
19383            scheduleWritePackageRestrictionsLocked(sourceUserId);
19384        }
19385    }
19386
19387    @Override
19388    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19389        mContext.enforceCallingOrSelfPermission(
19390                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19391        int callingUid = Binder.getCallingUid();
19392        enforceOwnerRights(ownerPackage, callingUid);
19393        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19394        synchronized (mPackages) {
19395            CrossProfileIntentResolver resolver =
19396                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19397            ArraySet<CrossProfileIntentFilter> set =
19398                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19399            for (CrossProfileIntentFilter filter : set) {
19400                if (filter.getOwnerPackage().equals(ownerPackage)) {
19401                    resolver.removeFilter(filter);
19402                }
19403            }
19404            scheduleWritePackageRestrictionsLocked(sourceUserId);
19405        }
19406    }
19407
19408    // Enforcing that callingUid is owning pkg on userId
19409    private void enforceOwnerRights(String pkg, int callingUid) {
19410        // The system owns everything.
19411        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19412            return;
19413        }
19414        int callingUserId = UserHandle.getUserId(callingUid);
19415        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19416        if (pi == null) {
19417            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19418                    + callingUserId);
19419        }
19420        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19421            throw new SecurityException("Calling uid " + callingUid
19422                    + " does not own package " + pkg);
19423        }
19424    }
19425
19426    @Override
19427    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19428        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19429    }
19430
19431    private Intent getHomeIntent() {
19432        Intent intent = new Intent(Intent.ACTION_MAIN);
19433        intent.addCategory(Intent.CATEGORY_HOME);
19434        intent.addCategory(Intent.CATEGORY_DEFAULT);
19435        return intent;
19436    }
19437
19438    private IntentFilter getHomeFilter() {
19439        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19440        filter.addCategory(Intent.CATEGORY_HOME);
19441        filter.addCategory(Intent.CATEGORY_DEFAULT);
19442        return filter;
19443    }
19444
19445    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19446            int userId) {
19447        Intent intent  = getHomeIntent();
19448        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19449                PackageManager.GET_META_DATA, userId);
19450        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19451                true, false, false, userId);
19452
19453        allHomeCandidates.clear();
19454        if (list != null) {
19455            for (ResolveInfo ri : list) {
19456                allHomeCandidates.add(ri);
19457            }
19458        }
19459        return (preferred == null || preferred.activityInfo == null)
19460                ? null
19461                : new ComponentName(preferred.activityInfo.packageName,
19462                        preferred.activityInfo.name);
19463    }
19464
19465    @Override
19466    public void setHomeActivity(ComponentName comp, int userId) {
19467        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19468        getHomeActivitiesAsUser(homeActivities, userId);
19469
19470        boolean found = false;
19471
19472        final int size = homeActivities.size();
19473        final ComponentName[] set = new ComponentName[size];
19474        for (int i = 0; i < size; i++) {
19475            final ResolveInfo candidate = homeActivities.get(i);
19476            final ActivityInfo info = candidate.activityInfo;
19477            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19478            set[i] = activityName;
19479            if (!found && activityName.equals(comp)) {
19480                found = true;
19481            }
19482        }
19483        if (!found) {
19484            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19485                    + userId);
19486        }
19487        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19488                set, comp, userId);
19489    }
19490
19491    private @Nullable String getSetupWizardPackageName() {
19492        final Intent intent = new Intent(Intent.ACTION_MAIN);
19493        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19494
19495        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19496                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19497                        | MATCH_DISABLED_COMPONENTS,
19498                UserHandle.myUserId());
19499        if (matches.size() == 1) {
19500            return matches.get(0).getComponentInfo().packageName;
19501        } else {
19502            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19503                    + ": matches=" + matches);
19504            return null;
19505        }
19506    }
19507
19508    private @Nullable String getStorageManagerPackageName() {
19509        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19510
19511        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19512                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19513                        | MATCH_DISABLED_COMPONENTS,
19514                UserHandle.myUserId());
19515        if (matches.size() == 1) {
19516            return matches.get(0).getComponentInfo().packageName;
19517        } else {
19518            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19519                    + matches.size() + ": matches=" + matches);
19520            return null;
19521        }
19522    }
19523
19524    @Override
19525    public void setApplicationEnabledSetting(String appPackageName,
19526            int newState, int flags, int userId, String callingPackage) {
19527        if (!sUserManager.exists(userId)) return;
19528        if (callingPackage == null) {
19529            callingPackage = Integer.toString(Binder.getCallingUid());
19530        }
19531        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19532    }
19533
19534    @Override
19535    public void setComponentEnabledSetting(ComponentName componentName,
19536            int newState, int flags, int userId) {
19537        if (!sUserManager.exists(userId)) return;
19538        setEnabledSetting(componentName.getPackageName(),
19539                componentName.getClassName(), newState, flags, userId, null);
19540    }
19541
19542    private void setEnabledSetting(final String packageName, String className, int newState,
19543            final int flags, int userId, String callingPackage) {
19544        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19545              || newState == COMPONENT_ENABLED_STATE_ENABLED
19546              || newState == COMPONENT_ENABLED_STATE_DISABLED
19547              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19548              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19549            throw new IllegalArgumentException("Invalid new component state: "
19550                    + newState);
19551        }
19552        PackageSetting pkgSetting;
19553        final int uid = Binder.getCallingUid();
19554        final int permission;
19555        if (uid == Process.SYSTEM_UID) {
19556            permission = PackageManager.PERMISSION_GRANTED;
19557        } else {
19558            permission = mContext.checkCallingOrSelfPermission(
19559                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19560        }
19561        enforceCrossUserPermission(uid, userId,
19562                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19563        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19564        boolean sendNow = false;
19565        boolean isApp = (className == null);
19566        String componentName = isApp ? packageName : className;
19567        int packageUid = -1;
19568        ArrayList<String> components;
19569
19570        // writer
19571        synchronized (mPackages) {
19572            pkgSetting = mSettings.mPackages.get(packageName);
19573            if (pkgSetting == null) {
19574                if (className == null) {
19575                    throw new IllegalArgumentException("Unknown package: " + packageName);
19576                }
19577                throw new IllegalArgumentException(
19578                        "Unknown component: " + packageName + "/" + className);
19579            }
19580        }
19581
19582        // Limit who can change which apps
19583        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19584            // Don't allow apps that don't have permission to modify other apps
19585            if (!allowedByPermission) {
19586                throw new SecurityException(
19587                        "Permission Denial: attempt to change component state from pid="
19588                        + Binder.getCallingPid()
19589                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19590            }
19591            // Don't allow changing protected packages.
19592            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19593                throw new SecurityException("Cannot disable a protected package: " + packageName);
19594            }
19595        }
19596
19597        synchronized (mPackages) {
19598            if (uid == Process.SHELL_UID
19599                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19600                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19601                // unless it is a test package.
19602                int oldState = pkgSetting.getEnabled(userId);
19603                if (className == null
19604                    &&
19605                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19606                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19607                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19608                    &&
19609                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19610                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19611                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19612                    // ok
19613                } else {
19614                    throw new SecurityException(
19615                            "Shell cannot change component state for " + packageName + "/"
19616                            + className + " to " + newState);
19617                }
19618            }
19619            if (className == null) {
19620                // We're dealing with an application/package level state change
19621                if (pkgSetting.getEnabled(userId) == newState) {
19622                    // Nothing to do
19623                    return;
19624                }
19625                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19626                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19627                    // Don't care about who enables an app.
19628                    callingPackage = null;
19629                }
19630                pkgSetting.setEnabled(newState, userId, callingPackage);
19631                // pkgSetting.pkg.mSetEnabled = newState;
19632            } else {
19633                // We're dealing with a component level state change
19634                // First, verify that this is a valid class name.
19635                PackageParser.Package pkg = pkgSetting.pkg;
19636                if (pkg == null || !pkg.hasComponentClassName(className)) {
19637                    if (pkg != null &&
19638                            pkg.applicationInfo.targetSdkVersion >=
19639                                    Build.VERSION_CODES.JELLY_BEAN) {
19640                        throw new IllegalArgumentException("Component class " + className
19641                                + " does not exist in " + packageName);
19642                    } else {
19643                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19644                                + className + " does not exist in " + packageName);
19645                    }
19646                }
19647                switch (newState) {
19648                case COMPONENT_ENABLED_STATE_ENABLED:
19649                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19650                        return;
19651                    }
19652                    break;
19653                case COMPONENT_ENABLED_STATE_DISABLED:
19654                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19655                        return;
19656                    }
19657                    break;
19658                case COMPONENT_ENABLED_STATE_DEFAULT:
19659                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19660                        return;
19661                    }
19662                    break;
19663                default:
19664                    Slog.e(TAG, "Invalid new component state: " + newState);
19665                    return;
19666                }
19667            }
19668            scheduleWritePackageRestrictionsLocked(userId);
19669            components = mPendingBroadcasts.get(userId, packageName);
19670            final boolean newPackage = components == null;
19671            if (newPackage) {
19672                components = new ArrayList<String>();
19673            }
19674            if (!components.contains(componentName)) {
19675                components.add(componentName);
19676            }
19677            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19678                sendNow = true;
19679                // Purge entry from pending broadcast list if another one exists already
19680                // since we are sending one right away.
19681                mPendingBroadcasts.remove(userId, packageName);
19682            } else {
19683                if (newPackage) {
19684                    mPendingBroadcasts.put(userId, packageName, components);
19685                }
19686                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19687                    // Schedule a message
19688                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19689                }
19690            }
19691        }
19692
19693        long callingId = Binder.clearCallingIdentity();
19694        try {
19695            if (sendNow) {
19696                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19697                sendPackageChangedBroadcast(packageName,
19698                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19699            }
19700        } finally {
19701            Binder.restoreCallingIdentity(callingId);
19702        }
19703    }
19704
19705    @Override
19706    public void flushPackageRestrictionsAsUser(int userId) {
19707        if (!sUserManager.exists(userId)) {
19708            return;
19709        }
19710        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19711                false /* checkShell */, "flushPackageRestrictions");
19712        synchronized (mPackages) {
19713            mSettings.writePackageRestrictionsLPr(userId);
19714            mDirtyUsers.remove(userId);
19715            if (mDirtyUsers.isEmpty()) {
19716                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19717            }
19718        }
19719    }
19720
19721    private void sendPackageChangedBroadcast(String packageName,
19722            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19723        if (DEBUG_INSTALL)
19724            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19725                    + componentNames);
19726        Bundle extras = new Bundle(4);
19727        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19728        String nameList[] = new String[componentNames.size()];
19729        componentNames.toArray(nameList);
19730        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19731        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19732        extras.putInt(Intent.EXTRA_UID, packageUid);
19733        // If this is not reporting a change of the overall package, then only send it
19734        // to registered receivers.  We don't want to launch a swath of apps for every
19735        // little component state change.
19736        final int flags = !componentNames.contains(packageName)
19737                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19738        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19739                new int[] {UserHandle.getUserId(packageUid)});
19740    }
19741
19742    @Override
19743    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19744        if (!sUserManager.exists(userId)) return;
19745        final int uid = Binder.getCallingUid();
19746        final int permission = mContext.checkCallingOrSelfPermission(
19747                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19748        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19749        enforceCrossUserPermission(uid, userId,
19750                true /* requireFullPermission */, true /* checkShell */, "stop package");
19751        // writer
19752        synchronized (mPackages) {
19753            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19754                    allowedByPermission, uid, userId)) {
19755                scheduleWritePackageRestrictionsLocked(userId);
19756            }
19757        }
19758    }
19759
19760    @Override
19761    public String getInstallerPackageName(String packageName) {
19762        // reader
19763        synchronized (mPackages) {
19764            return mSettings.getInstallerPackageNameLPr(packageName);
19765        }
19766    }
19767
19768    public boolean isOrphaned(String packageName) {
19769        // reader
19770        synchronized (mPackages) {
19771            return mSettings.isOrphaned(packageName);
19772        }
19773    }
19774
19775    @Override
19776    public int getApplicationEnabledSetting(String packageName, int userId) {
19777        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19778        int uid = Binder.getCallingUid();
19779        enforceCrossUserPermission(uid, userId,
19780                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19781        // reader
19782        synchronized (mPackages) {
19783            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19784        }
19785    }
19786
19787    @Override
19788    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19789        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19790        int uid = Binder.getCallingUid();
19791        enforceCrossUserPermission(uid, userId,
19792                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19793        // reader
19794        synchronized (mPackages) {
19795            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19796        }
19797    }
19798
19799    @Override
19800    public void enterSafeMode() {
19801        enforceSystemOrRoot("Only the system can request entering safe mode");
19802
19803        if (!mSystemReady) {
19804            mSafeMode = true;
19805        }
19806    }
19807
19808    @Override
19809    public void systemReady() {
19810        mSystemReady = true;
19811
19812        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19813        // disabled after already being started.
19814        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19815                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19816
19817        // Read the compatibilty setting when the system is ready.
19818        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19819                mContext.getContentResolver(),
19820                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19821        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19822        if (DEBUG_SETTINGS) {
19823            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19824        }
19825
19826        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19827
19828        synchronized (mPackages) {
19829            // Verify that all of the preferred activity components actually
19830            // exist.  It is possible for applications to be updated and at
19831            // that point remove a previously declared activity component that
19832            // had been set as a preferred activity.  We try to clean this up
19833            // the next time we encounter that preferred activity, but it is
19834            // possible for the user flow to never be able to return to that
19835            // situation so here we do a sanity check to make sure we haven't
19836            // left any junk around.
19837            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19838            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19839                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19840                removed.clear();
19841                for (PreferredActivity pa : pir.filterSet()) {
19842                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19843                        removed.add(pa);
19844                    }
19845                }
19846                if (removed.size() > 0) {
19847                    for (int r=0; r<removed.size(); r++) {
19848                        PreferredActivity pa = removed.get(r);
19849                        Slog.w(TAG, "Removing dangling preferred activity: "
19850                                + pa.mPref.mComponent);
19851                        pir.removeFilter(pa);
19852                    }
19853                    mSettings.writePackageRestrictionsLPr(
19854                            mSettings.mPreferredActivities.keyAt(i));
19855                }
19856            }
19857
19858            for (int userId : UserManagerService.getInstance().getUserIds()) {
19859                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19860                    grantPermissionsUserIds = ArrayUtils.appendInt(
19861                            grantPermissionsUserIds, userId);
19862                }
19863            }
19864        }
19865        sUserManager.systemReady();
19866
19867        // If we upgraded grant all default permissions before kicking off.
19868        for (int userId : grantPermissionsUserIds) {
19869            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19870        }
19871
19872        // If we did not grant default permissions, we preload from this the
19873        // default permission exceptions lazily to ensure we don't hit the
19874        // disk on a new user creation.
19875        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19876            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19877        }
19878
19879        // Kick off any messages waiting for system ready
19880        if (mPostSystemReadyMessages != null) {
19881            for (Message msg : mPostSystemReadyMessages) {
19882                msg.sendToTarget();
19883            }
19884            mPostSystemReadyMessages = null;
19885        }
19886
19887        // Watch for external volumes that come and go over time
19888        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19889        storage.registerListener(mStorageListener);
19890
19891        mInstallerService.systemReady();
19892        mPackageDexOptimizer.systemReady();
19893
19894        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19895                StorageManagerInternal.class);
19896        StorageManagerInternal.addExternalStoragePolicy(
19897                new StorageManagerInternal.ExternalStorageMountPolicy() {
19898            @Override
19899            public int getMountMode(int uid, String packageName) {
19900                if (Process.isIsolated(uid)) {
19901                    return Zygote.MOUNT_EXTERNAL_NONE;
19902                }
19903                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19904                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19905                }
19906                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19907                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19908                }
19909                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19910                    return Zygote.MOUNT_EXTERNAL_READ;
19911                }
19912                return Zygote.MOUNT_EXTERNAL_WRITE;
19913            }
19914
19915            @Override
19916            public boolean hasExternalStorage(int uid, String packageName) {
19917                return true;
19918            }
19919        });
19920
19921        // Now that we're mostly running, clean up stale users and apps
19922        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19923        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19924    }
19925
19926    @Override
19927    public boolean isSafeMode() {
19928        return mSafeMode;
19929    }
19930
19931    @Override
19932    public boolean hasSystemUidErrors() {
19933        return mHasSystemUidErrors;
19934    }
19935
19936    static String arrayToString(int[] array) {
19937        StringBuffer buf = new StringBuffer(128);
19938        buf.append('[');
19939        if (array != null) {
19940            for (int i=0; i<array.length; i++) {
19941                if (i > 0) buf.append(", ");
19942                buf.append(array[i]);
19943            }
19944        }
19945        buf.append(']');
19946        return buf.toString();
19947    }
19948
19949    static class DumpState {
19950        public static final int DUMP_LIBS = 1 << 0;
19951        public static final int DUMP_FEATURES = 1 << 1;
19952        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19953        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19954        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19955        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19956        public static final int DUMP_PERMISSIONS = 1 << 6;
19957        public static final int DUMP_PACKAGES = 1 << 7;
19958        public static final int DUMP_SHARED_USERS = 1 << 8;
19959        public static final int DUMP_MESSAGES = 1 << 9;
19960        public static final int DUMP_PROVIDERS = 1 << 10;
19961        public static final int DUMP_VERIFIERS = 1 << 11;
19962        public static final int DUMP_PREFERRED = 1 << 12;
19963        public static final int DUMP_PREFERRED_XML = 1 << 13;
19964        public static final int DUMP_KEYSETS = 1 << 14;
19965        public static final int DUMP_VERSION = 1 << 15;
19966        public static final int DUMP_INSTALLS = 1 << 16;
19967        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19968        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19969        public static final int DUMP_FROZEN = 1 << 19;
19970        public static final int DUMP_DEXOPT = 1 << 20;
19971        public static final int DUMP_COMPILER_STATS = 1 << 21;
19972
19973        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19974
19975        private int mTypes;
19976
19977        private int mOptions;
19978
19979        private boolean mTitlePrinted;
19980
19981        private SharedUserSetting mSharedUser;
19982
19983        public boolean isDumping(int type) {
19984            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19985                return true;
19986            }
19987
19988            return (mTypes & type) != 0;
19989        }
19990
19991        public void setDump(int type) {
19992            mTypes |= type;
19993        }
19994
19995        public boolean isOptionEnabled(int option) {
19996            return (mOptions & option) != 0;
19997        }
19998
19999        public void setOptionEnabled(int option) {
20000            mOptions |= option;
20001        }
20002
20003        public boolean onTitlePrinted() {
20004            final boolean printed = mTitlePrinted;
20005            mTitlePrinted = true;
20006            return printed;
20007        }
20008
20009        public boolean getTitlePrinted() {
20010            return mTitlePrinted;
20011        }
20012
20013        public void setTitlePrinted(boolean enabled) {
20014            mTitlePrinted = enabled;
20015        }
20016
20017        public SharedUserSetting getSharedUser() {
20018            return mSharedUser;
20019        }
20020
20021        public void setSharedUser(SharedUserSetting user) {
20022            mSharedUser = user;
20023        }
20024    }
20025
20026    @Override
20027    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20028            FileDescriptor err, String[] args, ShellCallback callback,
20029            ResultReceiver resultReceiver) {
20030        (new PackageManagerShellCommand(this)).exec(
20031                this, in, out, err, args, callback, resultReceiver);
20032    }
20033
20034    @Override
20035    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20036        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20037                != PackageManager.PERMISSION_GRANTED) {
20038            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20039                    + Binder.getCallingPid()
20040                    + ", uid=" + Binder.getCallingUid()
20041                    + " without permission "
20042                    + android.Manifest.permission.DUMP);
20043            return;
20044        }
20045
20046        DumpState dumpState = new DumpState();
20047        boolean fullPreferred = false;
20048        boolean checkin = false;
20049
20050        String packageName = null;
20051        ArraySet<String> permissionNames = null;
20052
20053        int opti = 0;
20054        while (opti < args.length) {
20055            String opt = args[opti];
20056            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20057                break;
20058            }
20059            opti++;
20060
20061            if ("-a".equals(opt)) {
20062                // Right now we only know how to print all.
20063            } else if ("-h".equals(opt)) {
20064                pw.println("Package manager dump options:");
20065                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20066                pw.println("    --checkin: dump for a checkin");
20067                pw.println("    -f: print details of intent filters");
20068                pw.println("    -h: print this help");
20069                pw.println("  cmd may be one of:");
20070                pw.println("    l[ibraries]: list known shared libraries");
20071                pw.println("    f[eatures]: list device features");
20072                pw.println("    k[eysets]: print known keysets");
20073                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20074                pw.println("    perm[issions]: dump permissions");
20075                pw.println("    permission [name ...]: dump declaration and use of given permission");
20076                pw.println("    pref[erred]: print preferred package settings");
20077                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20078                pw.println("    prov[iders]: dump content providers");
20079                pw.println("    p[ackages]: dump installed packages");
20080                pw.println("    s[hared-users]: dump shared user IDs");
20081                pw.println("    m[essages]: print collected runtime messages");
20082                pw.println("    v[erifiers]: print package verifier info");
20083                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20084                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20085                pw.println("    version: print database version info");
20086                pw.println("    write: write current settings now");
20087                pw.println("    installs: details about install sessions");
20088                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20089                pw.println("    dexopt: dump dexopt state");
20090                pw.println("    compiler-stats: dump compiler statistics");
20091                pw.println("    <package.name>: info about given package");
20092                return;
20093            } else if ("--checkin".equals(opt)) {
20094                checkin = true;
20095            } else if ("-f".equals(opt)) {
20096                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20097            } else {
20098                pw.println("Unknown argument: " + opt + "; use -h for help");
20099            }
20100        }
20101
20102        // Is the caller requesting to dump a particular piece of data?
20103        if (opti < args.length) {
20104            String cmd = args[opti];
20105            opti++;
20106            // Is this a package name?
20107            if ("android".equals(cmd) || cmd.contains(".")) {
20108                packageName = cmd;
20109                // When dumping a single package, we always dump all of its
20110                // filter information since the amount of data will be reasonable.
20111                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20112            } else if ("check-permission".equals(cmd)) {
20113                if (opti >= args.length) {
20114                    pw.println("Error: check-permission missing permission argument");
20115                    return;
20116                }
20117                String perm = args[opti];
20118                opti++;
20119                if (opti >= args.length) {
20120                    pw.println("Error: check-permission missing package argument");
20121                    return;
20122                }
20123
20124                String pkg = args[opti];
20125                opti++;
20126                int user = UserHandle.getUserId(Binder.getCallingUid());
20127                if (opti < args.length) {
20128                    try {
20129                        user = Integer.parseInt(args[opti]);
20130                    } catch (NumberFormatException e) {
20131                        pw.println("Error: check-permission user argument is not a number: "
20132                                + args[opti]);
20133                        return;
20134                    }
20135                }
20136
20137                // Normalize package name to handle renamed packages and static libs
20138                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20139
20140                pw.println(checkPermission(perm, pkg, user));
20141                return;
20142            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20143                dumpState.setDump(DumpState.DUMP_LIBS);
20144            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20145                dumpState.setDump(DumpState.DUMP_FEATURES);
20146            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20147                if (opti >= args.length) {
20148                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20149                            | DumpState.DUMP_SERVICE_RESOLVERS
20150                            | DumpState.DUMP_RECEIVER_RESOLVERS
20151                            | DumpState.DUMP_CONTENT_RESOLVERS);
20152                } else {
20153                    while (opti < args.length) {
20154                        String name = args[opti];
20155                        if ("a".equals(name) || "activity".equals(name)) {
20156                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20157                        } else if ("s".equals(name) || "service".equals(name)) {
20158                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20159                        } else if ("r".equals(name) || "receiver".equals(name)) {
20160                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20161                        } else if ("c".equals(name) || "content".equals(name)) {
20162                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20163                        } else {
20164                            pw.println("Error: unknown resolver table type: " + name);
20165                            return;
20166                        }
20167                        opti++;
20168                    }
20169                }
20170            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20171                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20172            } else if ("permission".equals(cmd)) {
20173                if (opti >= args.length) {
20174                    pw.println("Error: permission requires permission name");
20175                    return;
20176                }
20177                permissionNames = new ArraySet<>();
20178                while (opti < args.length) {
20179                    permissionNames.add(args[opti]);
20180                    opti++;
20181                }
20182                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20183                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20184            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20185                dumpState.setDump(DumpState.DUMP_PREFERRED);
20186            } else if ("preferred-xml".equals(cmd)) {
20187                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20188                if (opti < args.length && "--full".equals(args[opti])) {
20189                    fullPreferred = true;
20190                    opti++;
20191                }
20192            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20193                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20194            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20195                dumpState.setDump(DumpState.DUMP_PACKAGES);
20196            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20197                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20198            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20199                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20200            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20201                dumpState.setDump(DumpState.DUMP_MESSAGES);
20202            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20203                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20204            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20205                    || "intent-filter-verifiers".equals(cmd)) {
20206                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20207            } else if ("version".equals(cmd)) {
20208                dumpState.setDump(DumpState.DUMP_VERSION);
20209            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20210                dumpState.setDump(DumpState.DUMP_KEYSETS);
20211            } else if ("installs".equals(cmd)) {
20212                dumpState.setDump(DumpState.DUMP_INSTALLS);
20213            } else if ("frozen".equals(cmd)) {
20214                dumpState.setDump(DumpState.DUMP_FROZEN);
20215            } else if ("dexopt".equals(cmd)) {
20216                dumpState.setDump(DumpState.DUMP_DEXOPT);
20217            } else if ("compiler-stats".equals(cmd)) {
20218                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20219            } else if ("write".equals(cmd)) {
20220                synchronized (mPackages) {
20221                    mSettings.writeLPr();
20222                    pw.println("Settings written.");
20223                    return;
20224                }
20225            }
20226        }
20227
20228        if (checkin) {
20229            pw.println("vers,1");
20230        }
20231
20232        // reader
20233        synchronized (mPackages) {
20234            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20235                if (!checkin) {
20236                    if (dumpState.onTitlePrinted())
20237                        pw.println();
20238                    pw.println("Database versions:");
20239                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20240                }
20241            }
20242
20243            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20244                if (!checkin) {
20245                    if (dumpState.onTitlePrinted())
20246                        pw.println();
20247                    pw.println("Verifiers:");
20248                    pw.print("  Required: ");
20249                    pw.print(mRequiredVerifierPackage);
20250                    pw.print(" (uid=");
20251                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20252                            UserHandle.USER_SYSTEM));
20253                    pw.println(")");
20254                } else if (mRequiredVerifierPackage != null) {
20255                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20256                    pw.print(",");
20257                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20258                            UserHandle.USER_SYSTEM));
20259                }
20260            }
20261
20262            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20263                    packageName == null) {
20264                if (mIntentFilterVerifierComponent != null) {
20265                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20266                    if (!checkin) {
20267                        if (dumpState.onTitlePrinted())
20268                            pw.println();
20269                        pw.println("Intent Filter Verifier:");
20270                        pw.print("  Using: ");
20271                        pw.print(verifierPackageName);
20272                        pw.print(" (uid=");
20273                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20274                                UserHandle.USER_SYSTEM));
20275                        pw.println(")");
20276                    } else if (verifierPackageName != null) {
20277                        pw.print("ifv,"); pw.print(verifierPackageName);
20278                        pw.print(",");
20279                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20280                                UserHandle.USER_SYSTEM));
20281                    }
20282                } else {
20283                    pw.println();
20284                    pw.println("No Intent Filter Verifier available!");
20285                }
20286            }
20287
20288            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20289                boolean printedHeader = false;
20290                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20291                while (it.hasNext()) {
20292                    String libName = it.next();
20293                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20294                    if (versionedLib == null) {
20295                        continue;
20296                    }
20297                    final int versionCount = versionedLib.size();
20298                    for (int i = 0; i < versionCount; i++) {
20299                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20300                        if (!checkin) {
20301                            if (!printedHeader) {
20302                                if (dumpState.onTitlePrinted())
20303                                    pw.println();
20304                                pw.println("Libraries:");
20305                                printedHeader = true;
20306                            }
20307                            pw.print("  ");
20308                        } else {
20309                            pw.print("lib,");
20310                        }
20311                        pw.print(libEntry.info.getName());
20312                        if (libEntry.info.isStatic()) {
20313                            pw.print(" version=" + libEntry.info.getVersion());
20314                        }
20315                        if (!checkin) {
20316                            pw.print(" -> ");
20317                        }
20318                        if (libEntry.path != null) {
20319                            pw.print(" (jar) ");
20320                            pw.print(libEntry.path);
20321                        } else {
20322                            pw.print(" (apk) ");
20323                            pw.print(libEntry.apk);
20324                        }
20325                        pw.println();
20326                    }
20327                }
20328            }
20329
20330            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20331                if (dumpState.onTitlePrinted())
20332                    pw.println();
20333                if (!checkin) {
20334                    pw.println("Features:");
20335                }
20336
20337                for (FeatureInfo feat : mAvailableFeatures.values()) {
20338                    if (checkin) {
20339                        pw.print("feat,");
20340                        pw.print(feat.name);
20341                        pw.print(",");
20342                        pw.println(feat.version);
20343                    } else {
20344                        pw.print("  ");
20345                        pw.print(feat.name);
20346                        if (feat.version > 0) {
20347                            pw.print(" version=");
20348                            pw.print(feat.version);
20349                        }
20350                        pw.println();
20351                    }
20352                }
20353            }
20354
20355            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20356                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20357                        : "Activity Resolver Table:", "  ", packageName,
20358                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20359                    dumpState.setTitlePrinted(true);
20360                }
20361            }
20362            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20363                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20364                        : "Receiver Resolver Table:", "  ", packageName,
20365                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20366                    dumpState.setTitlePrinted(true);
20367                }
20368            }
20369            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20370                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20371                        : "Service Resolver Table:", "  ", packageName,
20372                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20373                    dumpState.setTitlePrinted(true);
20374                }
20375            }
20376            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20377                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20378                        : "Provider Resolver Table:", "  ", packageName,
20379                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20380                    dumpState.setTitlePrinted(true);
20381                }
20382            }
20383
20384            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20385                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20386                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20387                    int user = mSettings.mPreferredActivities.keyAt(i);
20388                    if (pir.dump(pw,
20389                            dumpState.getTitlePrinted()
20390                                ? "\nPreferred Activities User " + user + ":"
20391                                : "Preferred Activities User " + user + ":", "  ",
20392                            packageName, true, false)) {
20393                        dumpState.setTitlePrinted(true);
20394                    }
20395                }
20396            }
20397
20398            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20399                pw.flush();
20400                FileOutputStream fout = new FileOutputStream(fd);
20401                BufferedOutputStream str = new BufferedOutputStream(fout);
20402                XmlSerializer serializer = new FastXmlSerializer();
20403                try {
20404                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20405                    serializer.startDocument(null, true);
20406                    serializer.setFeature(
20407                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20408                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20409                    serializer.endDocument();
20410                    serializer.flush();
20411                } catch (IllegalArgumentException e) {
20412                    pw.println("Failed writing: " + e);
20413                } catch (IllegalStateException e) {
20414                    pw.println("Failed writing: " + e);
20415                } catch (IOException e) {
20416                    pw.println("Failed writing: " + e);
20417                }
20418            }
20419
20420            if (!checkin
20421                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20422                    && packageName == null) {
20423                pw.println();
20424                int count = mSettings.mPackages.size();
20425                if (count == 0) {
20426                    pw.println("No applications!");
20427                    pw.println();
20428                } else {
20429                    final String prefix = "  ";
20430                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20431                    if (allPackageSettings.size() == 0) {
20432                        pw.println("No domain preferred apps!");
20433                        pw.println();
20434                    } else {
20435                        pw.println("App verification status:");
20436                        pw.println();
20437                        count = 0;
20438                        for (PackageSetting ps : allPackageSettings) {
20439                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20440                            if (ivi == null || ivi.getPackageName() == null) continue;
20441                            pw.println(prefix + "Package: " + ivi.getPackageName());
20442                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20443                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20444                            pw.println();
20445                            count++;
20446                        }
20447                        if (count == 0) {
20448                            pw.println(prefix + "No app verification established.");
20449                            pw.println();
20450                        }
20451                        for (int userId : sUserManager.getUserIds()) {
20452                            pw.println("App linkages for user " + userId + ":");
20453                            pw.println();
20454                            count = 0;
20455                            for (PackageSetting ps : allPackageSettings) {
20456                                final long status = ps.getDomainVerificationStatusForUser(userId);
20457                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20458                                        && !DEBUG_DOMAIN_VERIFICATION) {
20459                                    continue;
20460                                }
20461                                pw.println(prefix + "Package: " + ps.name);
20462                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20463                                String statusStr = IntentFilterVerificationInfo.
20464                                        getStatusStringFromValue(status);
20465                                pw.println(prefix + "Status:  " + statusStr);
20466                                pw.println();
20467                                count++;
20468                            }
20469                            if (count == 0) {
20470                                pw.println(prefix + "No configured app linkages.");
20471                                pw.println();
20472                            }
20473                        }
20474                    }
20475                }
20476            }
20477
20478            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20479                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20480                if (packageName == null && permissionNames == null) {
20481                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20482                        if (iperm == 0) {
20483                            if (dumpState.onTitlePrinted())
20484                                pw.println();
20485                            pw.println("AppOp Permissions:");
20486                        }
20487                        pw.print("  AppOp Permission ");
20488                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20489                        pw.println(":");
20490                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20491                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20492                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20493                        }
20494                    }
20495                }
20496            }
20497
20498            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20499                boolean printedSomething = false;
20500                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20501                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20502                        continue;
20503                    }
20504                    if (!printedSomething) {
20505                        if (dumpState.onTitlePrinted())
20506                            pw.println();
20507                        pw.println("Registered ContentProviders:");
20508                        printedSomething = true;
20509                    }
20510                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20511                    pw.print("    "); pw.println(p.toString());
20512                }
20513                printedSomething = false;
20514                for (Map.Entry<String, PackageParser.Provider> entry :
20515                        mProvidersByAuthority.entrySet()) {
20516                    PackageParser.Provider p = entry.getValue();
20517                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20518                        continue;
20519                    }
20520                    if (!printedSomething) {
20521                        if (dumpState.onTitlePrinted())
20522                            pw.println();
20523                        pw.println("ContentProvider Authorities:");
20524                        printedSomething = true;
20525                    }
20526                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20527                    pw.print("    "); pw.println(p.toString());
20528                    if (p.info != null && p.info.applicationInfo != null) {
20529                        final String appInfo = p.info.applicationInfo.toString();
20530                        pw.print("      applicationInfo="); pw.println(appInfo);
20531                    }
20532                }
20533            }
20534
20535            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20536                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20537            }
20538
20539            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20540                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20541            }
20542
20543            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20544                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20545            }
20546
20547            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20548                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20549            }
20550
20551            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20552                // XXX should handle packageName != null by dumping only install data that
20553                // the given package is involved with.
20554                if (dumpState.onTitlePrinted()) pw.println();
20555                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20556            }
20557
20558            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20559                // XXX should handle packageName != null by dumping only install data that
20560                // the given package is involved with.
20561                if (dumpState.onTitlePrinted()) pw.println();
20562
20563                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20564                ipw.println();
20565                ipw.println("Frozen packages:");
20566                ipw.increaseIndent();
20567                if (mFrozenPackages.size() == 0) {
20568                    ipw.println("(none)");
20569                } else {
20570                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20571                        ipw.println(mFrozenPackages.valueAt(i));
20572                    }
20573                }
20574                ipw.decreaseIndent();
20575            }
20576
20577            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20578                if (dumpState.onTitlePrinted()) pw.println();
20579                dumpDexoptStateLPr(pw, packageName);
20580            }
20581
20582            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20583                if (dumpState.onTitlePrinted()) pw.println();
20584                dumpCompilerStatsLPr(pw, packageName);
20585            }
20586
20587            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20588                if (dumpState.onTitlePrinted()) pw.println();
20589                mSettings.dumpReadMessagesLPr(pw, dumpState);
20590
20591                pw.println();
20592                pw.println("Package warning messages:");
20593                BufferedReader in = null;
20594                String line = null;
20595                try {
20596                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20597                    while ((line = in.readLine()) != null) {
20598                        if (line.contains("ignored: updated version")) continue;
20599                        pw.println(line);
20600                    }
20601                } catch (IOException ignored) {
20602                } finally {
20603                    IoUtils.closeQuietly(in);
20604                }
20605            }
20606
20607            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20608                BufferedReader in = null;
20609                String line = null;
20610                try {
20611                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20612                    while ((line = in.readLine()) != null) {
20613                        if (line.contains("ignored: updated version")) continue;
20614                        pw.print("msg,");
20615                        pw.println(line);
20616                    }
20617                } catch (IOException ignored) {
20618                } finally {
20619                    IoUtils.closeQuietly(in);
20620                }
20621            }
20622        }
20623    }
20624
20625    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20626        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20627        ipw.println();
20628        ipw.println("Dexopt state:");
20629        ipw.increaseIndent();
20630        Collection<PackageParser.Package> packages = null;
20631        if (packageName != null) {
20632            PackageParser.Package targetPackage = mPackages.get(packageName);
20633            if (targetPackage != null) {
20634                packages = Collections.singletonList(targetPackage);
20635            } else {
20636                ipw.println("Unable to find package: " + packageName);
20637                return;
20638            }
20639        } else {
20640            packages = mPackages.values();
20641        }
20642
20643        for (PackageParser.Package pkg : packages) {
20644            ipw.println("[" + pkg.packageName + "]");
20645            ipw.increaseIndent();
20646            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20647            ipw.decreaseIndent();
20648        }
20649    }
20650
20651    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20652        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20653        ipw.println();
20654        ipw.println("Compiler stats:");
20655        ipw.increaseIndent();
20656        Collection<PackageParser.Package> packages = null;
20657        if (packageName != null) {
20658            PackageParser.Package targetPackage = mPackages.get(packageName);
20659            if (targetPackage != null) {
20660                packages = Collections.singletonList(targetPackage);
20661            } else {
20662                ipw.println("Unable to find package: " + packageName);
20663                return;
20664            }
20665        } else {
20666            packages = mPackages.values();
20667        }
20668
20669        for (PackageParser.Package pkg : packages) {
20670            ipw.println("[" + pkg.packageName + "]");
20671            ipw.increaseIndent();
20672
20673            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20674            if (stats == null) {
20675                ipw.println("(No recorded stats)");
20676            } else {
20677                stats.dump(ipw);
20678            }
20679            ipw.decreaseIndent();
20680        }
20681    }
20682
20683    private String dumpDomainString(String packageName) {
20684        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20685                .getList();
20686        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20687
20688        ArraySet<String> result = new ArraySet<>();
20689        if (iviList.size() > 0) {
20690            for (IntentFilterVerificationInfo ivi : iviList) {
20691                for (String host : ivi.getDomains()) {
20692                    result.add(host);
20693                }
20694            }
20695        }
20696        if (filters != null && filters.size() > 0) {
20697            for (IntentFilter filter : filters) {
20698                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20699                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20700                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20701                    result.addAll(filter.getHostsList());
20702                }
20703            }
20704        }
20705
20706        StringBuilder sb = new StringBuilder(result.size() * 16);
20707        for (String domain : result) {
20708            if (sb.length() > 0) sb.append(" ");
20709            sb.append(domain);
20710        }
20711        return sb.toString();
20712    }
20713
20714    // ------- apps on sdcard specific code -------
20715    static final boolean DEBUG_SD_INSTALL = false;
20716
20717    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20718
20719    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20720
20721    private boolean mMediaMounted = false;
20722
20723    static String getEncryptKey() {
20724        try {
20725            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20726                    SD_ENCRYPTION_KEYSTORE_NAME);
20727            if (sdEncKey == null) {
20728                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20729                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20730                if (sdEncKey == null) {
20731                    Slog.e(TAG, "Failed to create encryption keys");
20732                    return null;
20733                }
20734            }
20735            return sdEncKey;
20736        } catch (NoSuchAlgorithmException nsae) {
20737            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20738            return null;
20739        } catch (IOException ioe) {
20740            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20741            return null;
20742        }
20743    }
20744
20745    /*
20746     * Update media status on PackageManager.
20747     */
20748    @Override
20749    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20750        int callingUid = Binder.getCallingUid();
20751        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20752            throw new SecurityException("Media status can only be updated by the system");
20753        }
20754        // reader; this apparently protects mMediaMounted, but should probably
20755        // be a different lock in that case.
20756        synchronized (mPackages) {
20757            Log.i(TAG, "Updating external media status from "
20758                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20759                    + (mediaStatus ? "mounted" : "unmounted"));
20760            if (DEBUG_SD_INSTALL)
20761                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20762                        + ", mMediaMounted=" + mMediaMounted);
20763            if (mediaStatus == mMediaMounted) {
20764                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20765                        : 0, -1);
20766                mHandler.sendMessage(msg);
20767                return;
20768            }
20769            mMediaMounted = mediaStatus;
20770        }
20771        // Queue up an async operation since the package installation may take a
20772        // little while.
20773        mHandler.post(new Runnable() {
20774            public void run() {
20775                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20776            }
20777        });
20778    }
20779
20780    /**
20781     * Called by StorageManagerService when the initial ASECs to scan are available.
20782     * Should block until all the ASEC containers are finished being scanned.
20783     */
20784    public void scanAvailableAsecs() {
20785        updateExternalMediaStatusInner(true, false, false);
20786    }
20787
20788    /*
20789     * Collect information of applications on external media, map them against
20790     * existing containers and update information based on current mount status.
20791     * Please note that we always have to report status if reportStatus has been
20792     * set to true especially when unloading packages.
20793     */
20794    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20795            boolean externalStorage) {
20796        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20797        int[] uidArr = EmptyArray.INT;
20798
20799        final String[] list = PackageHelper.getSecureContainerList();
20800        if (ArrayUtils.isEmpty(list)) {
20801            Log.i(TAG, "No secure containers found");
20802        } else {
20803            // Process list of secure containers and categorize them
20804            // as active or stale based on their package internal state.
20805
20806            // reader
20807            synchronized (mPackages) {
20808                for (String cid : list) {
20809                    // Leave stages untouched for now; installer service owns them
20810                    if (PackageInstallerService.isStageName(cid)) continue;
20811
20812                    if (DEBUG_SD_INSTALL)
20813                        Log.i(TAG, "Processing container " + cid);
20814                    String pkgName = getAsecPackageName(cid);
20815                    if (pkgName == null) {
20816                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20817                        continue;
20818                    }
20819                    if (DEBUG_SD_INSTALL)
20820                        Log.i(TAG, "Looking for pkg : " + pkgName);
20821
20822                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20823                    if (ps == null) {
20824                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20825                        continue;
20826                    }
20827
20828                    /*
20829                     * Skip packages that are not external if we're unmounting
20830                     * external storage.
20831                     */
20832                    if (externalStorage && !isMounted && !isExternal(ps)) {
20833                        continue;
20834                    }
20835
20836                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20837                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20838                    // The package status is changed only if the code path
20839                    // matches between settings and the container id.
20840                    if (ps.codePathString != null
20841                            && ps.codePathString.startsWith(args.getCodePath())) {
20842                        if (DEBUG_SD_INSTALL) {
20843                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20844                                    + " at code path: " + ps.codePathString);
20845                        }
20846
20847                        // We do have a valid package installed on sdcard
20848                        processCids.put(args, ps.codePathString);
20849                        final int uid = ps.appId;
20850                        if (uid != -1) {
20851                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20852                        }
20853                    } else {
20854                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20855                                + ps.codePathString);
20856                    }
20857                }
20858            }
20859
20860            Arrays.sort(uidArr);
20861        }
20862
20863        // Process packages with valid entries.
20864        if (isMounted) {
20865            if (DEBUG_SD_INSTALL)
20866                Log.i(TAG, "Loading packages");
20867            loadMediaPackages(processCids, uidArr, externalStorage);
20868            startCleaningPackages();
20869            mInstallerService.onSecureContainersAvailable();
20870        } else {
20871            if (DEBUG_SD_INSTALL)
20872                Log.i(TAG, "Unloading packages");
20873            unloadMediaPackages(processCids, uidArr, reportStatus);
20874        }
20875    }
20876
20877    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20878            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20879        final int size = infos.size();
20880        final String[] packageNames = new String[size];
20881        final int[] packageUids = new int[size];
20882        for (int i = 0; i < size; i++) {
20883            final ApplicationInfo info = infos.get(i);
20884            packageNames[i] = info.packageName;
20885            packageUids[i] = info.uid;
20886        }
20887        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20888                finishedReceiver);
20889    }
20890
20891    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20892            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20893        sendResourcesChangedBroadcast(mediaStatus, replacing,
20894                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20895    }
20896
20897    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20898            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20899        int size = pkgList.length;
20900        if (size > 0) {
20901            // Send broadcasts here
20902            Bundle extras = new Bundle();
20903            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20904            if (uidArr != null) {
20905                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20906            }
20907            if (replacing) {
20908                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20909            }
20910            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20911                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20912            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20913        }
20914    }
20915
20916   /*
20917     * Look at potentially valid container ids from processCids If package
20918     * information doesn't match the one on record or package scanning fails,
20919     * the cid is added to list of removeCids. We currently don't delete stale
20920     * containers.
20921     */
20922    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20923            boolean externalStorage) {
20924        ArrayList<String> pkgList = new ArrayList<String>();
20925        Set<AsecInstallArgs> keys = processCids.keySet();
20926
20927        for (AsecInstallArgs args : keys) {
20928            String codePath = processCids.get(args);
20929            if (DEBUG_SD_INSTALL)
20930                Log.i(TAG, "Loading container : " + args.cid);
20931            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20932            try {
20933                // Make sure there are no container errors first.
20934                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20935                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20936                            + " when installing from sdcard");
20937                    continue;
20938                }
20939                // Check code path here.
20940                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20941                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20942                            + " does not match one in settings " + codePath);
20943                    continue;
20944                }
20945                // Parse package
20946                int parseFlags = mDefParseFlags;
20947                if (args.isExternalAsec()) {
20948                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20949                }
20950                if (args.isFwdLocked()) {
20951                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20952                }
20953
20954                synchronized (mInstallLock) {
20955                    PackageParser.Package pkg = null;
20956                    try {
20957                        // Sadly we don't know the package name yet to freeze it
20958                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20959                                SCAN_IGNORE_FROZEN, 0, null);
20960                    } catch (PackageManagerException e) {
20961                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20962                    }
20963                    // Scan the package
20964                    if (pkg != null) {
20965                        /*
20966                         * TODO why is the lock being held? doPostInstall is
20967                         * called in other places without the lock. This needs
20968                         * to be straightened out.
20969                         */
20970                        // writer
20971                        synchronized (mPackages) {
20972                            retCode = PackageManager.INSTALL_SUCCEEDED;
20973                            pkgList.add(pkg.packageName);
20974                            // Post process args
20975                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20976                                    pkg.applicationInfo.uid);
20977                        }
20978                    } else {
20979                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20980                    }
20981                }
20982
20983            } finally {
20984                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20985                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20986                }
20987            }
20988        }
20989        // writer
20990        synchronized (mPackages) {
20991            // If the platform SDK has changed since the last time we booted,
20992            // we need to re-grant app permission to catch any new ones that
20993            // appear. This is really a hack, and means that apps can in some
20994            // cases get permissions that the user didn't initially explicitly
20995            // allow... it would be nice to have some better way to handle
20996            // this situation.
20997            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20998                    : mSettings.getInternalVersion();
20999            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21000                    : StorageManager.UUID_PRIVATE_INTERNAL;
21001
21002            int updateFlags = UPDATE_PERMISSIONS_ALL;
21003            if (ver.sdkVersion != mSdkVersion) {
21004                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21005                        + mSdkVersion + "; regranting permissions for external");
21006                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21007            }
21008            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21009
21010            // Yay, everything is now upgraded
21011            ver.forceCurrent();
21012
21013            // can downgrade to reader
21014            // Persist settings
21015            mSettings.writeLPr();
21016        }
21017        // Send a broadcast to let everyone know we are done processing
21018        if (pkgList.size() > 0) {
21019            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21020        }
21021    }
21022
21023   /*
21024     * Utility method to unload a list of specified containers
21025     */
21026    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21027        // Just unmount all valid containers.
21028        for (AsecInstallArgs arg : cidArgs) {
21029            synchronized (mInstallLock) {
21030                arg.doPostDeleteLI(false);
21031           }
21032       }
21033   }
21034
21035    /*
21036     * Unload packages mounted on external media. This involves deleting package
21037     * data from internal structures, sending broadcasts about disabled packages,
21038     * gc'ing to free up references, unmounting all secure containers
21039     * corresponding to packages on external media, and posting a
21040     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21041     * that we always have to post this message if status has been requested no
21042     * matter what.
21043     */
21044    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21045            final boolean reportStatus) {
21046        if (DEBUG_SD_INSTALL)
21047            Log.i(TAG, "unloading media packages");
21048        ArrayList<String> pkgList = new ArrayList<String>();
21049        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21050        final Set<AsecInstallArgs> keys = processCids.keySet();
21051        for (AsecInstallArgs args : keys) {
21052            String pkgName = args.getPackageName();
21053            if (DEBUG_SD_INSTALL)
21054                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21055            // Delete package internally
21056            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21057            synchronized (mInstallLock) {
21058                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21059                final boolean res;
21060                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21061                        "unloadMediaPackages")) {
21062                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21063                            null);
21064                }
21065                if (res) {
21066                    pkgList.add(pkgName);
21067                } else {
21068                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21069                    failedList.add(args);
21070                }
21071            }
21072        }
21073
21074        // reader
21075        synchronized (mPackages) {
21076            // We didn't update the settings after removing each package;
21077            // write them now for all packages.
21078            mSettings.writeLPr();
21079        }
21080
21081        // We have to absolutely send UPDATED_MEDIA_STATUS only
21082        // after confirming that all the receivers processed the ordered
21083        // broadcast when packages get disabled, force a gc to clean things up.
21084        // and unload all the containers.
21085        if (pkgList.size() > 0) {
21086            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21087                    new IIntentReceiver.Stub() {
21088                public void performReceive(Intent intent, int resultCode, String data,
21089                        Bundle extras, boolean ordered, boolean sticky,
21090                        int sendingUser) throws RemoteException {
21091                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21092                            reportStatus ? 1 : 0, 1, keys);
21093                    mHandler.sendMessage(msg);
21094                }
21095            });
21096        } else {
21097            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21098                    keys);
21099            mHandler.sendMessage(msg);
21100        }
21101    }
21102
21103    private void loadPrivatePackages(final VolumeInfo vol) {
21104        mHandler.post(new Runnable() {
21105            @Override
21106            public void run() {
21107                loadPrivatePackagesInner(vol);
21108            }
21109        });
21110    }
21111
21112    private void loadPrivatePackagesInner(VolumeInfo vol) {
21113        final String volumeUuid = vol.fsUuid;
21114        if (TextUtils.isEmpty(volumeUuid)) {
21115            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21116            return;
21117        }
21118
21119        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21120        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21121        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21122
21123        final VersionInfo ver;
21124        final List<PackageSetting> packages;
21125        synchronized (mPackages) {
21126            ver = mSettings.findOrCreateVersion(volumeUuid);
21127            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21128        }
21129
21130        for (PackageSetting ps : packages) {
21131            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21132            synchronized (mInstallLock) {
21133                final PackageParser.Package pkg;
21134                try {
21135                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21136                    loaded.add(pkg.applicationInfo);
21137
21138                } catch (PackageManagerException e) {
21139                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21140                }
21141
21142                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21143                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21144                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21145                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21146                }
21147            }
21148        }
21149
21150        // Reconcile app data for all started/unlocked users
21151        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21152        final UserManager um = mContext.getSystemService(UserManager.class);
21153        UserManagerInternal umInternal = getUserManagerInternal();
21154        for (UserInfo user : um.getUsers()) {
21155            final int flags;
21156            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21157                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21158            } else if (umInternal.isUserRunning(user.id)) {
21159                flags = StorageManager.FLAG_STORAGE_DE;
21160            } else {
21161                continue;
21162            }
21163
21164            try {
21165                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21166                synchronized (mInstallLock) {
21167                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21168                }
21169            } catch (IllegalStateException e) {
21170                // Device was probably ejected, and we'll process that event momentarily
21171                Slog.w(TAG, "Failed to prepare storage: " + e);
21172            }
21173        }
21174
21175        synchronized (mPackages) {
21176            int updateFlags = UPDATE_PERMISSIONS_ALL;
21177            if (ver.sdkVersion != mSdkVersion) {
21178                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21179                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21180                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21181            }
21182            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21183
21184            // Yay, everything is now upgraded
21185            ver.forceCurrent();
21186
21187            mSettings.writeLPr();
21188        }
21189
21190        for (PackageFreezer freezer : freezers) {
21191            freezer.close();
21192        }
21193
21194        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21195        sendResourcesChangedBroadcast(true, false, loaded, null);
21196    }
21197
21198    private void unloadPrivatePackages(final VolumeInfo vol) {
21199        mHandler.post(new Runnable() {
21200            @Override
21201            public void run() {
21202                unloadPrivatePackagesInner(vol);
21203            }
21204        });
21205    }
21206
21207    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21208        final String volumeUuid = vol.fsUuid;
21209        if (TextUtils.isEmpty(volumeUuid)) {
21210            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21211            return;
21212        }
21213
21214        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21215        synchronized (mInstallLock) {
21216        synchronized (mPackages) {
21217            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21218            for (PackageSetting ps : packages) {
21219                if (ps.pkg == null) continue;
21220
21221                final ApplicationInfo info = ps.pkg.applicationInfo;
21222                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21223                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21224
21225                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21226                        "unloadPrivatePackagesInner")) {
21227                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21228                            false, null)) {
21229                        unloaded.add(info);
21230                    } else {
21231                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21232                    }
21233                }
21234
21235                // Try very hard to release any references to this package
21236                // so we don't risk the system server being killed due to
21237                // open FDs
21238                AttributeCache.instance().removePackage(ps.name);
21239            }
21240
21241            mSettings.writeLPr();
21242        }
21243        }
21244
21245        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21246        sendResourcesChangedBroadcast(false, false, unloaded, null);
21247
21248        // Try very hard to release any references to this path so we don't risk
21249        // the system server being killed due to open FDs
21250        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21251
21252        for (int i = 0; i < 3; i++) {
21253            System.gc();
21254            System.runFinalization();
21255        }
21256    }
21257
21258    /**
21259     * Prepare storage areas for given user on all mounted devices.
21260     */
21261    void prepareUserData(int userId, int userSerial, int flags) {
21262        synchronized (mInstallLock) {
21263            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21264            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21265                final String volumeUuid = vol.getFsUuid();
21266                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
21267            }
21268        }
21269    }
21270
21271    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
21272            boolean allowRecover) {
21273        // Prepare storage and verify that serial numbers are consistent; if
21274        // there's a mismatch we need to destroy to avoid leaking data
21275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21276        try {
21277            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
21278
21279            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
21280                UserManagerService.enforceSerialNumber(
21281                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
21282                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21283                    UserManagerService.enforceSerialNumber(
21284                            Environment.getDataSystemDeDirectory(userId), userSerial);
21285                }
21286            }
21287            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
21288                UserManagerService.enforceSerialNumber(
21289                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
21290                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21291                    UserManagerService.enforceSerialNumber(
21292                            Environment.getDataSystemCeDirectory(userId), userSerial);
21293                }
21294            }
21295
21296            synchronized (mInstallLock) {
21297                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
21298            }
21299        } catch (Exception e) {
21300            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
21301                    + " because we failed to prepare: " + e);
21302            destroyUserDataLI(volumeUuid, userId,
21303                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21304
21305            if (allowRecover) {
21306                // Try one last time; if we fail again we're really in trouble
21307                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
21308            }
21309        }
21310    }
21311
21312    /**
21313     * Destroy storage areas for given user on all mounted devices.
21314     */
21315    void destroyUserData(int userId, int flags) {
21316        synchronized (mInstallLock) {
21317            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21318            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21319                final String volumeUuid = vol.getFsUuid();
21320                destroyUserDataLI(volumeUuid, userId, flags);
21321            }
21322        }
21323    }
21324
21325    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
21326        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21327        try {
21328            // Clean up app data, profile data, and media data
21329            mInstaller.destroyUserData(volumeUuid, userId, flags);
21330
21331            // Clean up system data
21332            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21333                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21334                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
21335                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
21336                    FileUtils.deleteContentsAndDir(Environment.getDataMiscDeDirectory(userId));
21337                }
21338                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21339                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
21340                    FileUtils.deleteContentsAndDir(Environment.getDataMiscCeDirectory(userId));
21341                }
21342            }
21343
21344            // Data with special labels is now gone, so finish the job
21345            storage.destroyUserStorage(volumeUuid, userId, flags);
21346
21347        } catch (Exception e) {
21348            logCriticalInfo(Log.WARN,
21349                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
21350        }
21351    }
21352
21353    /**
21354     * Examine all users present on given mounted volume, and destroy data
21355     * belonging to users that are no longer valid, or whose user ID has been
21356     * recycled.
21357     */
21358    private void reconcileUsers(String volumeUuid) {
21359        final List<File> files = new ArrayList<>();
21360        Collections.addAll(files, FileUtils
21361                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
21362        Collections.addAll(files, FileUtils
21363                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
21364        Collections.addAll(files, FileUtils
21365                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
21366        Collections.addAll(files, FileUtils
21367                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
21368        Collections.addAll(files, FileUtils
21369                .listFilesOrEmpty(Environment.getDataMiscCeDirectory()));
21370        for (File file : files) {
21371            if (!file.isDirectory()) continue;
21372
21373            final int userId;
21374            final UserInfo info;
21375            try {
21376                userId = Integer.parseInt(file.getName());
21377                info = sUserManager.getUserInfo(userId);
21378            } catch (NumberFormatException e) {
21379                Slog.w(TAG, "Invalid user directory " + file);
21380                continue;
21381            }
21382
21383            boolean destroyUser = false;
21384            if (info == null) {
21385                logCriticalInfo(Log.WARN, "Destroying user directory " + file
21386                        + " because no matching user was found");
21387                destroyUser = true;
21388            } else if (!mOnlyCore) {
21389                try {
21390                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
21391                } catch (IOException e) {
21392                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
21393                            + " because we failed to enforce serial number: " + e);
21394                    destroyUser = true;
21395                }
21396            }
21397
21398            if (destroyUser) {
21399                synchronized (mInstallLock) {
21400                    destroyUserDataLI(volumeUuid, userId,
21401                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21402                }
21403            }
21404        }
21405    }
21406
21407    private void assertPackageKnown(String volumeUuid, String packageName)
21408            throws PackageManagerException {
21409        synchronized (mPackages) {
21410            // Normalize package name to handle renamed packages
21411            packageName = normalizePackageNameLPr(packageName);
21412
21413            final PackageSetting ps = mSettings.mPackages.get(packageName);
21414            if (ps == null) {
21415                throw new PackageManagerException("Package " + packageName + " is unknown");
21416            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21417                throw new PackageManagerException(
21418                        "Package " + packageName + " found on unknown volume " + volumeUuid
21419                                + "; expected volume " + ps.volumeUuid);
21420            }
21421        }
21422    }
21423
21424    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21425            throws PackageManagerException {
21426        synchronized (mPackages) {
21427            // Normalize package name to handle renamed packages
21428            packageName = normalizePackageNameLPr(packageName);
21429
21430            final PackageSetting ps = mSettings.mPackages.get(packageName);
21431            if (ps == null) {
21432                throw new PackageManagerException("Package " + packageName + " is unknown");
21433            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21434                throw new PackageManagerException(
21435                        "Package " + packageName + " found on unknown volume " + volumeUuid
21436                                + "; expected volume " + ps.volumeUuid);
21437            } else if (!ps.getInstalled(userId)) {
21438                throw new PackageManagerException(
21439                        "Package " + packageName + " not installed for user " + userId);
21440            }
21441        }
21442    }
21443
21444    private List<String> collectAbsoluteCodePaths() {
21445        synchronized (mPackages) {
21446            List<String> codePaths = new ArrayList<>();
21447            final int packageCount = mSettings.mPackages.size();
21448            for (int i = 0; i < packageCount; i++) {
21449                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21450                codePaths.add(ps.codePath.getAbsolutePath());
21451            }
21452            return codePaths;
21453        }
21454    }
21455
21456    /**
21457     * Examine all apps present on given mounted volume, and destroy apps that
21458     * aren't expected, either due to uninstallation or reinstallation on
21459     * another volume.
21460     */
21461    private void reconcileApps(String volumeUuid) {
21462        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21463        List<File> filesToDelete = null;
21464
21465        final File[] files = FileUtils.listFilesOrEmpty(
21466                Environment.getDataAppDirectory(volumeUuid));
21467        for (File file : files) {
21468            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21469                    && !PackageInstallerService.isStageName(file.getName());
21470            if (!isPackage) {
21471                // Ignore entries which are not packages
21472                continue;
21473            }
21474
21475            String absolutePath = file.getAbsolutePath();
21476
21477            boolean pathValid = false;
21478            final int absoluteCodePathCount = absoluteCodePaths.size();
21479            for (int i = 0; i < absoluteCodePathCount; i++) {
21480                String absoluteCodePath = absoluteCodePaths.get(i);
21481                if (absolutePath.startsWith(absoluteCodePath)) {
21482                    pathValid = true;
21483                    break;
21484                }
21485            }
21486
21487            if (!pathValid) {
21488                if (filesToDelete == null) {
21489                    filesToDelete = new ArrayList<>();
21490                }
21491                filesToDelete.add(file);
21492            }
21493        }
21494
21495        if (filesToDelete != null) {
21496            final int fileToDeleteCount = filesToDelete.size();
21497            for (int i = 0; i < fileToDeleteCount; i++) {
21498                File fileToDelete = filesToDelete.get(i);
21499                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21500                synchronized (mInstallLock) {
21501                    removeCodePathLI(fileToDelete);
21502                }
21503            }
21504        }
21505    }
21506
21507    /**
21508     * Reconcile all app data for the given user.
21509     * <p>
21510     * Verifies that directories exist and that ownership and labeling is
21511     * correct for all installed apps on all mounted volumes.
21512     */
21513    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21514        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21515        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21516            final String volumeUuid = vol.getFsUuid();
21517            synchronized (mInstallLock) {
21518                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21519            }
21520        }
21521    }
21522
21523    /**
21524     * Reconcile all app data on given mounted volume.
21525     * <p>
21526     * Destroys app data that isn't expected, either due to uninstallation or
21527     * reinstallation on another volume.
21528     * <p>
21529     * Verifies that directories exist and that ownership and labeling is
21530     * correct for all installed apps.
21531     */
21532    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21533            boolean migrateAppData) {
21534        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21535                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21536
21537        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21538        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21539
21540        // First look for stale data that doesn't belong, and check if things
21541        // have changed since we did our last restorecon
21542        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21543            if (StorageManager.isFileEncryptedNativeOrEmulated()
21544                    && !StorageManager.isUserKeyUnlocked(userId)) {
21545                throw new RuntimeException(
21546                        "Yikes, someone asked us to reconcile CE storage while " + userId
21547                                + " was still locked; this would have caused massive data loss!");
21548            }
21549
21550            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21551            for (File file : files) {
21552                final String packageName = file.getName();
21553                try {
21554                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21555                } catch (PackageManagerException e) {
21556                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21557                    try {
21558                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21559                                StorageManager.FLAG_STORAGE_CE, 0);
21560                    } catch (InstallerException e2) {
21561                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21562                    }
21563                }
21564            }
21565        }
21566        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21567            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21568            for (File file : files) {
21569                final String packageName = file.getName();
21570                try {
21571                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21572                } catch (PackageManagerException e) {
21573                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21574                    try {
21575                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21576                                StorageManager.FLAG_STORAGE_DE, 0);
21577                    } catch (InstallerException e2) {
21578                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21579                    }
21580                }
21581            }
21582        }
21583
21584        // Ensure that data directories are ready to roll for all packages
21585        // installed for this volume and user
21586        final List<PackageSetting> packages;
21587        synchronized (mPackages) {
21588            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21589        }
21590        int preparedCount = 0;
21591        for (PackageSetting ps : packages) {
21592            final String packageName = ps.name;
21593            if (ps.pkg == null) {
21594                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21595                // TODO: might be due to legacy ASEC apps; we should circle back
21596                // and reconcile again once they're scanned
21597                continue;
21598            }
21599
21600            if (ps.getInstalled(userId)) {
21601                prepareAppDataLIF(ps.pkg, userId, flags);
21602
21603                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21604                    // We may have just shuffled around app data directories, so
21605                    // prepare them one more time
21606                    prepareAppDataLIF(ps.pkg, userId, flags);
21607                }
21608
21609                preparedCount++;
21610            }
21611        }
21612
21613        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21614    }
21615
21616    /**
21617     * Prepare app data for the given app just after it was installed or
21618     * upgraded. This method carefully only touches users that it's installed
21619     * for, and it forces a restorecon to handle any seinfo changes.
21620     * <p>
21621     * Verifies that directories exist and that ownership and labeling is
21622     * correct for all installed apps. If there is an ownership mismatch, it
21623     * will try recovering system apps by wiping data; third-party app data is
21624     * left intact.
21625     * <p>
21626     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21627     */
21628    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21629        final PackageSetting ps;
21630        synchronized (mPackages) {
21631            ps = mSettings.mPackages.get(pkg.packageName);
21632            mSettings.writeKernelMappingLPr(ps);
21633        }
21634
21635        final UserManager um = mContext.getSystemService(UserManager.class);
21636        UserManagerInternal umInternal = getUserManagerInternal();
21637        for (UserInfo user : um.getUsers()) {
21638            final int flags;
21639            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21640                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21641            } else if (umInternal.isUserRunning(user.id)) {
21642                flags = StorageManager.FLAG_STORAGE_DE;
21643            } else {
21644                continue;
21645            }
21646
21647            if (ps.getInstalled(user.id)) {
21648                // TODO: when user data is locked, mark that we're still dirty
21649                prepareAppDataLIF(pkg, user.id, flags);
21650            }
21651        }
21652    }
21653
21654    /**
21655     * Prepare app data for the given app.
21656     * <p>
21657     * Verifies that directories exist and that ownership and labeling is
21658     * correct for all installed apps. If there is an ownership mismatch, this
21659     * will try recovering system apps by wiping data; third-party app data is
21660     * left intact.
21661     */
21662    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21663        if (pkg == null) {
21664            Slog.wtf(TAG, "Package was null!", new Throwable());
21665            return;
21666        }
21667        prepareAppDataLeafLIF(pkg, userId, flags);
21668        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21669        for (int i = 0; i < childCount; i++) {
21670            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21671        }
21672    }
21673
21674    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21675        if (DEBUG_APP_DATA) {
21676            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21677                    + Integer.toHexString(flags));
21678        }
21679
21680        final String volumeUuid = pkg.volumeUuid;
21681        final String packageName = pkg.packageName;
21682        final ApplicationInfo app = pkg.applicationInfo;
21683        final int appId = UserHandle.getAppId(app.uid);
21684
21685        Preconditions.checkNotNull(app.seinfo);
21686
21687        long ceDataInode = -1;
21688        try {
21689            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21690                    appId, app.seinfo, app.targetSdkVersion);
21691        } catch (InstallerException e) {
21692            if (app.isSystemApp()) {
21693                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21694                        + ", but trying to recover: " + e);
21695                destroyAppDataLeafLIF(pkg, userId, flags);
21696                try {
21697                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21698                            appId, app.seinfo, app.targetSdkVersion);
21699                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21700                } catch (InstallerException e2) {
21701                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21702                }
21703            } else {
21704                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21705            }
21706        }
21707
21708        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21709            // TODO: mark this structure as dirty so we persist it!
21710            synchronized (mPackages) {
21711                final PackageSetting ps = mSettings.mPackages.get(packageName);
21712                if (ps != null) {
21713                    ps.setCeDataInode(ceDataInode, userId);
21714                }
21715            }
21716        }
21717
21718        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21719    }
21720
21721    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21722        if (pkg == null) {
21723            Slog.wtf(TAG, "Package was null!", new Throwable());
21724            return;
21725        }
21726        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21727        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21728        for (int i = 0; i < childCount; i++) {
21729            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21730        }
21731    }
21732
21733    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21734        final String volumeUuid = pkg.volumeUuid;
21735        final String packageName = pkg.packageName;
21736        final ApplicationInfo app = pkg.applicationInfo;
21737
21738        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21739            // Create a native library symlink only if we have native libraries
21740            // and if the native libraries are 32 bit libraries. We do not provide
21741            // this symlink for 64 bit libraries.
21742            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21743                final String nativeLibPath = app.nativeLibraryDir;
21744                try {
21745                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21746                            nativeLibPath, userId);
21747                } catch (InstallerException e) {
21748                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21749                }
21750            }
21751        }
21752    }
21753
21754    /**
21755     * For system apps on non-FBE devices, this method migrates any existing
21756     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21757     * requested by the app.
21758     */
21759    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21760        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21761                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21762            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21763                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21764            try {
21765                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21766                        storageTarget);
21767            } catch (InstallerException e) {
21768                logCriticalInfo(Log.WARN,
21769                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21770            }
21771            return true;
21772        } else {
21773            return false;
21774        }
21775    }
21776
21777    public PackageFreezer freezePackage(String packageName, String killReason) {
21778        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21779    }
21780
21781    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21782        return new PackageFreezer(packageName, userId, killReason);
21783    }
21784
21785    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21786            String killReason) {
21787        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21788    }
21789
21790    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21791            String killReason) {
21792        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21793            return new PackageFreezer();
21794        } else {
21795            return freezePackage(packageName, userId, killReason);
21796        }
21797    }
21798
21799    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21800            String killReason) {
21801        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21802    }
21803
21804    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21805            String killReason) {
21806        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21807            return new PackageFreezer();
21808        } else {
21809            return freezePackage(packageName, userId, killReason);
21810        }
21811    }
21812
21813    /**
21814     * Class that freezes and kills the given package upon creation, and
21815     * unfreezes it upon closing. This is typically used when doing surgery on
21816     * app code/data to prevent the app from running while you're working.
21817     */
21818    private class PackageFreezer implements AutoCloseable {
21819        private final String mPackageName;
21820        private final PackageFreezer[] mChildren;
21821
21822        private final boolean mWeFroze;
21823
21824        private final AtomicBoolean mClosed = new AtomicBoolean();
21825        private final CloseGuard mCloseGuard = CloseGuard.get();
21826
21827        /**
21828         * Create and return a stub freezer that doesn't actually do anything,
21829         * typically used when someone requested
21830         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21831         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21832         */
21833        public PackageFreezer() {
21834            mPackageName = null;
21835            mChildren = null;
21836            mWeFroze = false;
21837            mCloseGuard.open("close");
21838        }
21839
21840        public PackageFreezer(String packageName, int userId, String killReason) {
21841            synchronized (mPackages) {
21842                mPackageName = packageName;
21843                mWeFroze = mFrozenPackages.add(mPackageName);
21844
21845                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21846                if (ps != null) {
21847                    killApplication(ps.name, ps.appId, userId, killReason);
21848                }
21849
21850                final PackageParser.Package p = mPackages.get(packageName);
21851                if (p != null && p.childPackages != null) {
21852                    final int N = p.childPackages.size();
21853                    mChildren = new PackageFreezer[N];
21854                    for (int i = 0; i < N; i++) {
21855                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21856                                userId, killReason);
21857                    }
21858                } else {
21859                    mChildren = null;
21860                }
21861            }
21862            mCloseGuard.open("close");
21863        }
21864
21865        @Override
21866        protected void finalize() throws Throwable {
21867            try {
21868                mCloseGuard.warnIfOpen();
21869                close();
21870            } finally {
21871                super.finalize();
21872            }
21873        }
21874
21875        @Override
21876        public void close() {
21877            mCloseGuard.close();
21878            if (mClosed.compareAndSet(false, true)) {
21879                synchronized (mPackages) {
21880                    if (mWeFroze) {
21881                        mFrozenPackages.remove(mPackageName);
21882                    }
21883
21884                    if (mChildren != null) {
21885                        for (PackageFreezer freezer : mChildren) {
21886                            freezer.close();
21887                        }
21888                    }
21889                }
21890            }
21891        }
21892    }
21893
21894    /**
21895     * Verify that given package is currently frozen.
21896     */
21897    private void checkPackageFrozen(String packageName) {
21898        synchronized (mPackages) {
21899            if (!mFrozenPackages.contains(packageName)) {
21900                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21901            }
21902        }
21903    }
21904
21905    @Override
21906    public int movePackage(final String packageName, final String volumeUuid) {
21907        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21908
21909        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21910        final int moveId = mNextMoveId.getAndIncrement();
21911        mHandler.post(new Runnable() {
21912            @Override
21913            public void run() {
21914                try {
21915                    movePackageInternal(packageName, volumeUuid, moveId, user);
21916                } catch (PackageManagerException e) {
21917                    Slog.w(TAG, "Failed to move " + packageName, e);
21918                    mMoveCallbacks.notifyStatusChanged(moveId,
21919                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21920                }
21921            }
21922        });
21923        return moveId;
21924    }
21925
21926    private void movePackageInternal(final String packageName, final String volumeUuid,
21927            final int moveId, UserHandle user) throws PackageManagerException {
21928        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21929        final PackageManager pm = mContext.getPackageManager();
21930
21931        final boolean currentAsec;
21932        final String currentVolumeUuid;
21933        final File codeFile;
21934        final String installerPackageName;
21935        final String packageAbiOverride;
21936        final int appId;
21937        final String seinfo;
21938        final String label;
21939        final int targetSdkVersion;
21940        final PackageFreezer freezer;
21941        final int[] installedUserIds;
21942
21943        // reader
21944        synchronized (mPackages) {
21945            final PackageParser.Package pkg = mPackages.get(packageName);
21946            final PackageSetting ps = mSettings.mPackages.get(packageName);
21947            if (pkg == null || ps == null) {
21948                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21949            }
21950
21951            if (pkg.applicationInfo.isSystemApp()) {
21952                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21953                        "Cannot move system application");
21954            }
21955
21956            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21957            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21958                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21959            if (isInternalStorage && !allow3rdPartyOnInternal) {
21960                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21961                        "3rd party apps are not allowed on internal storage");
21962            }
21963
21964            if (pkg.applicationInfo.isExternalAsec()) {
21965                currentAsec = true;
21966                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21967            } else if (pkg.applicationInfo.isForwardLocked()) {
21968                currentAsec = true;
21969                currentVolumeUuid = "forward_locked";
21970            } else {
21971                currentAsec = false;
21972                currentVolumeUuid = ps.volumeUuid;
21973
21974                final File probe = new File(pkg.codePath);
21975                final File probeOat = new File(probe, "oat");
21976                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21977                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21978                            "Move only supported for modern cluster style installs");
21979                }
21980            }
21981
21982            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21983                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21984                        "Package already moved to " + volumeUuid);
21985            }
21986            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21987                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21988                        "Device admin cannot be moved");
21989            }
21990
21991            if (mFrozenPackages.contains(packageName)) {
21992                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21993                        "Failed to move already frozen package");
21994            }
21995
21996            codeFile = new File(pkg.codePath);
21997            installerPackageName = ps.installerPackageName;
21998            packageAbiOverride = ps.cpuAbiOverrideString;
21999            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22000            seinfo = pkg.applicationInfo.seinfo;
22001            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22002            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22003            freezer = freezePackage(packageName, "movePackageInternal");
22004            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22005        }
22006
22007        final Bundle extras = new Bundle();
22008        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22009        extras.putString(Intent.EXTRA_TITLE, label);
22010        mMoveCallbacks.notifyCreated(moveId, extras);
22011
22012        int installFlags;
22013        final boolean moveCompleteApp;
22014        final File measurePath;
22015
22016        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22017            installFlags = INSTALL_INTERNAL;
22018            moveCompleteApp = !currentAsec;
22019            measurePath = Environment.getDataAppDirectory(volumeUuid);
22020        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22021            installFlags = INSTALL_EXTERNAL;
22022            moveCompleteApp = false;
22023            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22024        } else {
22025            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22026            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22027                    || !volume.isMountedWritable()) {
22028                freezer.close();
22029                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22030                        "Move location not mounted private volume");
22031            }
22032
22033            Preconditions.checkState(!currentAsec);
22034
22035            installFlags = INSTALL_INTERNAL;
22036            moveCompleteApp = true;
22037            measurePath = Environment.getDataAppDirectory(volumeUuid);
22038        }
22039
22040        final PackageStats stats = new PackageStats(null, -1);
22041        synchronized (mInstaller) {
22042            for (int userId : installedUserIds) {
22043                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22044                    freezer.close();
22045                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22046                            "Failed to measure package size");
22047                }
22048            }
22049        }
22050
22051        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22052                + stats.dataSize);
22053
22054        final long startFreeBytes = measurePath.getFreeSpace();
22055        final long sizeBytes;
22056        if (moveCompleteApp) {
22057            sizeBytes = stats.codeSize + stats.dataSize;
22058        } else {
22059            sizeBytes = stats.codeSize;
22060        }
22061
22062        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22063            freezer.close();
22064            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22065                    "Not enough free space to move");
22066        }
22067
22068        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22069
22070        final CountDownLatch installedLatch = new CountDownLatch(1);
22071        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22072            @Override
22073            public void onUserActionRequired(Intent intent) throws RemoteException {
22074                throw new IllegalStateException();
22075            }
22076
22077            @Override
22078            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22079                    Bundle extras) throws RemoteException {
22080                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22081                        + PackageManager.installStatusToString(returnCode, msg));
22082
22083                installedLatch.countDown();
22084                freezer.close();
22085
22086                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22087                switch (status) {
22088                    case PackageInstaller.STATUS_SUCCESS:
22089                        mMoveCallbacks.notifyStatusChanged(moveId,
22090                                PackageManager.MOVE_SUCCEEDED);
22091                        break;
22092                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22093                        mMoveCallbacks.notifyStatusChanged(moveId,
22094                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22095                        break;
22096                    default:
22097                        mMoveCallbacks.notifyStatusChanged(moveId,
22098                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22099                        break;
22100                }
22101            }
22102        };
22103
22104        final MoveInfo move;
22105        if (moveCompleteApp) {
22106            // Kick off a thread to report progress estimates
22107            new Thread() {
22108                @Override
22109                public void run() {
22110                    while (true) {
22111                        try {
22112                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22113                                break;
22114                            }
22115                        } catch (InterruptedException ignored) {
22116                        }
22117
22118                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22119                        final int progress = 10 + (int) MathUtils.constrain(
22120                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22121                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22122                    }
22123                }
22124            }.start();
22125
22126            final String dataAppName = codeFile.getName();
22127            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22128                    dataAppName, appId, seinfo, targetSdkVersion);
22129        } else {
22130            move = null;
22131        }
22132
22133        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22134
22135        final Message msg = mHandler.obtainMessage(INIT_COPY);
22136        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22137        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22138                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22139                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22140                PackageManager.INSTALL_REASON_UNKNOWN);
22141        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22142        msg.obj = params;
22143
22144        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22145                System.identityHashCode(msg.obj));
22146        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22147                System.identityHashCode(msg.obj));
22148
22149        mHandler.sendMessage(msg);
22150    }
22151
22152    @Override
22153    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22154        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22155
22156        final int realMoveId = mNextMoveId.getAndIncrement();
22157        final Bundle extras = new Bundle();
22158        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22159        mMoveCallbacks.notifyCreated(realMoveId, extras);
22160
22161        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22162            @Override
22163            public void onCreated(int moveId, Bundle extras) {
22164                // Ignored
22165            }
22166
22167            @Override
22168            public void onStatusChanged(int moveId, int status, long estMillis) {
22169                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22170            }
22171        };
22172
22173        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22174        storage.setPrimaryStorageUuid(volumeUuid, callback);
22175        return realMoveId;
22176    }
22177
22178    @Override
22179    public int getMoveStatus(int moveId) {
22180        mContext.enforceCallingOrSelfPermission(
22181                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22182        return mMoveCallbacks.mLastStatus.get(moveId);
22183    }
22184
22185    @Override
22186    public void registerMoveCallback(IPackageMoveObserver callback) {
22187        mContext.enforceCallingOrSelfPermission(
22188                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22189        mMoveCallbacks.register(callback);
22190    }
22191
22192    @Override
22193    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22194        mContext.enforceCallingOrSelfPermission(
22195                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22196        mMoveCallbacks.unregister(callback);
22197    }
22198
22199    @Override
22200    public boolean setInstallLocation(int loc) {
22201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22202                null);
22203        if (getInstallLocation() == loc) {
22204            return true;
22205        }
22206        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22207                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22208            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22209                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22210            return true;
22211        }
22212        return false;
22213   }
22214
22215    @Override
22216    public int getInstallLocation() {
22217        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22218                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22219                PackageHelper.APP_INSTALL_AUTO);
22220    }
22221
22222    /** Called by UserManagerService */
22223    void cleanUpUser(UserManagerService userManager, int userHandle) {
22224        synchronized (mPackages) {
22225            mDirtyUsers.remove(userHandle);
22226            mUserNeedsBadging.delete(userHandle);
22227            mSettings.removeUserLPw(userHandle);
22228            mPendingBroadcasts.remove(userHandle);
22229            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
22230            removeUnusedPackagesLPw(userManager, userHandle);
22231        }
22232    }
22233
22234    /**
22235     * We're removing userHandle and would like to remove any downloaded packages
22236     * that are no longer in use by any other user.
22237     * @param userHandle the user being removed
22238     */
22239    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22240        final boolean DEBUG_CLEAN_APKS = false;
22241        int [] users = userManager.getUserIds();
22242        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22243        while (psit.hasNext()) {
22244            PackageSetting ps = psit.next();
22245            if (ps.pkg == null) {
22246                continue;
22247            }
22248            final String packageName = ps.pkg.packageName;
22249            // Skip over if system app
22250            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22251                continue;
22252            }
22253            if (DEBUG_CLEAN_APKS) {
22254                Slog.i(TAG, "Checking package " + packageName);
22255            }
22256            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22257            if (keep) {
22258                if (DEBUG_CLEAN_APKS) {
22259                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22260                }
22261            } else {
22262                for (int i = 0; i < users.length; i++) {
22263                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22264                        keep = true;
22265                        if (DEBUG_CLEAN_APKS) {
22266                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22267                                    + users[i]);
22268                        }
22269                        break;
22270                    }
22271                }
22272            }
22273            if (!keep) {
22274                if (DEBUG_CLEAN_APKS) {
22275                    Slog.i(TAG, "  Removing package " + packageName);
22276                }
22277                mHandler.post(new Runnable() {
22278                    public void run() {
22279                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22280                                userHandle, 0);
22281                    } //end run
22282                });
22283            }
22284        }
22285    }
22286
22287    /** Called by UserManagerService */
22288    void createNewUser(int userId, String[] disallowedPackages) {
22289        synchronized (mInstallLock) {
22290            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22291        }
22292        synchronized (mPackages) {
22293            scheduleWritePackageRestrictionsLocked(userId);
22294            scheduleWritePackageListLocked(userId);
22295            applyFactoryDefaultBrowserLPw(userId);
22296            primeDomainVerificationsLPw(userId);
22297        }
22298    }
22299
22300    void onNewUserCreated(final int userId) {
22301        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22302        // If permission review for legacy apps is required, we represent
22303        // dagerous permissions for such apps as always granted runtime
22304        // permissions to keep per user flag state whether review is needed.
22305        // Hence, if a new user is added we have to propagate dangerous
22306        // permission grants for these legacy apps.
22307        if (mPermissionReviewRequired) {
22308            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22309                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22310        }
22311    }
22312
22313    @Override
22314    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22315        mContext.enforceCallingOrSelfPermission(
22316                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22317                "Only package verification agents can read the verifier device identity");
22318
22319        synchronized (mPackages) {
22320            return mSettings.getVerifierDeviceIdentityLPw();
22321        }
22322    }
22323
22324    @Override
22325    public void setPermissionEnforced(String permission, boolean enforced) {
22326        // TODO: Now that we no longer change GID for storage, this should to away.
22327        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22328                "setPermissionEnforced");
22329        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22330            synchronized (mPackages) {
22331                if (mSettings.mReadExternalStorageEnforced == null
22332                        || mSettings.mReadExternalStorageEnforced != enforced) {
22333                    mSettings.mReadExternalStorageEnforced = enforced;
22334                    mSettings.writeLPr();
22335                }
22336            }
22337            // kill any non-foreground processes so we restart them and
22338            // grant/revoke the GID.
22339            final IActivityManager am = ActivityManager.getService();
22340            if (am != null) {
22341                final long token = Binder.clearCallingIdentity();
22342                try {
22343                    am.killProcessesBelowForeground("setPermissionEnforcement");
22344                } catch (RemoteException e) {
22345                } finally {
22346                    Binder.restoreCallingIdentity(token);
22347                }
22348            }
22349        } else {
22350            throw new IllegalArgumentException("No selective enforcement for " + permission);
22351        }
22352    }
22353
22354    @Override
22355    @Deprecated
22356    public boolean isPermissionEnforced(String permission) {
22357        return true;
22358    }
22359
22360    @Override
22361    public boolean isStorageLow() {
22362        final long token = Binder.clearCallingIdentity();
22363        try {
22364            final DeviceStorageMonitorInternal
22365                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22366            if (dsm != null) {
22367                return dsm.isMemoryLow();
22368            } else {
22369                return false;
22370            }
22371        } finally {
22372            Binder.restoreCallingIdentity(token);
22373        }
22374    }
22375
22376    @Override
22377    public IPackageInstaller getPackageInstaller() {
22378        return mInstallerService;
22379    }
22380
22381    private boolean userNeedsBadging(int userId) {
22382        int index = mUserNeedsBadging.indexOfKey(userId);
22383        if (index < 0) {
22384            final UserInfo userInfo;
22385            final long token = Binder.clearCallingIdentity();
22386            try {
22387                userInfo = sUserManager.getUserInfo(userId);
22388            } finally {
22389                Binder.restoreCallingIdentity(token);
22390            }
22391            final boolean b;
22392            if (userInfo != null && userInfo.isManagedProfile()) {
22393                b = true;
22394            } else {
22395                b = false;
22396            }
22397            mUserNeedsBadging.put(userId, b);
22398            return b;
22399        }
22400        return mUserNeedsBadging.valueAt(index);
22401    }
22402
22403    @Override
22404    public KeySet getKeySetByAlias(String packageName, String alias) {
22405        if (packageName == null || alias == null) {
22406            return null;
22407        }
22408        synchronized(mPackages) {
22409            final PackageParser.Package pkg = mPackages.get(packageName);
22410            if (pkg == null) {
22411                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22412                throw new IllegalArgumentException("Unknown package: " + packageName);
22413            }
22414            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22415            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22416        }
22417    }
22418
22419    @Override
22420    public KeySet getSigningKeySet(String packageName) {
22421        if (packageName == null) {
22422            return null;
22423        }
22424        synchronized(mPackages) {
22425            final PackageParser.Package pkg = mPackages.get(packageName);
22426            if (pkg == null) {
22427                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22428                throw new IllegalArgumentException("Unknown package: " + packageName);
22429            }
22430            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22431                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22432                throw new SecurityException("May not access signing KeySet of other apps.");
22433            }
22434            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22435            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22436        }
22437    }
22438
22439    @Override
22440    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22441        if (packageName == null || ks == null) {
22442            return false;
22443        }
22444        synchronized(mPackages) {
22445            final PackageParser.Package pkg = mPackages.get(packageName);
22446            if (pkg == null) {
22447                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22448                throw new IllegalArgumentException("Unknown package: " + packageName);
22449            }
22450            IBinder ksh = ks.getToken();
22451            if (ksh instanceof KeySetHandle) {
22452                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22453                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22454            }
22455            return false;
22456        }
22457    }
22458
22459    @Override
22460    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22461        if (packageName == null || ks == null) {
22462            return false;
22463        }
22464        synchronized(mPackages) {
22465            final PackageParser.Package pkg = mPackages.get(packageName);
22466            if (pkg == null) {
22467                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22468                throw new IllegalArgumentException("Unknown package: " + packageName);
22469            }
22470            IBinder ksh = ks.getToken();
22471            if (ksh instanceof KeySetHandle) {
22472                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22473                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22474            }
22475            return false;
22476        }
22477    }
22478
22479    private void deletePackageIfUnusedLPr(final String packageName) {
22480        PackageSetting ps = mSettings.mPackages.get(packageName);
22481        if (ps == null) {
22482            return;
22483        }
22484        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22485            // TODO Implement atomic delete if package is unused
22486            // It is currently possible that the package will be deleted even if it is installed
22487            // after this method returns.
22488            mHandler.post(new Runnable() {
22489                public void run() {
22490                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22491                            0, PackageManager.DELETE_ALL_USERS);
22492                }
22493            });
22494        }
22495    }
22496
22497    /**
22498     * Check and throw if the given before/after packages would be considered a
22499     * downgrade.
22500     */
22501    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22502            throws PackageManagerException {
22503        if (after.versionCode < before.mVersionCode) {
22504            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22505                    "Update version code " + after.versionCode + " is older than current "
22506                    + before.mVersionCode);
22507        } else if (after.versionCode == before.mVersionCode) {
22508            if (after.baseRevisionCode < before.baseRevisionCode) {
22509                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22510                        "Update base revision code " + after.baseRevisionCode
22511                        + " is older than current " + before.baseRevisionCode);
22512            }
22513
22514            if (!ArrayUtils.isEmpty(after.splitNames)) {
22515                for (int i = 0; i < after.splitNames.length; i++) {
22516                    final String splitName = after.splitNames[i];
22517                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22518                    if (j != -1) {
22519                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22520                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22521                                    "Update split " + splitName + " revision code "
22522                                    + after.splitRevisionCodes[i] + " is older than current "
22523                                    + before.splitRevisionCodes[j]);
22524                        }
22525                    }
22526                }
22527            }
22528        }
22529    }
22530
22531    private static class MoveCallbacks extends Handler {
22532        private static final int MSG_CREATED = 1;
22533        private static final int MSG_STATUS_CHANGED = 2;
22534
22535        private final RemoteCallbackList<IPackageMoveObserver>
22536                mCallbacks = new RemoteCallbackList<>();
22537
22538        private final SparseIntArray mLastStatus = new SparseIntArray();
22539
22540        public MoveCallbacks(Looper looper) {
22541            super(looper);
22542        }
22543
22544        public void register(IPackageMoveObserver callback) {
22545            mCallbacks.register(callback);
22546        }
22547
22548        public void unregister(IPackageMoveObserver callback) {
22549            mCallbacks.unregister(callback);
22550        }
22551
22552        @Override
22553        public void handleMessage(Message msg) {
22554            final SomeArgs args = (SomeArgs) msg.obj;
22555            final int n = mCallbacks.beginBroadcast();
22556            for (int i = 0; i < n; i++) {
22557                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22558                try {
22559                    invokeCallback(callback, msg.what, args);
22560                } catch (RemoteException ignored) {
22561                }
22562            }
22563            mCallbacks.finishBroadcast();
22564            args.recycle();
22565        }
22566
22567        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22568                throws RemoteException {
22569            switch (what) {
22570                case MSG_CREATED: {
22571                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22572                    break;
22573                }
22574                case MSG_STATUS_CHANGED: {
22575                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22576                    break;
22577                }
22578            }
22579        }
22580
22581        private void notifyCreated(int moveId, Bundle extras) {
22582            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22583
22584            final SomeArgs args = SomeArgs.obtain();
22585            args.argi1 = moveId;
22586            args.arg2 = extras;
22587            obtainMessage(MSG_CREATED, args).sendToTarget();
22588        }
22589
22590        private void notifyStatusChanged(int moveId, int status) {
22591            notifyStatusChanged(moveId, status, -1);
22592        }
22593
22594        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22595            Slog.v(TAG, "Move " + moveId + " status " + status);
22596
22597            final SomeArgs args = SomeArgs.obtain();
22598            args.argi1 = moveId;
22599            args.argi2 = status;
22600            args.arg3 = estMillis;
22601            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22602
22603            synchronized (mLastStatus) {
22604                mLastStatus.put(moveId, status);
22605            }
22606        }
22607    }
22608
22609    private final static class OnPermissionChangeListeners extends Handler {
22610        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22611
22612        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22613                new RemoteCallbackList<>();
22614
22615        public OnPermissionChangeListeners(Looper looper) {
22616            super(looper);
22617        }
22618
22619        @Override
22620        public void handleMessage(Message msg) {
22621            switch (msg.what) {
22622                case MSG_ON_PERMISSIONS_CHANGED: {
22623                    final int uid = msg.arg1;
22624                    handleOnPermissionsChanged(uid);
22625                } break;
22626            }
22627        }
22628
22629        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22630            mPermissionListeners.register(listener);
22631
22632        }
22633
22634        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22635            mPermissionListeners.unregister(listener);
22636        }
22637
22638        public void onPermissionsChanged(int uid) {
22639            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22640                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22641            }
22642        }
22643
22644        private void handleOnPermissionsChanged(int uid) {
22645            final int count = mPermissionListeners.beginBroadcast();
22646            try {
22647                for (int i = 0; i < count; i++) {
22648                    IOnPermissionsChangeListener callback = mPermissionListeners
22649                            .getBroadcastItem(i);
22650                    try {
22651                        callback.onPermissionsChanged(uid);
22652                    } catch (RemoteException e) {
22653                        Log.e(TAG, "Permission listener is dead", e);
22654                    }
22655                }
22656            } finally {
22657                mPermissionListeners.finishBroadcast();
22658            }
22659        }
22660    }
22661
22662    private class PackageManagerInternalImpl extends PackageManagerInternal {
22663        @Override
22664        public void setLocationPackagesProvider(PackagesProvider provider) {
22665            synchronized (mPackages) {
22666                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22667            }
22668        }
22669
22670        @Override
22671        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22672            synchronized (mPackages) {
22673                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22674            }
22675        }
22676
22677        @Override
22678        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22679            synchronized (mPackages) {
22680                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22681            }
22682        }
22683
22684        @Override
22685        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22686            synchronized (mPackages) {
22687                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22688            }
22689        }
22690
22691        @Override
22692        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22693            synchronized (mPackages) {
22694                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22695            }
22696        }
22697
22698        @Override
22699        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22700            synchronized (mPackages) {
22701                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22702            }
22703        }
22704
22705        @Override
22706        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22707            synchronized (mPackages) {
22708                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22709                        packageName, userId);
22710            }
22711        }
22712
22713        @Override
22714        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22715            synchronized (mPackages) {
22716                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22717                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22718                        packageName, userId);
22719            }
22720        }
22721
22722        @Override
22723        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22724            synchronized (mPackages) {
22725                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22726                        packageName, userId);
22727            }
22728        }
22729
22730        @Override
22731        public void setKeepUninstalledPackages(final List<String> packageList) {
22732            Preconditions.checkNotNull(packageList);
22733            List<String> removedFromList = null;
22734            synchronized (mPackages) {
22735                if (mKeepUninstalledPackages != null) {
22736                    final int packagesCount = mKeepUninstalledPackages.size();
22737                    for (int i = 0; i < packagesCount; i++) {
22738                        String oldPackage = mKeepUninstalledPackages.get(i);
22739                        if (packageList != null && packageList.contains(oldPackage)) {
22740                            continue;
22741                        }
22742                        if (removedFromList == null) {
22743                            removedFromList = new ArrayList<>();
22744                        }
22745                        removedFromList.add(oldPackage);
22746                    }
22747                }
22748                mKeepUninstalledPackages = new ArrayList<>(packageList);
22749                if (removedFromList != null) {
22750                    final int removedCount = removedFromList.size();
22751                    for (int i = 0; i < removedCount; i++) {
22752                        deletePackageIfUnusedLPr(removedFromList.get(i));
22753                    }
22754                }
22755            }
22756        }
22757
22758        @Override
22759        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22760            synchronized (mPackages) {
22761                // If we do not support permission review, done.
22762                if (!mPermissionReviewRequired) {
22763                    return false;
22764                }
22765
22766                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22767                if (packageSetting == null) {
22768                    return false;
22769                }
22770
22771                // Permission review applies only to apps not supporting the new permission model.
22772                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22773                    return false;
22774                }
22775
22776                // Legacy apps have the permission and get user consent on launch.
22777                PermissionsState permissionsState = packageSetting.getPermissionsState();
22778                return permissionsState.isPermissionReviewRequired(userId);
22779            }
22780        }
22781
22782        @Override
22783        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22784            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22785        }
22786
22787        @Override
22788        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22789                int userId) {
22790            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22791        }
22792
22793        @Override
22794        public void setDeviceAndProfileOwnerPackages(
22795                int deviceOwnerUserId, String deviceOwnerPackage,
22796                SparseArray<String> profileOwnerPackages) {
22797            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22798                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22799        }
22800
22801        @Override
22802        public boolean isPackageDataProtected(int userId, String packageName) {
22803            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22804        }
22805
22806        @Override
22807        public boolean isPackageEphemeral(int userId, String packageName) {
22808            synchronized (mPackages) {
22809                PackageParser.Package p = mPackages.get(packageName);
22810                return p != null ? p.applicationInfo.isEphemeralApp() : false;
22811            }
22812        }
22813
22814        @Override
22815        public boolean wasPackageEverLaunched(String packageName, int userId) {
22816            synchronized (mPackages) {
22817                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22818            }
22819        }
22820
22821        @Override
22822        public void grantRuntimePermission(String packageName, String name, int userId,
22823                boolean overridePolicy) {
22824            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22825                    overridePolicy);
22826        }
22827
22828        @Override
22829        public void revokeRuntimePermission(String packageName, String name, int userId,
22830                boolean overridePolicy) {
22831            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22832                    overridePolicy);
22833        }
22834
22835        @Override
22836        public String getNameForUid(int uid) {
22837            return PackageManagerService.this.getNameForUid(uid);
22838        }
22839
22840        @Override
22841        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22842                Intent origIntent, String resolvedType, Intent launchIntent,
22843                String callingPackage, int userId) {
22844            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22845                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22846        }
22847
22848        @Override
22849        public void grantEphemeralAccess(int userId, Intent intent,
22850                int targetAppId, int ephemeralAppId) {
22851            synchronized (mPackages) {
22852                mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent,
22853                        targetAppId, ephemeralAppId);
22854            }
22855        }
22856
22857        public String getSetupWizardPackageName() {
22858            return mSetupWizardPackage;
22859        }
22860
22861        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22862            if (policy != null) {
22863                mExternalSourcesPolicy = policy;
22864            }
22865        }
22866    }
22867
22868    @Override
22869    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22870        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22871        synchronized (mPackages) {
22872            final long identity = Binder.clearCallingIdentity();
22873            try {
22874                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22875                        packageNames, userId);
22876            } finally {
22877                Binder.restoreCallingIdentity(identity);
22878            }
22879        }
22880    }
22881
22882    private static void enforceSystemOrPhoneCaller(String tag) {
22883        int callingUid = Binder.getCallingUid();
22884        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22885            throw new SecurityException(
22886                    "Cannot call " + tag + " from UID " + callingUid);
22887        }
22888    }
22889
22890    boolean isHistoricalPackageUsageAvailable() {
22891        return mPackageUsage.isHistoricalPackageUsageAvailable();
22892    }
22893
22894    /**
22895     * Return a <b>copy</b> of the collection of packages known to the package manager.
22896     * @return A copy of the values of mPackages.
22897     */
22898    Collection<PackageParser.Package> getPackages() {
22899        synchronized (mPackages) {
22900            return new ArrayList<>(mPackages.values());
22901        }
22902    }
22903
22904    /**
22905     * Logs process start information (including base APK hash) to the security log.
22906     * @hide
22907     */
22908    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22909            String apkFile, int pid) {
22910        if (!SecurityLog.isLoggingEnabled()) {
22911            return;
22912        }
22913        Bundle data = new Bundle();
22914        data.putLong("startTimestamp", System.currentTimeMillis());
22915        data.putString("processName", processName);
22916        data.putInt("uid", uid);
22917        data.putString("seinfo", seinfo);
22918        data.putString("apkFile", apkFile);
22919        data.putInt("pid", pid);
22920        Message msg = mProcessLoggingHandler.obtainMessage(
22921                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22922        msg.setData(data);
22923        mProcessLoggingHandler.sendMessage(msg);
22924    }
22925
22926    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22927        return mCompilerStats.getPackageStats(pkgName);
22928    }
22929
22930    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22931        return getOrCreateCompilerPackageStats(pkg.packageName);
22932    }
22933
22934    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22935        return mCompilerStats.getOrCreatePackageStats(pkgName);
22936    }
22937
22938    public void deleteCompilerPackageStats(String pkgName) {
22939        mCompilerStats.deletePackageStats(pkgName);
22940    }
22941
22942    @Override
22943    public int getInstallReason(String packageName, int userId) {
22944        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22945                true /* requireFullPermission */, false /* checkShell */,
22946                "get install reason");
22947        synchronized (mPackages) {
22948            final PackageSetting ps = mSettings.mPackages.get(packageName);
22949            if (ps != null) {
22950                return ps.getInstallReason(userId);
22951            }
22952        }
22953        return PackageManager.INSTALL_REASON_UNKNOWN;
22954    }
22955
22956    @Override
22957    public boolean canRequestPackageInstalls(String packageName, int userId) {
22958        int callingUid = Binder.getCallingUid();
22959        int uid = getPackageUid(packageName, 0, userId);
22960        if (callingUid != uid && callingUid != Process.ROOT_UID
22961                && callingUid != Process.SYSTEM_UID) {
22962            throw new SecurityException(
22963                    "Caller uid " + callingUid + " does not own package " + packageName);
22964        }
22965        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22966        if (info == null) {
22967            return false;
22968        }
22969        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22970            throw new UnsupportedOperationException(
22971                    "Operation only supported on apps targeting Android O or higher");
22972        }
22973        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22974        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22975        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22976            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22977        }
22978        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22979            return false;
22980        }
22981        if (mExternalSourcesPolicy != null) {
22982            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22983            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22984                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22985            }
22986        }
22987        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
22988    }
22989}
22990