PackageManagerService.java revision 964d2ebb94c41d2cf1fb45b534e86c10e0ced3ac
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.IActivityManager;
105import android.app.ResourcesManager;
106import android.app.admin.IDevicePolicyManager;
107import android.app.admin.SecurityLog;
108import android.app.backup.IBackupManager;
109import android.content.BroadcastReceiver;
110import android.content.ComponentName;
111import android.content.ContentResolver;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralIntentFilter;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.PatternMatcher;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.ShellCallback;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.provider.Settings.Secure;
203import android.security.KeyStore;
204import android.security.SystemKeyStore;
205import android.system.ErrnoException;
206import android.system.Os;
207import android.text.TextUtils;
208import android.text.format.DateUtils;
209import android.util.ArrayMap;
210import android.util.ArraySet;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.Pair;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.RoSystemProperties;
237import com.android.internal.os.SomeArgs;
238import com.android.internal.os.Zygote;
239import com.android.internal.telephony.CarrierAppUtils;
240import com.android.internal.util.ArrayUtils;
241import com.android.internal.util.FastPrintWriter;
242import com.android.internal.util.FastXmlSerializer;
243import com.android.internal.util.IndentingPrintWriter;
244import com.android.internal.util.Preconditions;
245import com.android.internal.util.XmlUtils;
246import com.android.server.AttributeCache;
247import com.android.server.EventLogTags;
248import com.android.server.FgThread;
249import com.android.server.IntentResolver;
250import com.android.server.LocalServices;
251import com.android.server.ServiceThread;
252import com.android.server.SystemConfig;
253import com.android.server.Watchdog;
254import com.android.server.net.NetworkPolicyManagerInternal;
255import com.android.server.pm.PermissionsState.PermissionState;
256import com.android.server.pm.Settings.DatabaseVersion;
257import com.android.server.pm.Settings.VersionInfo;
258import com.android.server.storage.DeviceStorageMonitorInternal;
259
260import dalvik.system.CloseGuard;
261import dalvik.system.DexFile;
262import dalvik.system.VMRuntime;
263
264import libcore.io.IoUtils;
265import libcore.util.EmptyArray;
266
267import org.xmlpull.v1.XmlPullParser;
268import org.xmlpull.v1.XmlPullParserException;
269import org.xmlpull.v1.XmlSerializer;
270
271import java.io.BufferedOutputStream;
272import java.io.BufferedReader;
273import java.io.ByteArrayInputStream;
274import java.io.ByteArrayOutputStream;
275import java.io.File;
276import java.io.FileDescriptor;
277import java.io.FileInputStream;
278import java.io.FileNotFoundException;
279import java.io.FileOutputStream;
280import java.io.FileReader;
281import java.io.FilenameFilter;
282import java.io.IOException;
283import java.io.PrintWriter;
284import java.nio.charset.StandardCharsets;
285import java.security.DigestInputStream;
286import java.security.MessageDigest;
287import java.security.NoSuchAlgorithmException;
288import java.security.PublicKey;
289import java.security.cert.Certificate;
290import java.security.cert.CertificateEncodingException;
291import java.security.cert.CertificateException;
292import java.text.SimpleDateFormat;
293import java.util.ArrayList;
294import java.util.Arrays;
295import java.util.Collection;
296import java.util.Collections;
297import java.util.Comparator;
298import java.util.Date;
299import java.util.HashSet;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309
310/**
311 * Keep track of all those APKs everywhere.
312 * <p>
313 * Internally there are two important locks:
314 * <ul>
315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
316 * and other related state. It is a fine-grained lock that should only be held
317 * momentarily, as it's one of the most contended locks in the system.
318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
319 * operations typically involve heavy lifting of application data on disk. Since
320 * {@code installd} is single-threaded, and it's operations can often be slow,
321 * this lock should never be acquired while already holding {@link #mPackages}.
322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
323 * holding {@link #mInstallLock}.
324 * </ul>
325 * Many internal methods rely on the caller to hold the appropriate locks, and
326 * this contract is expressed through method name suffixes:
327 * <ul>
328 * <li>fooLI(): the caller must hold {@link #mInstallLock}
329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
330 * being modified must be frozen
331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
333 * </ul>
334 * <p>
335 * Because this class is very central to the platform's security; please run all
336 * CTS and unit tests whenever making modifications:
337 *
338 * <pre>
339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
341 * </pre>
342 */
343public class PackageManagerService extends IPackageManager.Stub {
344    static final String TAG = "PackageManager";
345    static final boolean DEBUG_SETTINGS = false;
346    static final boolean DEBUG_PREFERRED = false;
347    static final boolean DEBUG_UPGRADE = false;
348    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
349    private static final boolean DEBUG_BACKUP = false;
350    private static final boolean DEBUG_INSTALL = false;
351    private static final boolean DEBUG_REMOVE = false;
352    private static final boolean DEBUG_BROADCASTS = false;
353    private static final boolean DEBUG_SHOW_INFO = false;
354    private static final boolean DEBUG_PACKAGE_INFO = false;
355    private static final boolean DEBUG_INTENT_MATCHING = false;
356    private static final boolean DEBUG_PACKAGE_SCANNING = false;
357    private static final boolean DEBUG_VERIFY = false;
358    private static final boolean DEBUG_FILTERS = false;
359
360    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
361    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
362    // user, but by default initialize to this.
363    static final boolean DEBUG_DEXOPT = false;
364
365    private static final boolean DEBUG_ABI_SELECTION = false;
366    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
367    private static final boolean DEBUG_TRIAGED_MISSING = false;
368    private static final boolean DEBUG_APP_DATA = false;
369
370    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
371    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
372
373    private static final boolean DISABLE_EPHEMERAL_APPS = false;
374    private static final boolean HIDE_EPHEMERAL_APIS = true;
375
376    private static final int RADIO_UID = Process.PHONE_UID;
377    private static final int LOG_UID = Process.LOG_UID;
378    private static final int NFC_UID = Process.NFC_UID;
379    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
380    private static final int SHELL_UID = Process.SHELL_UID;
381
382    // Cap the size of permission trees that 3rd party apps can define
383    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
384
385    // Suffix used during package installation when copying/moving
386    // package apks to install directory.
387    private static final String INSTALL_PACKAGE_SUFFIX = "-";
388
389    static final int SCAN_NO_DEX = 1<<1;
390    static final int SCAN_FORCE_DEX = 1<<2;
391    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
392    static final int SCAN_NEW_INSTALL = 1<<4;
393    static final int SCAN_NO_PATHS = 1<<5;
394    static final int SCAN_UPDATE_TIME = 1<<6;
395    static final int SCAN_DEFER_DEX = 1<<7;
396    static final int SCAN_BOOTING = 1<<8;
397    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
398    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
399    static final int SCAN_REPLACING = 1<<11;
400    static final int SCAN_REQUIRE_KNOWN = 1<<12;
401    static final int SCAN_MOVE = 1<<13;
402    static final int SCAN_INITIAL = 1<<14;
403    static final int SCAN_CHECK_ONLY = 1<<15;
404    static final int SCAN_DONT_KILL_APP = 1<<17;
405    static final int SCAN_IGNORE_FROZEN = 1<<18;
406
407    static final int REMOVE_CHATTY = 1<<16;
408
409    private static final int[] EMPTY_INT_ARRAY = new int[0];
410
411    /**
412     * Timeout (in milliseconds) after which the watchdog should declare that
413     * our handler thread is wedged.  The usual default for such things is one
414     * minute but we sometimes do very lengthy I/O operations on this thread,
415     * such as installing multi-gigabyte applications, so ours needs to be longer.
416     */
417    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
418
419    /**
420     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
421     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
422     * settings entry if available, otherwise we use the hardcoded default.  If it's been
423     * more than this long since the last fstrim, we force one during the boot sequence.
424     *
425     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
426     * one gets run at the next available charging+idle time.  This final mandatory
427     * no-fstrim check kicks in only of the other scheduling criteria is never met.
428     */
429    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
430
431    /**
432     * Whether verification is enabled by default.
433     */
434    private static final boolean DEFAULT_VERIFY_ENABLE = true;
435
436    /**
437     * The default maximum time to wait for the verification agent to return in
438     * milliseconds.
439     */
440    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
441
442    /**
443     * The default response for package verification timeout.
444     *
445     * This can be either PackageManager.VERIFICATION_ALLOW or
446     * PackageManager.VERIFICATION_REJECT.
447     */
448    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
449
450    static final String PLATFORM_PACKAGE_NAME = "android";
451
452    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
453
454    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
455            DEFAULT_CONTAINER_PACKAGE,
456            "com.android.defcontainer.DefaultContainerService");
457
458    private static final String KILL_APP_REASON_GIDS_CHANGED =
459            "permission grant or revoke changed gids";
460
461    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
462            "permissions revoked";
463
464    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
465
466    private static final String PACKAGE_SCHEME = "package";
467
468    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
469    /**
470     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
471     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
472     * VENDOR_OVERLAY_DIR.
473     */
474    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
475    /**
476     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
477     * is in VENDOR_OVERLAY_THEME_PROPERTY.
478     */
479    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
480            = "persist.vendor.overlay.theme";
481
482    /** Permission grant: not grant the permission. */
483    private static final int GRANT_DENIED = 1;
484
485    /** Permission grant: grant the permission as an install permission. */
486    private static final int GRANT_INSTALL = 2;
487
488    /** Permission grant: grant the permission as a runtime one. */
489    private static final int GRANT_RUNTIME = 3;
490
491    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
492    private static final int GRANT_UPGRADE = 4;
493
494    /** Canonical intent used to identify what counts as a "web browser" app */
495    private static final Intent sBrowserIntent;
496    static {
497        sBrowserIntent = new Intent();
498        sBrowserIntent.setAction(Intent.ACTION_VIEW);
499        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
500        sBrowserIntent.setData(Uri.parse("http:"));
501    }
502
503    /**
504     * The set of all protected actions [i.e. those actions for which a high priority
505     * intent filter is disallowed].
506     */
507    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
508    static {
509        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
510        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
511        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
512        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
513    }
514
515    // Compilation reasons.
516    public static final int REASON_FIRST_BOOT = 0;
517    public static final int REASON_BOOT = 1;
518    public static final int REASON_INSTALL = 2;
519    public static final int REASON_BACKGROUND_DEXOPT = 3;
520    public static final int REASON_AB_OTA = 4;
521    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
522    public static final int REASON_SHARED_APK = 6;
523    public static final int REASON_FORCED_DEXOPT = 7;
524    public static final int REASON_CORE_APP = 8;
525
526    public static final int REASON_LAST = REASON_CORE_APP;
527
528    /** Special library name that skips shared libraries check during compilation. */
529    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
530
531    final ServiceThread mHandlerThread;
532
533    final PackageHandler mHandler;
534
535    private final ProcessLoggingHandler mProcessLoggingHandler;
536
537    /**
538     * Messages for {@link #mHandler} that need to wait for system ready before
539     * being dispatched.
540     */
541    private ArrayList<Message> mPostSystemReadyMessages;
542
543    final int mSdkVersion = Build.VERSION.SDK_INT;
544
545    final Context mContext;
546    final boolean mFactoryTest;
547    final boolean mOnlyCore;
548    final DisplayMetrics mMetrics;
549    final int mDefParseFlags;
550    final String[] mSeparateProcesses;
551    final boolean mIsUpgrade;
552    final boolean mIsPreNUpgrade;
553    final boolean mIsPreNMR1Upgrade;
554
555    @GuardedBy("mPackages")
556    private boolean mDexOptDialogShown;
557
558    /** The location for ASEC container files on internal storage. */
559    final String mAsecInternalPath;
560
561    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
562    // LOCK HELD.  Can be called with mInstallLock held.
563    @GuardedBy("mInstallLock")
564    final Installer mInstaller;
565
566    /** Directory where installed third-party apps stored */
567    final File mAppInstallDir;
568    final File mEphemeralInstallDir;
569
570    /**
571     * Directory to which applications installed internally have their
572     * 32 bit native libraries copied.
573     */
574    private File mAppLib32InstallDir;
575
576    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
577    // apps.
578    final File mDrmAppPrivateInstallDir;
579
580    // ----------------------------------------------------------------
581
582    // Lock for state used when installing and doing other long running
583    // operations.  Methods that must be called with this lock held have
584    // the suffix "LI".
585    final Object mInstallLock = new Object();
586
587    // ----------------------------------------------------------------
588
589    // Keys are String (package name), values are Package.  This also serves
590    // as the lock for the global state.  Methods that must be called with
591    // this lock held have the prefix "LP".
592    @GuardedBy("mPackages")
593    final ArrayMap<String, PackageParser.Package> mPackages =
594            new ArrayMap<String, PackageParser.Package>();
595
596    final ArrayMap<String, Set<String>> mKnownCodebase =
597            new ArrayMap<String, Set<String>>();
598
599    // Tracks available target package names -> overlay package paths.
600    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
601        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
602
603    /**
604     * Tracks new system packages [received in an OTA] that we expect to
605     * find updated user-installed versions. Keys are package name, values
606     * are package location.
607     */
608    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
609    /**
610     * Tracks high priority intent filters for protected actions. During boot, certain
611     * filter actions are protected and should never be allowed to have a high priority
612     * intent filter for them. However, there is one, and only one exception -- the
613     * setup wizard. It must be able to define a high priority intent filter for these
614     * actions to ensure there are no escapes from the wizard. We need to delay processing
615     * of these during boot as we need to look at all of the system packages in order
616     * to know which component is the setup wizard.
617     */
618    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
619    /**
620     * Whether or not processing protected filters should be deferred.
621     */
622    private boolean mDeferProtectedFilters = true;
623
624    /**
625     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
626     */
627    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
628    /**
629     * Whether or not system app permissions should be promoted from install to runtime.
630     */
631    boolean mPromoteSystemApps;
632
633    @GuardedBy("mPackages")
634    final Settings mSettings;
635
636    /**
637     * Set of package names that are currently "frozen", which means active
638     * surgery is being done on the code/data for that package. The platform
639     * will refuse to launch frozen packages to avoid race conditions.
640     *
641     * @see PackageFreezer
642     */
643    @GuardedBy("mPackages")
644    final ArraySet<String> mFrozenPackages = new ArraySet<>();
645
646    final ProtectedPackages mProtectedPackages;
647
648    boolean mFirstBoot;
649
650    // System configuration read by SystemConfig.
651    final int[] mGlobalGids;
652    final SparseArray<ArraySet<String>> mSystemPermissions;
653    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
654
655    // If mac_permissions.xml was found for seinfo labeling.
656    boolean mFoundPolicyFile;
657
658    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
659
660    public static final class SharedLibraryEntry {
661        public final String path;
662        public final String apk;
663
664        SharedLibraryEntry(String _path, String _apk) {
665            path = _path;
666            apk = _apk;
667        }
668    }
669
670    // Currently known shared libraries.
671    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
672            new ArrayMap<String, SharedLibraryEntry>();
673
674    // All available activities, for your resolving pleasure.
675    final ActivityIntentResolver mActivities =
676            new ActivityIntentResolver();
677
678    // All available receivers, for your resolving pleasure.
679    final ActivityIntentResolver mReceivers =
680            new ActivityIntentResolver();
681
682    // All available services, for your resolving pleasure.
683    final ServiceIntentResolver mServices = new ServiceIntentResolver();
684
685    // All available providers, for your resolving pleasure.
686    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
687
688    // Mapping from provider base names (first directory in content URI codePath)
689    // to the provider information.
690    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
691            new ArrayMap<String, PackageParser.Provider>();
692
693    // Mapping from instrumentation class names to info about them.
694    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
695            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
696
697    // Mapping from permission names to info about them.
698    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
699            new ArrayMap<String, PackageParser.PermissionGroup>();
700
701    // Packages whose data we have transfered into another package, thus
702    // should no longer exist.
703    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
704
705    // Broadcast actions that are only available to the system.
706    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
707
708    /** List of packages waiting for verification. */
709    final SparseArray<PackageVerificationState> mPendingVerification
710            = new SparseArray<PackageVerificationState>();
711
712    /** Set of packages associated with each app op permission. */
713    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
714
715    final PackageInstallerService mInstallerService;
716
717    private final PackageDexOptimizer mPackageDexOptimizer;
718
719    private AtomicInteger mNextMoveId = new AtomicInteger();
720    private final MoveCallbacks mMoveCallbacks;
721
722    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
723
724    // Cache of users who need badging.
725    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
726
727    /** Token for keys in mPendingVerification. */
728    private int mPendingVerificationToken = 0;
729
730    volatile boolean mSystemReady;
731    volatile boolean mSafeMode;
732    volatile boolean mHasSystemUidErrors;
733
734    ApplicationInfo mAndroidApplication;
735    final ActivityInfo mResolveActivity = new ActivityInfo();
736    final ResolveInfo mResolveInfo = new ResolveInfo();
737    ComponentName mResolveComponentName;
738    PackageParser.Package mPlatformPackage;
739    ComponentName mCustomResolverComponentName;
740
741    boolean mResolverReplaced = false;
742
743    private final @Nullable ComponentName mIntentFilterVerifierComponent;
744    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
745
746    private int mIntentFilterVerificationToken = 0;
747
748    /** Component that knows whether or not an ephemeral application exists */
749    final ComponentName mEphemeralResolverComponent;
750    /** The service connection to the ephemeral resolver */
751    final EphemeralResolverConnection mEphemeralResolverConnection;
752
753    /** Component used to install ephemeral applications */
754    final ComponentName mEphemeralInstallerComponent;
755    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
756    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
757
758    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
759            = new SparseArray<IntentFilterVerificationState>();
760
761    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
762
763    // List of packages names to keep cached, even if they are uninstalled for all users
764    private List<String> mKeepUninstalledPackages;
765
766    private UserManagerInternal mUserManagerInternal;
767
768    private static class IFVerificationParams {
769        PackageParser.Package pkg;
770        boolean replacing;
771        int userId;
772        int verifierUid;
773
774        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
775                int _userId, int _verifierUid) {
776            pkg = _pkg;
777            replacing = _replacing;
778            userId = _userId;
779            replacing = _replacing;
780            verifierUid = _verifierUid;
781        }
782    }
783
784    private interface IntentFilterVerifier<T extends IntentFilter> {
785        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
786                                               T filter, String packageName);
787        void startVerifications(int userId);
788        void receiveVerificationResponse(int verificationId);
789    }
790
791    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
792        private Context mContext;
793        private ComponentName mIntentFilterVerifierComponent;
794        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
795
796        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
797            mContext = context;
798            mIntentFilterVerifierComponent = verifierComponent;
799        }
800
801        private String getDefaultScheme() {
802            return IntentFilter.SCHEME_HTTPS;
803        }
804
805        @Override
806        public void startVerifications(int userId) {
807            // Launch verifications requests
808            int count = mCurrentIntentFilterVerifications.size();
809            for (int n=0; n<count; n++) {
810                int verificationId = mCurrentIntentFilterVerifications.get(n);
811                final IntentFilterVerificationState ivs =
812                        mIntentFilterVerificationStates.get(verificationId);
813
814                String packageName = ivs.getPackageName();
815
816                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
817                final int filterCount = filters.size();
818                ArraySet<String> domainsSet = new ArraySet<>();
819                for (int m=0; m<filterCount; m++) {
820                    PackageParser.ActivityIntentInfo filter = filters.get(m);
821                    domainsSet.addAll(filter.getHostsList());
822                }
823                synchronized (mPackages) {
824                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
825                            packageName, domainsSet) != null) {
826                        scheduleWriteSettingsLocked();
827                    }
828                }
829                sendVerificationRequest(userId, verificationId, ivs);
830            }
831            mCurrentIntentFilterVerifications.clear();
832        }
833
834        private void sendVerificationRequest(int userId, int verificationId,
835                IntentFilterVerificationState ivs) {
836
837            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
838            verificationIntent.putExtra(
839                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
840                    verificationId);
841            verificationIntent.putExtra(
842                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
843                    getDefaultScheme());
844            verificationIntent.putExtra(
845                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
846                    ivs.getHostsString());
847            verificationIntent.putExtra(
848                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
849                    ivs.getPackageName());
850            verificationIntent.setComponent(mIntentFilterVerifierComponent);
851            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
852
853            UserHandle user = new UserHandle(userId);
854            mContext.sendBroadcastAsUser(verificationIntent, user);
855            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
856                    "Sending IntentFilter verification broadcast");
857        }
858
859        public void receiveVerificationResponse(int verificationId) {
860            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
861
862            final boolean verified = ivs.isVerified();
863
864            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
865            final int count = filters.size();
866            if (DEBUG_DOMAIN_VERIFICATION) {
867                Slog.i(TAG, "Received verification response " + verificationId
868                        + " for " + count + " filters, verified=" + verified);
869            }
870            for (int n=0; n<count; n++) {
871                PackageParser.ActivityIntentInfo filter = filters.get(n);
872                filter.setVerified(verified);
873
874                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
875                        + " verified with result:" + verified + " and hosts:"
876                        + ivs.getHostsString());
877            }
878
879            mIntentFilterVerificationStates.remove(verificationId);
880
881            final String packageName = ivs.getPackageName();
882            IntentFilterVerificationInfo ivi = null;
883
884            synchronized (mPackages) {
885                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
886            }
887            if (ivi == null) {
888                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
889                        + verificationId + " packageName:" + packageName);
890                return;
891            }
892            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
893                    "Updating IntentFilterVerificationInfo for package " + packageName
894                            +" verificationId:" + verificationId);
895
896            synchronized (mPackages) {
897                if (verified) {
898                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
899                } else {
900                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
901                }
902                scheduleWriteSettingsLocked();
903
904                final int userId = ivs.getUserId();
905                if (userId != UserHandle.USER_ALL) {
906                    final int userStatus =
907                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
908
909                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
910                    boolean needUpdate = false;
911
912                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
913                    // already been set by the User thru the Disambiguation dialog
914                    switch (userStatus) {
915                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
916                            if (verified) {
917                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
918                            } else {
919                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
920                            }
921                            needUpdate = true;
922                            break;
923
924                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
925                            if (verified) {
926                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
927                                needUpdate = true;
928                            }
929                            break;
930
931                        default:
932                            // Nothing to do
933                    }
934
935                    if (needUpdate) {
936                        mSettings.updateIntentFilterVerificationStatusLPw(
937                                packageName, updatedStatus, userId);
938                        scheduleWritePackageRestrictionsLocked(userId);
939                    }
940                }
941            }
942        }
943
944        @Override
945        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
946                    ActivityIntentInfo filter, String packageName) {
947            if (!hasValidDomains(filter)) {
948                return false;
949            }
950            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
951            if (ivs == null) {
952                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
953                        packageName);
954            }
955            if (DEBUG_DOMAIN_VERIFICATION) {
956                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
957            }
958            ivs.addFilter(filter);
959            return true;
960        }
961
962        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
963                int userId, int verificationId, String packageName) {
964            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
965                    verifierUid, userId, packageName);
966            ivs.setPendingState();
967            synchronized (mPackages) {
968                mIntentFilterVerificationStates.append(verificationId, ivs);
969                mCurrentIntentFilterVerifications.add(verificationId);
970            }
971            return ivs;
972        }
973    }
974
975    private static boolean hasValidDomains(ActivityIntentInfo filter) {
976        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
977                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
978                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
979    }
980
981    // Set of pending broadcasts for aggregating enable/disable of components.
982    static class PendingPackageBroadcasts {
983        // for each user id, a map of <package name -> components within that package>
984        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
985
986        public PendingPackageBroadcasts() {
987            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
988        }
989
990        public ArrayList<String> get(int userId, String packageName) {
991            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
992            return packages.get(packageName);
993        }
994
995        public void put(int userId, String packageName, ArrayList<String> components) {
996            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
997            packages.put(packageName, components);
998        }
999
1000        public void remove(int userId, String packageName) {
1001            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1002            if (packages != null) {
1003                packages.remove(packageName);
1004            }
1005        }
1006
1007        public void remove(int userId) {
1008            mUidMap.remove(userId);
1009        }
1010
1011        public int userIdCount() {
1012            return mUidMap.size();
1013        }
1014
1015        public int userIdAt(int n) {
1016            return mUidMap.keyAt(n);
1017        }
1018
1019        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1020            return mUidMap.get(userId);
1021        }
1022
1023        public int size() {
1024            // total number of pending broadcast entries across all userIds
1025            int num = 0;
1026            for (int i = 0; i< mUidMap.size(); i++) {
1027                num += mUidMap.valueAt(i).size();
1028            }
1029            return num;
1030        }
1031
1032        public void clear() {
1033            mUidMap.clear();
1034        }
1035
1036        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1037            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1038            if (map == null) {
1039                map = new ArrayMap<String, ArrayList<String>>();
1040                mUidMap.put(userId, map);
1041            }
1042            return map;
1043        }
1044    }
1045    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1046
1047    // Service Connection to remote media container service to copy
1048    // package uri's from external media onto secure containers
1049    // or internal storage.
1050    private IMediaContainerService mContainerService = null;
1051
1052    static final int SEND_PENDING_BROADCAST = 1;
1053    static final int MCS_BOUND = 3;
1054    static final int END_COPY = 4;
1055    static final int INIT_COPY = 5;
1056    static final int MCS_UNBIND = 6;
1057    static final int START_CLEANING_PACKAGE = 7;
1058    static final int FIND_INSTALL_LOC = 8;
1059    static final int POST_INSTALL = 9;
1060    static final int MCS_RECONNECT = 10;
1061    static final int MCS_GIVE_UP = 11;
1062    static final int UPDATED_MEDIA_STATUS = 12;
1063    static final int WRITE_SETTINGS = 13;
1064    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1065    static final int PACKAGE_VERIFIED = 15;
1066    static final int CHECK_PENDING_VERIFICATION = 16;
1067    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1068    static final int INTENT_FILTER_VERIFIED = 18;
1069    static final int WRITE_PACKAGE_LIST = 19;
1070
1071    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1072
1073    // Delay time in millisecs
1074    static final int BROADCAST_DELAY = 10 * 1000;
1075
1076    static UserManagerService sUserManager;
1077
1078    // Stores a list of users whose package restrictions file needs to be updated
1079    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1080
1081    final private DefaultContainerConnection mDefContainerConn =
1082            new DefaultContainerConnection();
1083    class DefaultContainerConnection implements ServiceConnection {
1084        public void onServiceConnected(ComponentName name, IBinder service) {
1085            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1086            final IMediaContainerService imcs = IMediaContainerService.Stub
1087                    .asInterface(Binder.allowBlocking(service));
1088            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1089        }
1090
1091        public void onServiceDisconnected(ComponentName name) {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1093        }
1094    }
1095
1096    // Recordkeeping of restore-after-install operations that are currently in flight
1097    // between the Package Manager and the Backup Manager
1098    static class PostInstallData {
1099        public InstallArgs args;
1100        public PackageInstalledInfo res;
1101
1102        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1103            args = _a;
1104            res = _r;
1105        }
1106    }
1107
1108    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1109    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1110
1111    // XML tags for backup/restore of various bits of state
1112    private static final String TAG_PREFERRED_BACKUP = "pa";
1113    private static final String TAG_DEFAULT_APPS = "da";
1114    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1115
1116    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1117    private static final String TAG_ALL_GRANTS = "rt-grants";
1118    private static final String TAG_GRANT = "grant";
1119    private static final String ATTR_PACKAGE_NAME = "pkg";
1120
1121    private static final String TAG_PERMISSION = "perm";
1122    private static final String ATTR_PERMISSION_NAME = "name";
1123    private static final String ATTR_IS_GRANTED = "g";
1124    private static final String ATTR_USER_SET = "set";
1125    private static final String ATTR_USER_FIXED = "fixed";
1126    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1127
1128    // System/policy permission grants are not backed up
1129    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1130            FLAG_PERMISSION_POLICY_FIXED
1131            | FLAG_PERMISSION_SYSTEM_FIXED
1132            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1133
1134    // And we back up these user-adjusted states
1135    private static final int USER_RUNTIME_GRANT_MASK =
1136            FLAG_PERMISSION_USER_SET
1137            | FLAG_PERMISSION_USER_FIXED
1138            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1139
1140    final @Nullable String mRequiredVerifierPackage;
1141    final @NonNull String mRequiredInstallerPackage;
1142    final @NonNull String mRequiredUninstallerPackage;
1143    final @Nullable String mSetupWizardPackage;
1144    final @Nullable String mStorageManagerPackage;
1145    final @NonNull String mServicesSystemSharedLibraryPackageName;
1146    final @NonNull String mSharedSystemSharedLibraryPackageName;
1147
1148    final boolean mPermissionReviewRequired;
1149
1150    private final PackageUsage mPackageUsage = new PackageUsage();
1151    private final CompilerStats mCompilerStats = new CompilerStats();
1152
1153    class PackageHandler extends Handler {
1154        private boolean mBound = false;
1155        final ArrayList<HandlerParams> mPendingInstalls =
1156            new ArrayList<HandlerParams>();
1157
1158        private boolean connectToService() {
1159            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1160                    " DefaultContainerService");
1161            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1162            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1163            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1164                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1165                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166                mBound = true;
1167                return true;
1168            }
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170            return false;
1171        }
1172
1173        private void disconnectService() {
1174            mContainerService = null;
1175            mBound = false;
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1177            mContext.unbindService(mDefContainerConn);
1178            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1179        }
1180
1181        PackageHandler(Looper looper) {
1182            super(looper);
1183        }
1184
1185        public void handleMessage(Message msg) {
1186            try {
1187                doHandleMessage(msg);
1188            } finally {
1189                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1190            }
1191        }
1192
1193        void doHandleMessage(Message msg) {
1194            switch (msg.what) {
1195                case INIT_COPY: {
1196                    HandlerParams params = (HandlerParams) msg.obj;
1197                    int idx = mPendingInstalls.size();
1198                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1199                    // If a bind was already initiated we dont really
1200                    // need to do anything. The pending install
1201                    // will be processed later on.
1202                    if (!mBound) {
1203                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1204                                System.identityHashCode(mHandler));
1205                        // If this is the only one pending we might
1206                        // have to bind to the service again.
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            params.serviceError();
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                    System.identityHashCode(mHandler));
1212                            if (params.traceMethod != null) {
1213                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1214                                        params.traceCookie);
1215                            }
1216                            return;
1217                        } else {
1218                            // Once we bind to the service, the first
1219                            // pending request will be processed.
1220                            mPendingInstalls.add(idx, params);
1221                        }
1222                    } else {
1223                        mPendingInstalls.add(idx, params);
1224                        // Already bound to the service. Just make
1225                        // sure we trigger off processing the first request.
1226                        if (idx == 0) {
1227                            mHandler.sendEmptyMessage(MCS_BOUND);
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_BOUND: {
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1234                    if (msg.obj != null) {
1235                        mContainerService = (IMediaContainerService) msg.obj;
1236                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1237                                System.identityHashCode(mHandler));
1238                    }
1239                    if (mContainerService == null) {
1240                        if (!mBound) {
1241                            // Something seriously wrong since we are not bound and we are not
1242                            // waiting for connection. Bail out.
1243                            Slog.e(TAG, "Cannot bind to media container service");
1244                            for (HandlerParams params : mPendingInstalls) {
1245                                // Indicate service bind error
1246                                params.serviceError();
1247                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1248                                        System.identityHashCode(params));
1249                                if (params.traceMethod != null) {
1250                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1251                                            params.traceMethod, params.traceCookie);
1252                                }
1253                                return;
1254                            }
1255                            mPendingInstalls.clear();
1256                        } else {
1257                            Slog.w(TAG, "Waiting to connect to media container service");
1258                        }
1259                    } else if (mPendingInstalls.size() > 0) {
1260                        HandlerParams params = mPendingInstalls.get(0);
1261                        if (params != null) {
1262                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1263                                    System.identityHashCode(params));
1264                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1265                            if (params.startCopy()) {
1266                                // We are done...  look for more work or to
1267                                // go idle.
1268                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                        "Checking for more work or unbind...");
1270                                // Delete pending install
1271                                if (mPendingInstalls.size() > 0) {
1272                                    mPendingInstalls.remove(0);
1273                                }
1274                                if (mPendingInstalls.size() == 0) {
1275                                    if (mBound) {
1276                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                                "Posting delayed MCS_UNBIND");
1278                                        removeMessages(MCS_UNBIND);
1279                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1280                                        // Unbind after a little delay, to avoid
1281                                        // continual thrashing.
1282                                        sendMessageDelayed(ubmsg, 10000);
1283                                    }
1284                                } else {
1285                                    // There are more pending requests in queue.
1286                                    // Just post MCS_BOUND message to trigger processing
1287                                    // of next pending install.
1288                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1289                                            "Posting MCS_BOUND for next work");
1290                                    mHandler.sendEmptyMessage(MCS_BOUND);
1291                                }
1292                            }
1293                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1294                        }
1295                    } else {
1296                        // Should never happen ideally.
1297                        Slog.w(TAG, "Empty queue");
1298                    }
1299                    break;
1300                }
1301                case MCS_RECONNECT: {
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1303                    if (mPendingInstalls.size() > 0) {
1304                        if (mBound) {
1305                            disconnectService();
1306                        }
1307                        if (!connectToService()) {
1308                            Slog.e(TAG, "Failed to bind to media container service");
1309                            for (HandlerParams params : mPendingInstalls) {
1310                                // Indicate service bind error
1311                                params.serviceError();
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1313                                        System.identityHashCode(params));
1314                            }
1315                            mPendingInstalls.clear();
1316                        }
1317                    }
1318                    break;
1319                }
1320                case MCS_UNBIND: {
1321                    // If there is no actual work left, then time to unbind.
1322                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1323
1324                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1325                        if (mBound) {
1326                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1327
1328                            disconnectService();
1329                        }
1330                    } else if (mPendingInstalls.size() > 0) {
1331                        // There are more pending requests in queue.
1332                        // Just post MCS_BOUND message to trigger processing
1333                        // of next pending install.
1334                        mHandler.sendEmptyMessage(MCS_BOUND);
1335                    }
1336
1337                    break;
1338                }
1339                case MCS_GIVE_UP: {
1340                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1341                    HandlerParams params = mPendingInstalls.remove(0);
1342                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                            System.identityHashCode(params));
1344                    break;
1345                }
1346                case SEND_PENDING_BROADCAST: {
1347                    String packages[];
1348                    ArrayList<String> components[];
1349                    int size = 0;
1350                    int uids[];
1351                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1352                    synchronized (mPackages) {
1353                        if (mPendingBroadcasts == null) {
1354                            return;
1355                        }
1356                        size = mPendingBroadcasts.size();
1357                        if (size <= 0) {
1358                            // Nothing to be done. Just return
1359                            return;
1360                        }
1361                        packages = new String[size];
1362                        components = new ArrayList[size];
1363                        uids = new int[size];
1364                        int i = 0;  // filling out the above arrays
1365
1366                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1367                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1368                            Iterator<Map.Entry<String, ArrayList<String>>> it
1369                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1370                                            .entrySet().iterator();
1371                            while (it.hasNext() && i < size) {
1372                                Map.Entry<String, ArrayList<String>> ent = it.next();
1373                                packages[i] = ent.getKey();
1374                                components[i] = ent.getValue();
1375                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1376                                uids[i] = (ps != null)
1377                                        ? UserHandle.getUid(packageUserId, ps.appId)
1378                                        : -1;
1379                                i++;
1380                            }
1381                        }
1382                        size = i;
1383                        mPendingBroadcasts.clear();
1384                    }
1385                    // Send broadcasts
1386                    for (int i = 0; i < size; i++) {
1387                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                    break;
1391                }
1392                case START_CLEANING_PACKAGE: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    final String packageName = (String)msg.obj;
1395                    final int userId = msg.arg1;
1396                    final boolean andCode = msg.arg2 != 0;
1397                    synchronized (mPackages) {
1398                        if (userId == UserHandle.USER_ALL) {
1399                            int[] users = sUserManager.getUserIds();
1400                            for (int user : users) {
1401                                mSettings.addPackageToCleanLPw(
1402                                        new PackageCleanItem(user, packageName, andCode));
1403                            }
1404                        } else {
1405                            mSettings.addPackageToCleanLPw(
1406                                    new PackageCleanItem(userId, packageName, andCode));
1407                        }
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                    startCleaningPackages();
1411                } break;
1412                case POST_INSTALL: {
1413                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1414
1415                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1416                    final boolean didRestore = (msg.arg2 != 0);
1417                    mRunningInstalls.delete(msg.arg1);
1418
1419                    if (data != null) {
1420                        InstallArgs args = data.args;
1421                        PackageInstalledInfo parentRes = data.res;
1422
1423                        final boolean grantPermissions = (args.installFlags
1424                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1425                        final boolean killApp = (args.installFlags
1426                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1427                        final String[] grantedPermissions = args.installGrantPermissions;
1428
1429                        // Handle the parent package
1430                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1431                                grantedPermissions, didRestore, args.installerPackageName,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1440                                    grantedPermissions, false, args.installerPackageName,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1474                            PackageHelper.getMountService().finishMediaUpdate();
1475                        } catch (RemoteException e) {
1476                            Log.e(TAG, "MountService not running?");
1477                        }
1478                    }
1479                } break;
1480                case WRITE_SETTINGS: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_SETTINGS);
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        mSettings.writeLPr();
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case WRITE_PACKAGE_RESTRICTIONS: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    synchronized (mPackages) {
1493                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1494                        for (int userId : mDirtyUsers) {
1495                            mSettings.writePackageRestrictionsLPr(userId);
1496                        }
1497                        mDirtyUsers.clear();
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                } break;
1501                case WRITE_PACKAGE_LIST: {
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1503                    synchronized (mPackages) {
1504                        removeMessages(WRITE_PACKAGE_LIST);
1505                        mSettings.writePackageListLPr(msg.arg1);
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                } break;
1509                case CHECK_PENDING_VERIFICATION: {
1510                    final int verificationId = msg.arg1;
1511                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1512
1513                    if ((state != null) && !state.timeoutExtended()) {
1514                        final InstallArgs args = state.getInstallArgs();
1515                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1516
1517                        Slog.i(TAG, "Verification timed out for " + originUri);
1518                        mPendingVerification.remove(verificationId);
1519
1520                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1521
1522                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1523                            Slog.i(TAG, "Continuing with installation of " + originUri);
1524                            state.setVerifierResponse(Binder.getCallingUid(),
1525                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1526                            broadcastPackageVerified(verificationId, originUri,
1527                                    PackageManager.VERIFICATION_ALLOW,
1528                                    state.getInstallArgs().getUser());
1529                            try {
1530                                ret = args.copyApk(mContainerService, true);
1531                            } catch (RemoteException e) {
1532                                Slog.e(TAG, "Could not contact the ContainerService");
1533                            }
1534                        } else {
1535                            broadcastPackageVerified(verificationId, originUri,
1536                                    PackageManager.VERIFICATION_REJECT,
1537                                    state.getInstallArgs().getUser());
1538                        }
1539
1540                        Trace.asyncTraceEnd(
1541                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1542
1543                        processPendingInstall(args, ret);
1544                        mHandler.sendEmptyMessage(MCS_UNBIND);
1545                    }
1546                    break;
1547                }
1548                case PACKAGE_VERIFIED: {
1549                    final int verificationId = msg.arg1;
1550
1551                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1552                    if (state == null) {
1553                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1554                        break;
1555                    }
1556
1557                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1558
1559                    state.setVerifierResponse(response.callerUid, response.code);
1560
1561                    if (state.isVerificationComplete()) {
1562                        mPendingVerification.remove(verificationId);
1563
1564                        final InstallArgs args = state.getInstallArgs();
1565                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1566
1567                        int ret;
1568                        if (state.isInstallAllowed()) {
1569                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1570                            broadcastPackageVerified(verificationId, originUri,
1571                                    response.code, state.getInstallArgs().getUser());
1572                            try {
1573                                ret = args.copyApk(mContainerService, true);
1574                            } catch (RemoteException e) {
1575                                Slog.e(TAG, "Could not contact the ContainerService");
1576                            }
1577                        } else {
1578                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1579                        }
1580
1581                        Trace.asyncTraceEnd(
1582                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1583
1584                        processPendingInstall(args, ret);
1585                        mHandler.sendEmptyMessage(MCS_UNBIND);
1586                    }
1587
1588                    break;
1589                }
1590                case START_INTENT_FILTER_VERIFICATIONS: {
1591                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1592                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1593                            params.replacing, params.pkg);
1594                    break;
1595                }
1596                case INTENT_FILTER_VERIFIED: {
1597                    final int verificationId = msg.arg1;
1598
1599                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1600                            verificationId);
1601                    if (state == null) {
1602                        Slog.w(TAG, "Invalid IntentFilter verification token "
1603                                + verificationId + " received");
1604                        break;
1605                    }
1606
1607                    final int userId = state.getUserId();
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "Processing IntentFilter verification with token:"
1611                            + verificationId + " and userId:" + userId);
1612
1613                    final IntentFilterVerificationResponse response =
1614                            (IntentFilterVerificationResponse) msg.obj;
1615
1616                    state.setVerifierResponse(response.callerUid, response.code);
1617
1618                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1619                            "IntentFilter verification with token:" + verificationId
1620                            + " and userId:" + userId
1621                            + " is settings verifier response with response code:"
1622                            + response.code);
1623
1624                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1625                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1626                                + response.getFailedDomainsString());
1627                    }
1628
1629                    if (state.isVerificationComplete()) {
1630                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1631                    } else {
1632                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1633                                "IntentFilter verification with token:" + verificationId
1634                                + " was not said to be complete");
1635                    }
1636
1637                    break;
1638                }
1639            }
1640        }
1641    }
1642
1643    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1644            boolean killApp, String[] grantedPermissions,
1645            boolean launchedForRestore, String installerPackage,
1646            IPackageInstallObserver2 installObserver) {
1647        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1648            // Send the removed broadcasts
1649            if (res.removedInfo != null) {
1650                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1651            }
1652
1653            // Now that we successfully installed the package, grant runtime
1654            // permissions if requested before broadcasting the install.
1655            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1656                    >= Build.VERSION_CODES.M) {
1657                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1658            }
1659
1660            final boolean update = res.removedInfo != null
1661                    && res.removedInfo.removedPackage != null;
1662
1663            // If this is the first time we have child packages for a disabled privileged
1664            // app that had no children, we grant requested runtime permissions to the new
1665            // children if the parent on the system image had them already granted.
1666            if (res.pkg.parentPackage != null) {
1667                synchronized (mPackages) {
1668                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1669                }
1670            }
1671
1672            synchronized (mPackages) {
1673                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1674            }
1675
1676            final String packageName = res.pkg.applicationInfo.packageName;
1677
1678            // Determine the set of users who are adding this package for
1679            // the first time vs. those who are seeing an update.
1680            int[] firstUsers = EMPTY_INT_ARRAY;
1681            int[] updateUsers = EMPTY_INT_ARRAY;
1682            if (res.origUsers == null || res.origUsers.length == 0) {
1683                firstUsers = res.newUsers;
1684            } else {
1685                for (int newUser : res.newUsers) {
1686                    boolean isNew = true;
1687                    for (int origUser : res.origUsers) {
1688                        if (origUser == newUser) {
1689                            isNew = false;
1690                            break;
1691                        }
1692                    }
1693                    if (isNew) {
1694                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1695                    } else {
1696                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1697                    }
1698                }
1699            }
1700
1701            // Send installed broadcasts if the install/update is not ephemeral
1702            if (!isEphemeral(res.pkg)) {
1703                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1704
1705                // Send added for users that see the package for the first time
1706                // sendPackageAddedForNewUsers also deals with system apps
1707                int appId = UserHandle.getAppId(res.uid);
1708                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1709                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1710
1711                // Send added for users that don't see the package for the first time
1712                Bundle extras = new Bundle(1);
1713                extras.putInt(Intent.EXTRA_UID, res.uid);
1714                if (update) {
1715                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1716                }
1717                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1718                        extras, 0 /*flags*/, null /*targetPackage*/,
1719                        null /*finishedReceiver*/, updateUsers);
1720
1721                // Send replaced for users that don't see the package for the first time
1722                if (update) {
1723                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1724                            packageName, extras, 0 /*flags*/,
1725                            null /*targetPackage*/, null /*finishedReceiver*/,
1726                            updateUsers);
1727                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1728                            null /*package*/, null /*extras*/, 0 /*flags*/,
1729                            packageName /*targetPackage*/,
1730                            null /*finishedReceiver*/, updateUsers);
1731                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1732                    // First-install and we did a restore, so we're responsible for the
1733                    // first-launch broadcast.
1734                    if (DEBUG_BACKUP) {
1735                        Slog.i(TAG, "Post-restore of " + packageName
1736                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1737                    }
1738                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1739                }
1740
1741                // Send broadcast package appeared if forward locked/external for all users
1742                // treat asec-hosted packages like removable media on upgrade
1743                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1744                    if (DEBUG_INSTALL) {
1745                        Slog.i(TAG, "upgrading pkg " + res.pkg
1746                                + " is ASEC-hosted -> AVAILABLE");
1747                    }
1748                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1749                    ArrayList<String> pkgList = new ArrayList<>(1);
1750                    pkgList.add(packageName);
1751                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1752                }
1753            }
1754
1755            // Work that needs to happen on first install within each user
1756            if (firstUsers != null && firstUsers.length > 0) {
1757                synchronized (mPackages) {
1758                    for (int userId : firstUsers) {
1759                        // If this app is a browser and it's newly-installed for some
1760                        // users, clear any default-browser state in those users. The
1761                        // app's nature doesn't depend on the user, so we can just check
1762                        // its browser nature in any user and generalize.
1763                        if (packageIsBrowser(packageName, userId)) {
1764                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1765                        }
1766
1767                        // We may also need to apply pending (restored) runtime
1768                        // permission grants within these users.
1769                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1770                    }
1771                }
1772            }
1773
1774            // Log current value of "unknown sources" setting
1775            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1776                    getUnknownSourcesSettings());
1777
1778            // Force a gc to clear up things
1779            Runtime.getRuntime().gc();
1780
1781            // Remove the replaced package's older resources safely now
1782            // We delete after a gc for applications  on sdcard.
1783            if (res.removedInfo != null && res.removedInfo.args != null) {
1784                synchronized (mInstallLock) {
1785                    res.removedInfo.args.doPostDeleteLI(true);
1786                }
1787            }
1788        }
1789
1790        // If someone is watching installs - notify them
1791        if (installObserver != null) {
1792            try {
1793                Bundle extras = extrasForInstallResult(res);
1794                installObserver.onPackageInstalled(res.name, res.returnCode,
1795                        res.returnMsg, extras);
1796            } catch (RemoteException e) {
1797                Slog.i(TAG, "Observer no longer exists.");
1798            }
1799        }
1800    }
1801
1802    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1803            PackageParser.Package pkg) {
1804        if (pkg.parentPackage == null) {
1805            return;
1806        }
1807        if (pkg.requestedPermissions == null) {
1808            return;
1809        }
1810        final PackageSetting disabledSysParentPs = mSettings
1811                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1812        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1813                || !disabledSysParentPs.isPrivileged()
1814                || (disabledSysParentPs.childPackageNames != null
1815                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1816            return;
1817        }
1818        final int[] allUserIds = sUserManager.getUserIds();
1819        final int permCount = pkg.requestedPermissions.size();
1820        for (int i = 0; i < permCount; i++) {
1821            String permission = pkg.requestedPermissions.get(i);
1822            BasePermission bp = mSettings.mPermissions.get(permission);
1823            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1824                continue;
1825            }
1826            for (int userId : allUserIds) {
1827                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1828                        permission, userId)) {
1829                    grantRuntimePermission(pkg.packageName, permission, userId);
1830                }
1831            }
1832        }
1833    }
1834
1835    private StorageEventListener mStorageListener = new StorageEventListener() {
1836        @Override
1837        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1838            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1839                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1840                    final String volumeUuid = vol.getFsUuid();
1841
1842                    // Clean up any users or apps that were removed or recreated
1843                    // while this volume was missing
1844                    reconcileUsers(volumeUuid);
1845                    reconcileApps(volumeUuid);
1846
1847                    // Clean up any install sessions that expired or were
1848                    // cancelled while this volume was missing
1849                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1850
1851                    loadPrivatePackages(vol);
1852
1853                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1854                    unloadPrivatePackages(vol);
1855                }
1856            }
1857
1858            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1859                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1860                    updateExternalMediaStatus(true, false);
1861                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1862                    updateExternalMediaStatus(false, false);
1863                }
1864            }
1865        }
1866
1867        @Override
1868        public void onVolumeForgotten(String fsUuid) {
1869            if (TextUtils.isEmpty(fsUuid)) {
1870                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1871                return;
1872            }
1873
1874            // Remove any apps installed on the forgotten volume
1875            synchronized (mPackages) {
1876                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1877                for (PackageSetting ps : packages) {
1878                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1879                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1880                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1881                }
1882
1883                mSettings.onVolumeForgotten(fsUuid);
1884                mSettings.writeLPr();
1885            }
1886        }
1887    };
1888
1889    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1890            String[] grantedPermissions) {
1891        for (int userId : userIds) {
1892            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1893        }
1894
1895        // We could have touched GID membership, so flush out packages.list
1896        synchronized (mPackages) {
1897            mSettings.writePackageListLPr();
1898        }
1899    }
1900
1901    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1902            String[] grantedPermissions) {
1903        SettingBase sb = (SettingBase) pkg.mExtras;
1904        if (sb == null) {
1905            return;
1906        }
1907
1908        PermissionsState permissionsState = sb.getPermissionsState();
1909
1910        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1911                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1912
1913        for (String permission : pkg.requestedPermissions) {
1914            final BasePermission bp;
1915            synchronized (mPackages) {
1916                bp = mSettings.mPermissions.get(permission);
1917            }
1918            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1919                    && (grantedPermissions == null
1920                           || ArrayUtils.contains(grantedPermissions, permission))) {
1921                final int flags = permissionsState.getPermissionFlags(permission, userId);
1922                // Installer cannot change immutable permissions.
1923                if ((flags & immutableFlags) == 0) {
1924                    grantRuntimePermission(pkg.packageName, permission, userId);
1925                }
1926            }
1927        }
1928    }
1929
1930    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1931        Bundle extras = null;
1932        switch (res.returnCode) {
1933            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1934                extras = new Bundle();
1935                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1936                        res.origPermission);
1937                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1938                        res.origPackage);
1939                break;
1940            }
1941            case PackageManager.INSTALL_SUCCEEDED: {
1942                extras = new Bundle();
1943                extras.putBoolean(Intent.EXTRA_REPLACING,
1944                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1945                break;
1946            }
1947        }
1948        return extras;
1949    }
1950
1951    void scheduleWriteSettingsLocked() {
1952        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1953            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1954        }
1955    }
1956
1957    void scheduleWritePackageListLocked(int userId) {
1958        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1959            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1960            msg.arg1 = userId;
1961            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1962        }
1963    }
1964
1965    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1966        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1967        scheduleWritePackageRestrictionsLocked(userId);
1968    }
1969
1970    void scheduleWritePackageRestrictionsLocked(int userId) {
1971        final int[] userIds = (userId == UserHandle.USER_ALL)
1972                ? sUserManager.getUserIds() : new int[]{userId};
1973        for (int nextUserId : userIds) {
1974            if (!sUserManager.exists(nextUserId)) return;
1975            mDirtyUsers.add(nextUserId);
1976            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1977                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1978            }
1979        }
1980    }
1981
1982    public static PackageManagerService main(Context context, Installer installer,
1983            boolean factoryTest, boolean onlyCore) {
1984        // Self-check for initial settings.
1985        PackageManagerServiceCompilerMapping.checkProperties();
1986
1987        PackageManagerService m = new PackageManagerService(context, installer,
1988                factoryTest, onlyCore);
1989        m.enableSystemUserPackages();
1990        ServiceManager.addService("package", m);
1991        return m;
1992    }
1993
1994    private void enableSystemUserPackages() {
1995        if (!UserManager.isSplitSystemUser()) {
1996            return;
1997        }
1998        // For system user, enable apps based on the following conditions:
1999        // - app is whitelisted or belong to one of these groups:
2000        //   -- system app which has no launcher icons
2001        //   -- system app which has INTERACT_ACROSS_USERS permission
2002        //   -- system IME app
2003        // - app is not in the blacklist
2004        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2005        Set<String> enableApps = new ArraySet<>();
2006        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2007                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2008                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2009        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2010        enableApps.addAll(wlApps);
2011        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2012                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2013        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2014        enableApps.removeAll(blApps);
2015        Log.i(TAG, "Applications installed for system user: " + enableApps);
2016        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2017                UserHandle.SYSTEM);
2018        final int allAppsSize = allAps.size();
2019        synchronized (mPackages) {
2020            for (int i = 0; i < allAppsSize; i++) {
2021                String pName = allAps.get(i);
2022                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2023                // Should not happen, but we shouldn't be failing if it does
2024                if (pkgSetting == null) {
2025                    continue;
2026                }
2027                boolean install = enableApps.contains(pName);
2028                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2029                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2030                            + " for system user");
2031                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2032                }
2033            }
2034        }
2035    }
2036
2037    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2038        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2039                Context.DISPLAY_SERVICE);
2040        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2041    }
2042
2043    /**
2044     * Requests that files preopted on a secondary system partition be copied to the data partition
2045     * if possible.  Note that the actual copying of the files is accomplished by init for security
2046     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2047     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2048     */
2049    private static void requestCopyPreoptedFiles() {
2050        final int WAIT_TIME_MS = 100;
2051        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2052        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2053            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2054            // We will wait for up to 100 seconds.
2055            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2056            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2057                try {
2058                    Thread.sleep(WAIT_TIME_MS);
2059                } catch (InterruptedException e) {
2060                    // Do nothing
2061                }
2062                if (SystemClock.uptimeMillis() > timeEnd) {
2063                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2064                    Slog.wtf(TAG, "cppreopt did not finish!");
2065                    break;
2066                }
2067            }
2068        }
2069    }
2070
2071    public PackageManagerService(Context context, Installer installer,
2072            boolean factoryTest, boolean onlyCore) {
2073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2074        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2075                SystemClock.uptimeMillis());
2076
2077        if (mSdkVersion <= 0) {
2078            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2079        }
2080
2081        mContext = context;
2082
2083        mPermissionReviewRequired = context.getResources().getBoolean(
2084                R.bool.config_permissionReviewRequired);
2085
2086        mFactoryTest = factoryTest;
2087        mOnlyCore = onlyCore;
2088        mMetrics = new DisplayMetrics();
2089        mSettings = new Settings(mPackages);
2090        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2091                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2092        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2093                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2095                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2097                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2099                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2100        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2101                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102
2103        String separateProcesses = SystemProperties.get("debug.separate_processes");
2104        if (separateProcesses != null && separateProcesses.length() > 0) {
2105            if ("*".equals(separateProcesses)) {
2106                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2107                mSeparateProcesses = null;
2108                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2109            } else {
2110                mDefParseFlags = 0;
2111                mSeparateProcesses = separateProcesses.split(",");
2112                Slog.w(TAG, "Running with debug.separate_processes: "
2113                        + separateProcesses);
2114            }
2115        } else {
2116            mDefParseFlags = 0;
2117            mSeparateProcesses = null;
2118        }
2119
2120        mInstaller = installer;
2121        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2122                "*dexopt*");
2123        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2124
2125        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2126                FgThread.get().getLooper());
2127
2128        getDefaultDisplayMetrics(context, mMetrics);
2129
2130        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2131        SystemConfig systemConfig = SystemConfig.getInstance();
2132        mGlobalGids = systemConfig.getGlobalGids();
2133        mSystemPermissions = systemConfig.getSystemPermissions();
2134        mAvailableFeatures = systemConfig.getAvailableFeatures();
2135        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2136
2137        mProtectedPackages = new ProtectedPackages(mContext);
2138
2139        synchronized (mInstallLock) {
2140        // writer
2141        synchronized (mPackages) {
2142            mHandlerThread = new ServiceThread(TAG,
2143                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2144            mHandlerThread.start();
2145            mHandler = new PackageHandler(mHandlerThread.getLooper());
2146            mProcessLoggingHandler = new ProcessLoggingHandler();
2147            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2148
2149            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2150
2151            File dataDir = Environment.getDataDirectory();
2152            mAppInstallDir = new File(dataDir, "app");
2153            mAppLib32InstallDir = new File(dataDir, "app-lib");
2154            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2155            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2156            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2157
2158            sUserManager = new UserManagerService(context, this, mPackages);
2159
2160            // Propagate permission configuration in to package manager.
2161            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2162                    = systemConfig.getPermissions();
2163            for (int i=0; i<permConfig.size(); i++) {
2164                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2165                BasePermission bp = mSettings.mPermissions.get(perm.name);
2166                if (bp == null) {
2167                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2168                    mSettings.mPermissions.put(perm.name, bp);
2169                }
2170                if (perm.gids != null) {
2171                    bp.setGids(perm.gids, perm.perUser);
2172                }
2173            }
2174
2175            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2176            for (int i=0; i<libConfig.size(); i++) {
2177                mSharedLibraries.put(libConfig.keyAt(i),
2178                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2179            }
2180
2181            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2182
2183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2184            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2185            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2186
2187            if (mFirstBoot) {
2188                requestCopyPreoptedFiles();
2189            }
2190
2191            String customResolverActivity = Resources.getSystem().getString(
2192                    R.string.config_customResolverActivity);
2193            if (TextUtils.isEmpty(customResolverActivity)) {
2194                customResolverActivity = null;
2195            } else {
2196                mCustomResolverComponentName = ComponentName.unflattenFromString(
2197                        customResolverActivity);
2198            }
2199
2200            long startTime = SystemClock.uptimeMillis();
2201
2202            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2203                    startTime);
2204
2205            // Set flag to monitor and not change apk file paths when
2206            // scanning install directories.
2207            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2208
2209            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2210            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2211
2212            if (bootClassPath == null) {
2213                Slog.w(TAG, "No BOOTCLASSPATH found!");
2214            }
2215
2216            if (systemServerClassPath == null) {
2217                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2218            }
2219
2220            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2221            final String[] dexCodeInstructionSets =
2222                    getDexCodeInstructionSets(
2223                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2224
2225            /**
2226             * Ensure all external libraries have had dexopt run on them.
2227             */
2228            if (mSharedLibraries.size() > 0) {
2229                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2230                // NOTE: For now, we're compiling these system "shared libraries"
2231                // (and framework jars) into all available architectures. It's possible
2232                // to compile them only when we come across an app that uses them (there's
2233                // already logic for that in scanPackageLI) but that adds some complexity.
2234                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2235                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2236                        final String lib = libEntry.path;
2237                        if (lib == null) {
2238                            continue;
2239                        }
2240
2241                        try {
2242                            // Shared libraries do not have profiles so we perform a full
2243                            // AOT compilation (if needed).
2244                            int dexoptNeeded = DexFile.getDexOptNeeded(
2245                                    lib, dexCodeInstructionSet,
2246                                    getCompilerFilterForReason(REASON_SHARED_APK),
2247                                    false /* newProfile */);
2248                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2249                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2250                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2251                                        getCompilerFilterForReason(REASON_SHARED_APK),
2252                                        StorageManager.UUID_PRIVATE_INTERNAL,
2253                                        SKIP_SHARED_LIBRARY_CHECK);
2254                            }
2255                        } catch (FileNotFoundException e) {
2256                            Slog.w(TAG, "Library not found: " + lib);
2257                        } catch (IOException | InstallerException e) {
2258                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2259                                    + e.getMessage());
2260                        }
2261                    }
2262                }
2263                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2264            }
2265
2266            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2267
2268            final VersionInfo ver = mSettings.getInternalVersion();
2269            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2270
2271            // when upgrading from pre-M, promote system app permissions from install to runtime
2272            mPromoteSystemApps =
2273                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2274
2275            // When upgrading from pre-N, we need to handle package extraction like first boot,
2276            // as there is no profiling data available.
2277            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2278
2279            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2280
2281            // save off the names of pre-existing system packages prior to scanning; we don't
2282            // want to automatically grant runtime permissions for new system apps
2283            if (mPromoteSystemApps) {
2284                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2285                while (pkgSettingIter.hasNext()) {
2286                    PackageSetting ps = pkgSettingIter.next();
2287                    if (isSystemApp(ps)) {
2288                        mExistingSystemPackages.add(ps.name);
2289                    }
2290                }
2291            }
2292
2293            // Collect vendor overlay packages. (Do this before scanning any apps.)
2294            // For security and version matching reason, only consider
2295            // overlay packages if they reside in the right directory.
2296            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2297            if (overlayThemeDir.isEmpty()) {
2298                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2299            }
2300            if (!overlayThemeDir.isEmpty()) {
2301                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2302                        | PackageParser.PARSE_IS_SYSTEM
2303                        | PackageParser.PARSE_IS_SYSTEM_DIR
2304                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2305            }
2306            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2307                    | PackageParser.PARSE_IS_SYSTEM
2308                    | PackageParser.PARSE_IS_SYSTEM_DIR
2309                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2310
2311            // Find base frameworks (resource packages without code).
2312            scanDirTracedLI(frameworkDir, mDefParseFlags
2313                    | PackageParser.PARSE_IS_SYSTEM
2314                    | PackageParser.PARSE_IS_SYSTEM_DIR
2315                    | PackageParser.PARSE_IS_PRIVILEGED,
2316                    scanFlags | SCAN_NO_DEX, 0);
2317
2318            // Collected privileged system packages.
2319            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2320            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2321                    | PackageParser.PARSE_IS_SYSTEM
2322                    | PackageParser.PARSE_IS_SYSTEM_DIR
2323                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2324
2325            // Collect ordinary system packages.
2326            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2327            scanDirTracedLI(systemAppDir, mDefParseFlags
2328                    | PackageParser.PARSE_IS_SYSTEM
2329                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2330
2331            // Collect all vendor packages.
2332            File vendorAppDir = new File("/vendor/app");
2333            try {
2334                vendorAppDir = vendorAppDir.getCanonicalFile();
2335            } catch (IOException e) {
2336                // failed to look up canonical path, continue with original one
2337            }
2338            scanDirTracedLI(vendorAppDir, mDefParseFlags
2339                    | PackageParser.PARSE_IS_SYSTEM
2340                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2341
2342            // Collect all OEM packages.
2343            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2344            scanDirTracedLI(oemAppDir, mDefParseFlags
2345                    | PackageParser.PARSE_IS_SYSTEM
2346                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2347
2348            // Prune any system packages that no longer exist.
2349            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2350            if (!mOnlyCore) {
2351                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2352                while (psit.hasNext()) {
2353                    PackageSetting ps = psit.next();
2354
2355                    /*
2356                     * If this is not a system app, it can't be a
2357                     * disable system app.
2358                     */
2359                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2360                        continue;
2361                    }
2362
2363                    /*
2364                     * If the package is scanned, it's not erased.
2365                     */
2366                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2367                    if (scannedPkg != null) {
2368                        /*
2369                         * If the system app is both scanned and in the
2370                         * disabled packages list, then it must have been
2371                         * added via OTA. Remove it from the currently
2372                         * scanned package so the previously user-installed
2373                         * application can be scanned.
2374                         */
2375                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2376                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2377                                    + ps.name + "; removing system app.  Last known codePath="
2378                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2379                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2380                                    + scannedPkg.mVersionCode);
2381                            removePackageLI(scannedPkg, true);
2382                            mExpectingBetter.put(ps.name, ps.codePath);
2383                        }
2384
2385                        continue;
2386                    }
2387
2388                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2389                        psit.remove();
2390                        logCriticalInfo(Log.WARN, "System package " + ps.name
2391                                + " no longer exists; it's data will be wiped");
2392                        // Actual deletion of code and data will be handled by later
2393                        // reconciliation step
2394                    } else {
2395                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2396                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2397                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2398                        }
2399                    }
2400                }
2401            }
2402
2403            //look for any incomplete package installations
2404            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2405            for (int i = 0; i < deletePkgsList.size(); i++) {
2406                // Actual deletion of code and data will be handled by later
2407                // reconciliation step
2408                final String packageName = deletePkgsList.get(i).name;
2409                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2410                synchronized (mPackages) {
2411                    mSettings.removePackageLPw(packageName);
2412                }
2413            }
2414
2415            //delete tmp files
2416            deleteTempPackageFiles();
2417
2418            // Remove any shared userIDs that have no associated packages
2419            mSettings.pruneSharedUsersLPw();
2420
2421            if (!mOnlyCore) {
2422                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2423                        SystemClock.uptimeMillis());
2424                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2425
2426                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2427                        | PackageParser.PARSE_FORWARD_LOCK,
2428                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2429
2430                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2431                        | PackageParser.PARSE_IS_EPHEMERAL,
2432                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2433
2434                /**
2435                 * Remove disable package settings for any updated system
2436                 * apps that were removed via an OTA. If they're not a
2437                 * previously-updated app, remove them completely.
2438                 * Otherwise, just revoke their system-level permissions.
2439                 */
2440                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2441                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2442                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2443
2444                    String msg;
2445                    if (deletedPkg == null) {
2446                        msg = "Updated system package " + deletedAppName
2447                                + " no longer exists; it's data will be wiped";
2448                        // Actual deletion of code and data will be handled by later
2449                        // reconciliation step
2450                    } else {
2451                        msg = "Updated system app + " + deletedAppName
2452                                + " no longer present; removing system privileges for "
2453                                + deletedAppName;
2454
2455                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2456
2457                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2458                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2459                    }
2460                    logCriticalInfo(Log.WARN, msg);
2461                }
2462
2463                /**
2464                 * Make sure all system apps that we expected to appear on
2465                 * the userdata partition actually showed up. If they never
2466                 * appeared, crawl back and revive the system version.
2467                 */
2468                for (int i = 0; i < mExpectingBetter.size(); i++) {
2469                    final String packageName = mExpectingBetter.keyAt(i);
2470                    if (!mPackages.containsKey(packageName)) {
2471                        final File scanFile = mExpectingBetter.valueAt(i);
2472
2473                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2474                                + " but never showed up; reverting to system");
2475
2476                        int reparseFlags = mDefParseFlags;
2477                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2478                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2479                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2480                                    | PackageParser.PARSE_IS_PRIVILEGED;
2481                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2482                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2483                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2484                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2485                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2486                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2487                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2488                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2489                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2490                        } else {
2491                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2492                            continue;
2493                        }
2494
2495                        mSettings.enableSystemPackageLPw(packageName);
2496
2497                        try {
2498                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2499                        } catch (PackageManagerException e) {
2500                            Slog.e(TAG, "Failed to parse original system package: "
2501                                    + e.getMessage());
2502                        }
2503                    }
2504                }
2505            }
2506            mExpectingBetter.clear();
2507
2508            // Resolve the storage manager.
2509            mStorageManagerPackage = getStorageManagerPackageName();
2510
2511            // Resolve protected action filters. Only the setup wizard is allowed to
2512            // have a high priority filter for these actions.
2513            mSetupWizardPackage = getSetupWizardPackageName();
2514            if (mProtectedFilters.size() > 0) {
2515                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2516                    Slog.i(TAG, "No setup wizard;"
2517                        + " All protected intents capped to priority 0");
2518                }
2519                for (ActivityIntentInfo filter : mProtectedFilters) {
2520                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2521                        if (DEBUG_FILTERS) {
2522                            Slog.i(TAG, "Found setup wizard;"
2523                                + " allow priority " + filter.getPriority() + ";"
2524                                + " package: " + filter.activity.info.packageName
2525                                + " activity: " + filter.activity.className
2526                                + " priority: " + filter.getPriority());
2527                        }
2528                        // skip setup wizard; allow it to keep the high priority filter
2529                        continue;
2530                    }
2531                    Slog.w(TAG, "Protected action; cap priority to 0;"
2532                            + " package: " + filter.activity.info.packageName
2533                            + " activity: " + filter.activity.className
2534                            + " origPrio: " + filter.getPriority());
2535                    filter.setPriority(0);
2536                }
2537            }
2538            mDeferProtectedFilters = false;
2539            mProtectedFilters.clear();
2540
2541            // Now that we know all of the shared libraries, update all clients to have
2542            // the correct library paths.
2543            updateAllSharedLibrariesLPw();
2544
2545            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2546                // NOTE: We ignore potential failures here during a system scan (like
2547                // the rest of the commands above) because there's precious little we
2548                // can do about it. A settings error is reported, though.
2549                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2550            }
2551
2552            // Now that we know all the packages we are keeping,
2553            // read and update their last usage times.
2554            mPackageUsage.read(mPackages);
2555            mCompilerStats.read();
2556
2557            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2558                    SystemClock.uptimeMillis());
2559            Slog.i(TAG, "Time to scan packages: "
2560                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2561                    + " seconds");
2562
2563            // If the platform SDK has changed since the last time we booted,
2564            // we need to re-grant app permission to catch any new ones that
2565            // appear.  This is really a hack, and means that apps can in some
2566            // cases get permissions that the user didn't initially explicitly
2567            // allow...  it would be nice to have some better way to handle
2568            // this situation.
2569            int updateFlags = UPDATE_PERMISSIONS_ALL;
2570            if (ver.sdkVersion != mSdkVersion) {
2571                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2572                        + mSdkVersion + "; regranting permissions for internal storage");
2573                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2574            }
2575            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2576            ver.sdkVersion = mSdkVersion;
2577
2578            // If this is the first boot or an update from pre-M, and it is a normal
2579            // boot, then we need to initialize the default preferred apps across
2580            // all defined users.
2581            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2582                for (UserInfo user : sUserManager.getUsers(true)) {
2583                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2584                    applyFactoryDefaultBrowserLPw(user.id);
2585                    primeDomainVerificationsLPw(user.id);
2586                }
2587            }
2588
2589            // Prepare storage for system user really early during boot,
2590            // since core system apps like SettingsProvider and SystemUI
2591            // can't wait for user to start
2592            final int storageFlags;
2593            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2594                storageFlags = StorageManager.FLAG_STORAGE_DE;
2595            } else {
2596                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2597            }
2598            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2599                    storageFlags, true /* migrateAppData */);
2600
2601            // If this is first boot after an OTA, and a normal boot, then
2602            // we need to clear code cache directories.
2603            // Note that we do *not* clear the application profiles. These remain valid
2604            // across OTAs and are used to drive profile verification (post OTA) and
2605            // profile compilation (without waiting to collect a fresh set of profiles).
2606            if (mIsUpgrade && !onlyCore) {
2607                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2608                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2609                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2610                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2611                        // No apps are running this early, so no need to freeze
2612                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2613                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2614                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2615                    }
2616                }
2617                ver.fingerprint = Build.FINGERPRINT;
2618            }
2619
2620            checkDefaultBrowser();
2621
2622            // clear only after permissions and other defaults have been updated
2623            mExistingSystemPackages.clear();
2624            mPromoteSystemApps = false;
2625
2626            // All the changes are done during package scanning.
2627            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2628
2629            // can downgrade to reader
2630            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2631            mSettings.writeLPr();
2632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2633
2634            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2635            // early on (before the package manager declares itself as early) because other
2636            // components in the system server might ask for package contexts for these apps.
2637            //
2638            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2639            // (i.e, that the data partition is unavailable).
2640            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2641                long start = System.nanoTime();
2642                List<PackageParser.Package> coreApps = new ArrayList<>();
2643                for (PackageParser.Package pkg : mPackages.values()) {
2644                    if (pkg.coreApp) {
2645                        coreApps.add(pkg);
2646                    }
2647                }
2648
2649                int[] stats = performDexOptUpgrade(coreApps, false,
2650                        getCompilerFilterForReason(REASON_CORE_APP));
2651
2652                final int elapsedTimeSeconds =
2653                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2654                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2655
2656                if (DEBUG_DEXOPT) {
2657                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2658                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2659                }
2660
2661
2662                // TODO: Should we log these stats to tron too ?
2663                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2664                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2665                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2666                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2667            }
2668
2669            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2670                    SystemClock.uptimeMillis());
2671
2672            if (!mOnlyCore) {
2673                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2674                mRequiredInstallerPackage = getRequiredInstallerLPr();
2675                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2676                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2677                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2678                        mIntentFilterVerifierComponent);
2679                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2680                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2681                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2682                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2683            } else {
2684                mRequiredVerifierPackage = null;
2685                mRequiredInstallerPackage = null;
2686                mRequiredUninstallerPackage = null;
2687                mIntentFilterVerifierComponent = null;
2688                mIntentFilterVerifier = null;
2689                mServicesSystemSharedLibraryPackageName = null;
2690                mSharedSystemSharedLibraryPackageName = null;
2691            }
2692
2693            mInstallerService = new PackageInstallerService(context, this);
2694
2695            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2696            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2697            // both the installer and resolver must be present to enable ephemeral
2698            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2699                if (DEBUG_EPHEMERAL) {
2700                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2701                            + " installer:" + ephemeralInstallerComponent);
2702                }
2703                mEphemeralResolverComponent = ephemeralResolverComponent;
2704                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2705                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2706                mEphemeralResolverConnection =
2707                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2708            } else {
2709                if (DEBUG_EPHEMERAL) {
2710                    final String missingComponent =
2711                            (ephemeralResolverComponent == null)
2712                            ? (ephemeralInstallerComponent == null)
2713                                    ? "resolver and installer"
2714                                    : "resolver"
2715                            : "installer";
2716                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2717                }
2718                mEphemeralResolverComponent = null;
2719                mEphemeralInstallerComponent = null;
2720                mEphemeralResolverConnection = null;
2721            }
2722
2723            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2724        } // synchronized (mPackages)
2725        } // synchronized (mInstallLock)
2726
2727        // Now after opening every single application zip, make sure they
2728        // are all flushed.  Not really needed, but keeps things nice and
2729        // tidy.
2730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2731        Runtime.getRuntime().gc();
2732        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2733
2734        // The initial scanning above does many calls into installd while
2735        // holding the mPackages lock, but we're mostly interested in yelling
2736        // once we have a booted system.
2737        mInstaller.setWarnIfHeld(mPackages);
2738
2739        // Expose private service for system components to use.
2740        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2741        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2742    }
2743
2744    @Override
2745    public boolean isFirstBoot() {
2746        return mFirstBoot;
2747    }
2748
2749    @Override
2750    public boolean isOnlyCoreApps() {
2751        return mOnlyCore;
2752    }
2753
2754    @Override
2755    public boolean isUpgrade() {
2756        return mIsUpgrade;
2757    }
2758
2759    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2760        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2761
2762        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2763                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2764                UserHandle.USER_SYSTEM);
2765        if (matches.size() == 1) {
2766            return matches.get(0).getComponentInfo().packageName;
2767        } else if (matches.size() == 0) {
2768            Log.e(TAG, "There should probably be a verifier, but, none were found");
2769            return null;
2770        }
2771        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2772    }
2773
2774    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2775        synchronized (mPackages) {
2776            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2777            if (libraryEntry == null) {
2778                throw new IllegalStateException("Missing required shared library:" + libraryName);
2779            }
2780            return libraryEntry.apk;
2781        }
2782    }
2783
2784    private @NonNull String getRequiredInstallerLPr() {
2785        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2786        intent.addCategory(Intent.CATEGORY_DEFAULT);
2787        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2788
2789        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2790                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2791                UserHandle.USER_SYSTEM);
2792        if (matches.size() == 1) {
2793            ResolveInfo resolveInfo = matches.get(0);
2794            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2795                throw new RuntimeException("The installer must be a privileged app");
2796            }
2797            return matches.get(0).getComponentInfo().packageName;
2798        } else {
2799            throw new RuntimeException("There must be exactly one installer; found " + matches);
2800        }
2801    }
2802
2803    private @NonNull String getRequiredUninstallerLPr() {
2804        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2805        intent.addCategory(Intent.CATEGORY_DEFAULT);
2806        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2807
2808        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2809                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2810                UserHandle.USER_SYSTEM);
2811        if (resolveInfo == null ||
2812                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2813            throw new RuntimeException("There must be exactly one uninstaller; found "
2814                    + resolveInfo);
2815        }
2816        return resolveInfo.getComponentInfo().packageName;
2817    }
2818
2819    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2820        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2821
2822        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2823                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2824                UserHandle.USER_SYSTEM);
2825        ResolveInfo best = null;
2826        final int N = matches.size();
2827        for (int i = 0; i < N; i++) {
2828            final ResolveInfo cur = matches.get(i);
2829            final String packageName = cur.getComponentInfo().packageName;
2830            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2831                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2832                continue;
2833            }
2834
2835            if (best == null || cur.priority > best.priority) {
2836                best = cur;
2837            }
2838        }
2839
2840        if (best != null) {
2841            return best.getComponentInfo().getComponentName();
2842        } else {
2843            throw new RuntimeException("There must be at least one intent filter verifier");
2844        }
2845    }
2846
2847    private @Nullable ComponentName getEphemeralResolverLPr() {
2848        final String[] packageArray =
2849                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2850        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2851            if (DEBUG_EPHEMERAL) {
2852                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2853            }
2854            return null;
2855        }
2856
2857        final int resolveFlags =
2858                MATCH_DIRECT_BOOT_AWARE
2859                | MATCH_DIRECT_BOOT_UNAWARE
2860                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2861        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2862        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2863                resolveFlags, UserHandle.USER_SYSTEM);
2864
2865        final int N = resolvers.size();
2866        if (N == 0) {
2867            if (DEBUG_EPHEMERAL) {
2868                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2869            }
2870            return null;
2871        }
2872
2873        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2874        for (int i = 0; i < N; i++) {
2875            final ResolveInfo info = resolvers.get(i);
2876
2877            if (info.serviceInfo == null) {
2878                continue;
2879            }
2880
2881            final String packageName = info.serviceInfo.packageName;
2882            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2883                if (DEBUG_EPHEMERAL) {
2884                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2885                            + " pkg: " + packageName + ", info:" + info);
2886                }
2887                continue;
2888            }
2889
2890            if (DEBUG_EPHEMERAL) {
2891                Slog.v(TAG, "Ephemeral resolver found;"
2892                        + " pkg: " + packageName + ", info:" + info);
2893            }
2894            return new ComponentName(packageName, info.serviceInfo.name);
2895        }
2896        if (DEBUG_EPHEMERAL) {
2897            Slog.v(TAG, "Ephemeral resolver NOT found");
2898        }
2899        return null;
2900    }
2901
2902    private @Nullable ComponentName getEphemeralInstallerLPr() {
2903        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2904        intent.addCategory(Intent.CATEGORY_DEFAULT);
2905        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2906
2907        final int resolveFlags =
2908                MATCH_DIRECT_BOOT_AWARE
2909                | MATCH_DIRECT_BOOT_UNAWARE
2910                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2911        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2912                resolveFlags, UserHandle.USER_SYSTEM);
2913        if (matches.size() == 0) {
2914            return null;
2915        } else if (matches.size() == 1) {
2916            return matches.get(0).getComponentInfo().getComponentName();
2917        } else {
2918            throw new RuntimeException(
2919                    "There must be at most one ephemeral installer; found " + matches);
2920        }
2921    }
2922
2923    private void primeDomainVerificationsLPw(int userId) {
2924        if (DEBUG_DOMAIN_VERIFICATION) {
2925            Slog.d(TAG, "Priming domain verifications in user " + userId);
2926        }
2927
2928        SystemConfig systemConfig = SystemConfig.getInstance();
2929        ArraySet<String> packages = systemConfig.getLinkedApps();
2930
2931        for (String packageName : packages) {
2932            PackageParser.Package pkg = mPackages.get(packageName);
2933            if (pkg != null) {
2934                if (!pkg.isSystemApp()) {
2935                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2936                    continue;
2937                }
2938
2939                ArraySet<String> domains = null;
2940                for (PackageParser.Activity a : pkg.activities) {
2941                    for (ActivityIntentInfo filter : a.intents) {
2942                        if (hasValidDomains(filter)) {
2943                            if (domains == null) {
2944                                domains = new ArraySet<String>();
2945                            }
2946                            domains.addAll(filter.getHostsList());
2947                        }
2948                    }
2949                }
2950
2951                if (domains != null && domains.size() > 0) {
2952                    if (DEBUG_DOMAIN_VERIFICATION) {
2953                        Slog.v(TAG, "      + " + packageName);
2954                    }
2955                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2956                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2957                    // and then 'always' in the per-user state actually used for intent resolution.
2958                    final IntentFilterVerificationInfo ivi;
2959                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2960                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2961                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2962                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2963                } else {
2964                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2965                            + "' does not handle web links");
2966                }
2967            } else {
2968                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2969            }
2970        }
2971
2972        scheduleWritePackageRestrictionsLocked(userId);
2973        scheduleWriteSettingsLocked();
2974    }
2975
2976    private void applyFactoryDefaultBrowserLPw(int userId) {
2977        // The default browser app's package name is stored in a string resource,
2978        // with a product-specific overlay used for vendor customization.
2979        String browserPkg = mContext.getResources().getString(
2980                com.android.internal.R.string.default_browser);
2981        if (!TextUtils.isEmpty(browserPkg)) {
2982            // non-empty string => required to be a known package
2983            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2984            if (ps == null) {
2985                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2986                browserPkg = null;
2987            } else {
2988                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2989            }
2990        }
2991
2992        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2993        // default.  If there's more than one, just leave everything alone.
2994        if (browserPkg == null) {
2995            calculateDefaultBrowserLPw(userId);
2996        }
2997    }
2998
2999    private void calculateDefaultBrowserLPw(int userId) {
3000        List<String> allBrowsers = resolveAllBrowserApps(userId);
3001        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3002        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3003    }
3004
3005    private List<String> resolveAllBrowserApps(int userId) {
3006        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3007        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3008                PackageManager.MATCH_ALL, userId);
3009
3010        final int count = list.size();
3011        List<String> result = new ArrayList<String>(count);
3012        for (int i=0; i<count; i++) {
3013            ResolveInfo info = list.get(i);
3014            if (info.activityInfo == null
3015                    || !info.handleAllWebDataURI
3016                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3017                    || result.contains(info.activityInfo.packageName)) {
3018                continue;
3019            }
3020            result.add(info.activityInfo.packageName);
3021        }
3022
3023        return result;
3024    }
3025
3026    private boolean packageIsBrowser(String packageName, int userId) {
3027        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3028                PackageManager.MATCH_ALL, userId);
3029        final int N = list.size();
3030        for (int i = 0; i < N; i++) {
3031            ResolveInfo info = list.get(i);
3032            if (packageName.equals(info.activityInfo.packageName)) {
3033                return true;
3034            }
3035        }
3036        return false;
3037    }
3038
3039    private void checkDefaultBrowser() {
3040        final int myUserId = UserHandle.myUserId();
3041        final String packageName = getDefaultBrowserPackageName(myUserId);
3042        if (packageName != null) {
3043            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3044            if (info == null) {
3045                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3046                synchronized (mPackages) {
3047                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3048                }
3049            }
3050        }
3051    }
3052
3053    @Override
3054    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3055            throws RemoteException {
3056        try {
3057            return super.onTransact(code, data, reply, flags);
3058        } catch (RuntimeException e) {
3059            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3060                Slog.wtf(TAG, "Package Manager Crash", e);
3061            }
3062            throw e;
3063        }
3064    }
3065
3066    static int[] appendInts(int[] cur, int[] add) {
3067        if (add == null) return cur;
3068        if (cur == null) return add;
3069        final int N = add.length;
3070        for (int i=0; i<N; i++) {
3071            cur = appendInt(cur, add[i]);
3072        }
3073        return cur;
3074    }
3075
3076    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3077        if (!sUserManager.exists(userId)) return null;
3078        if (ps == null) {
3079            return null;
3080        }
3081        final PackageParser.Package p = ps.pkg;
3082        if (p == null) {
3083            return null;
3084        }
3085
3086        final PermissionsState permissionsState = ps.getPermissionsState();
3087
3088        // Compute GIDs only if requested
3089        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3090                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3091        // Compute granted permissions only if package has requested permissions
3092        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3093                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3094        final PackageUserState state = ps.readUserState(userId);
3095
3096        return PackageParser.generatePackageInfo(p, gids, flags,
3097                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3098    }
3099
3100    @Override
3101    public void checkPackageStartable(String packageName, int userId) {
3102        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3103
3104        synchronized (mPackages) {
3105            final PackageSetting ps = mSettings.mPackages.get(packageName);
3106            if (ps == null) {
3107                throw new SecurityException("Package " + packageName + " was not found!");
3108            }
3109
3110            if (!ps.getInstalled(userId)) {
3111                throw new SecurityException(
3112                        "Package " + packageName + " was not installed for user " + userId + "!");
3113            }
3114
3115            if (mSafeMode && !ps.isSystem()) {
3116                throw new SecurityException("Package " + packageName + " not a system app!");
3117            }
3118
3119            if (mFrozenPackages.contains(packageName)) {
3120                throw new SecurityException("Package " + packageName + " is currently frozen!");
3121            }
3122
3123            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3124                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3125                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3126            }
3127        }
3128    }
3129
3130    @Override
3131    public boolean isPackageAvailable(String packageName, int userId) {
3132        if (!sUserManager.exists(userId)) return false;
3133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3134                false /* requireFullPermission */, false /* checkShell */, "is package available");
3135        synchronized (mPackages) {
3136            PackageParser.Package p = mPackages.get(packageName);
3137            if (p != null) {
3138                final PackageSetting ps = (PackageSetting) p.mExtras;
3139                if (ps != null) {
3140                    final PackageUserState state = ps.readUserState(userId);
3141                    if (state != null) {
3142                        return PackageParser.isAvailable(state);
3143                    }
3144                }
3145            }
3146        }
3147        return false;
3148    }
3149
3150    @Override
3151    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3152        if (!sUserManager.exists(userId)) return null;
3153        flags = updateFlagsForPackage(flags, userId, packageName);
3154        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3155                false /* requireFullPermission */, false /* checkShell */, "get package info");
3156        // reader
3157        synchronized (mPackages) {
3158            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3159            PackageParser.Package p = null;
3160            if (matchFactoryOnly) {
3161                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3162                if (ps != null) {
3163                    return generatePackageInfo(ps, flags, userId);
3164                }
3165            }
3166            if (p == null) {
3167                p = mPackages.get(packageName);
3168                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3169                    return null;
3170                }
3171            }
3172            if (DEBUG_PACKAGE_INFO)
3173                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3174            if (p != null) {
3175                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3176            }
3177            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3178                final PackageSetting ps = mSettings.mPackages.get(packageName);
3179                return generatePackageInfo(ps, flags, userId);
3180            }
3181        }
3182        return null;
3183    }
3184
3185    @Override
3186    public String[] currentToCanonicalPackageNames(String[] names) {
3187        String[] out = new String[names.length];
3188        // reader
3189        synchronized (mPackages) {
3190            for (int i=names.length-1; i>=0; i--) {
3191                PackageSetting ps = mSettings.mPackages.get(names[i]);
3192                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3193            }
3194        }
3195        return out;
3196    }
3197
3198    @Override
3199    public String[] canonicalToCurrentPackageNames(String[] names) {
3200        String[] out = new String[names.length];
3201        // reader
3202        synchronized (mPackages) {
3203            for (int i=names.length-1; i>=0; i--) {
3204                String cur = mSettings.getRenamedPackageLPr(names[i]);
3205                out[i] = cur != null ? cur : names[i];
3206            }
3207        }
3208        return out;
3209    }
3210
3211    @Override
3212    public int getPackageUid(String packageName, int flags, int userId) {
3213        if (!sUserManager.exists(userId)) return -1;
3214        flags = updateFlagsForPackage(flags, userId, packageName);
3215        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3216                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3217
3218        // reader
3219        synchronized (mPackages) {
3220            final PackageParser.Package p = mPackages.get(packageName);
3221            if (p != null && p.isMatch(flags)) {
3222                return UserHandle.getUid(userId, p.applicationInfo.uid);
3223            }
3224            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3225                final PackageSetting ps = mSettings.mPackages.get(packageName);
3226                if (ps != null && ps.isMatch(flags)) {
3227                    return UserHandle.getUid(userId, ps.appId);
3228                }
3229            }
3230        }
3231
3232        return -1;
3233    }
3234
3235    @Override
3236    public int[] getPackageGids(String packageName, int flags, int userId) {
3237        if (!sUserManager.exists(userId)) return null;
3238        flags = updateFlagsForPackage(flags, userId, packageName);
3239        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3240                false /* requireFullPermission */, false /* checkShell */,
3241                "getPackageGids");
3242
3243        // reader
3244        synchronized (mPackages) {
3245            final PackageParser.Package p = mPackages.get(packageName);
3246            if (p != null && p.isMatch(flags)) {
3247                PackageSetting ps = (PackageSetting) p.mExtras;
3248                return ps.getPermissionsState().computeGids(userId);
3249            }
3250            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3251                final PackageSetting ps = mSettings.mPackages.get(packageName);
3252                if (ps != null && ps.isMatch(flags)) {
3253                    return ps.getPermissionsState().computeGids(userId);
3254                }
3255            }
3256        }
3257
3258        return null;
3259    }
3260
3261    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3262        if (bp.perm != null) {
3263            return PackageParser.generatePermissionInfo(bp.perm, flags);
3264        }
3265        PermissionInfo pi = new PermissionInfo();
3266        pi.name = bp.name;
3267        pi.packageName = bp.sourcePackage;
3268        pi.nonLocalizedLabel = bp.name;
3269        pi.protectionLevel = bp.protectionLevel;
3270        return pi;
3271    }
3272
3273    @Override
3274    public PermissionInfo getPermissionInfo(String name, int flags) {
3275        // reader
3276        synchronized (mPackages) {
3277            final BasePermission p = mSettings.mPermissions.get(name);
3278            if (p != null) {
3279                return generatePermissionInfo(p, flags);
3280            }
3281            return null;
3282        }
3283    }
3284
3285    @Override
3286    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3287            int flags) {
3288        // reader
3289        synchronized (mPackages) {
3290            if (group != null && !mPermissionGroups.containsKey(group)) {
3291                // This is thrown as NameNotFoundException
3292                return null;
3293            }
3294
3295            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3296            for (BasePermission p : mSettings.mPermissions.values()) {
3297                if (group == null) {
3298                    if (p.perm == null || p.perm.info.group == null) {
3299                        out.add(generatePermissionInfo(p, flags));
3300                    }
3301                } else {
3302                    if (p.perm != null && group.equals(p.perm.info.group)) {
3303                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3304                    }
3305                }
3306            }
3307            return new ParceledListSlice<>(out);
3308        }
3309    }
3310
3311    @Override
3312    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3313        // reader
3314        synchronized (mPackages) {
3315            return PackageParser.generatePermissionGroupInfo(
3316                    mPermissionGroups.get(name), flags);
3317        }
3318    }
3319
3320    @Override
3321    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3322        // reader
3323        synchronized (mPackages) {
3324            final int N = mPermissionGroups.size();
3325            ArrayList<PermissionGroupInfo> out
3326                    = new ArrayList<PermissionGroupInfo>(N);
3327            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3328                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3329            }
3330            return new ParceledListSlice<>(out);
3331        }
3332    }
3333
3334    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3335            int userId) {
3336        if (!sUserManager.exists(userId)) return null;
3337        PackageSetting ps = mSettings.mPackages.get(packageName);
3338        if (ps != null) {
3339            if (ps.pkg == null) {
3340                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3341                if (pInfo != null) {
3342                    return pInfo.applicationInfo;
3343                }
3344                return null;
3345            }
3346            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3347                    ps.readUserState(userId), userId);
3348        }
3349        return null;
3350    }
3351
3352    @Override
3353    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3354        if (!sUserManager.exists(userId)) return null;
3355        flags = updateFlagsForApplication(flags, userId, packageName);
3356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3357                false /* requireFullPermission */, false /* checkShell */, "get application info");
3358        // writer
3359        synchronized (mPackages) {
3360            PackageParser.Package p = mPackages.get(packageName);
3361            if (DEBUG_PACKAGE_INFO) Log.v(
3362                    TAG, "getApplicationInfo " + packageName
3363                    + ": " + p);
3364            if (p != null) {
3365                PackageSetting ps = mSettings.mPackages.get(packageName);
3366                if (ps == null) return null;
3367                // Note: isEnabledLP() does not apply here - always return info
3368                return PackageParser.generateApplicationInfo(
3369                        p, flags, ps.readUserState(userId), userId);
3370            }
3371            if ("android".equals(packageName)||"system".equals(packageName)) {
3372                return mAndroidApplication;
3373            }
3374            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3375                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3376            }
3377        }
3378        return null;
3379    }
3380
3381    @Override
3382    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3383            final IPackageDataObserver observer) {
3384        mContext.enforceCallingOrSelfPermission(
3385                android.Manifest.permission.CLEAR_APP_CACHE, null);
3386        // Queue up an async operation since clearing cache may take a little while.
3387        mHandler.post(new Runnable() {
3388            public void run() {
3389                mHandler.removeCallbacks(this);
3390                boolean success = true;
3391                synchronized (mInstallLock) {
3392                    try {
3393                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3394                    } catch (InstallerException e) {
3395                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3396                        success = false;
3397                    }
3398                }
3399                if (observer != null) {
3400                    try {
3401                        observer.onRemoveCompleted(null, success);
3402                    } catch (RemoteException e) {
3403                        Slog.w(TAG, "RemoveException when invoking call back");
3404                    }
3405                }
3406            }
3407        });
3408    }
3409
3410    @Override
3411    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3412            final IntentSender pi) {
3413        mContext.enforceCallingOrSelfPermission(
3414                android.Manifest.permission.CLEAR_APP_CACHE, null);
3415        // Queue up an async operation since clearing cache may take a little while.
3416        mHandler.post(new Runnable() {
3417            public void run() {
3418                mHandler.removeCallbacks(this);
3419                boolean success = true;
3420                synchronized (mInstallLock) {
3421                    try {
3422                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3423                    } catch (InstallerException e) {
3424                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3425                        success = false;
3426                    }
3427                }
3428                if(pi != null) {
3429                    try {
3430                        // Callback via pending intent
3431                        int code = success ? 1 : 0;
3432                        pi.sendIntent(null, code, null,
3433                                null, null);
3434                    } catch (SendIntentException e1) {
3435                        Slog.i(TAG, "Failed to send pending intent");
3436                    }
3437                }
3438            }
3439        });
3440    }
3441
3442    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3443        synchronized (mInstallLock) {
3444            try {
3445                mInstaller.freeCache(volumeUuid, freeStorageSize);
3446            } catch (InstallerException e) {
3447                throw new IOException("Failed to free enough space", e);
3448            }
3449        }
3450    }
3451
3452    /**
3453     * Update given flags based on encryption status of current user.
3454     */
3455    private int updateFlags(int flags, int userId) {
3456        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3457                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3458            // Caller expressed an explicit opinion about what encryption
3459            // aware/unaware components they want to see, so fall through and
3460            // give them what they want
3461        } else {
3462            // Caller expressed no opinion, so match based on user state
3463            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3464                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3465            } else {
3466                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3467            }
3468        }
3469        return flags;
3470    }
3471
3472    private UserManagerInternal getUserManagerInternal() {
3473        if (mUserManagerInternal == null) {
3474            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3475        }
3476        return mUserManagerInternal;
3477    }
3478
3479    /**
3480     * Update given flags when being used to request {@link PackageInfo}.
3481     */
3482    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3483        boolean triaged = true;
3484        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3485                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3486            // Caller is asking for component details, so they'd better be
3487            // asking for specific encryption matching behavior, or be triaged
3488            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3489                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3490                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3491                triaged = false;
3492            }
3493        }
3494        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3495                | PackageManager.MATCH_SYSTEM_ONLY
3496                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3497            triaged = false;
3498        }
3499        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3500            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3501                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3502        }
3503        return updateFlags(flags, userId);
3504    }
3505
3506    /**
3507     * Update given flags when being used to request {@link ApplicationInfo}.
3508     */
3509    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3510        return updateFlagsForPackage(flags, userId, cookie);
3511    }
3512
3513    /**
3514     * Update given flags when being used to request {@link ComponentInfo}.
3515     */
3516    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3517        if (cookie instanceof Intent) {
3518            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3519                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3520            }
3521        }
3522
3523        boolean triaged = true;
3524        // Caller is asking for component details, so they'd better be
3525        // asking for specific encryption matching behavior, or be triaged
3526        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3527                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3528                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3529            triaged = false;
3530        }
3531        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3532            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3533                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3534        }
3535
3536        return updateFlags(flags, userId);
3537    }
3538
3539    /**
3540     * Update given flags when being used to request {@link ResolveInfo}.
3541     */
3542    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3543        // Safe mode means we shouldn't match any third-party components
3544        if (mSafeMode) {
3545            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3546        }
3547
3548        return updateFlagsForComponent(flags, userId, cookie);
3549    }
3550
3551    @Override
3552    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3553        if (!sUserManager.exists(userId)) return null;
3554        flags = updateFlagsForComponent(flags, userId, component);
3555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3556                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3557        synchronized (mPackages) {
3558            PackageParser.Activity a = mActivities.mActivities.get(component);
3559
3560            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3561            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3562                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3563                if (ps == null) return null;
3564                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3565                        userId);
3566            }
3567            if (mResolveComponentName.equals(component)) {
3568                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3569                        new PackageUserState(), userId);
3570            }
3571        }
3572        return null;
3573    }
3574
3575    @Override
3576    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3577            String resolvedType) {
3578        synchronized (mPackages) {
3579            if (component.equals(mResolveComponentName)) {
3580                // The resolver supports EVERYTHING!
3581                return true;
3582            }
3583            PackageParser.Activity a = mActivities.mActivities.get(component);
3584            if (a == null) {
3585                return false;
3586            }
3587            for (int i=0; i<a.intents.size(); i++) {
3588                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3589                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3590                    return true;
3591                }
3592            }
3593            return false;
3594        }
3595    }
3596
3597    @Override
3598    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3599        if (!sUserManager.exists(userId)) return null;
3600        flags = updateFlagsForComponent(flags, userId, component);
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3602                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3603        synchronized (mPackages) {
3604            PackageParser.Activity a = mReceivers.mActivities.get(component);
3605            if (DEBUG_PACKAGE_INFO) Log.v(
3606                TAG, "getReceiverInfo " + component + ": " + a);
3607            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3608                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3609                if (ps == null) return null;
3610                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3611                        userId);
3612            }
3613        }
3614        return null;
3615    }
3616
3617    @Override
3618    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3619        if (!sUserManager.exists(userId)) return null;
3620        flags = updateFlagsForComponent(flags, userId, component);
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3622                false /* requireFullPermission */, false /* checkShell */, "get service info");
3623        synchronized (mPackages) {
3624            PackageParser.Service s = mServices.mServices.get(component);
3625            if (DEBUG_PACKAGE_INFO) Log.v(
3626                TAG, "getServiceInfo " + component + ": " + s);
3627            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3628                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3629                if (ps == null) return null;
3630                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3631                        userId);
3632            }
3633        }
3634        return null;
3635    }
3636
3637    @Override
3638    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3639        if (!sUserManager.exists(userId)) return null;
3640        flags = updateFlagsForComponent(flags, userId, component);
3641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3642                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3643        synchronized (mPackages) {
3644            PackageParser.Provider p = mProviders.mProviders.get(component);
3645            if (DEBUG_PACKAGE_INFO) Log.v(
3646                TAG, "getProviderInfo " + component + ": " + p);
3647            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3648                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3649                if (ps == null) return null;
3650                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3651                        userId);
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public String[] getSystemSharedLibraryNames() {
3659        Set<String> libSet;
3660        synchronized (mPackages) {
3661            libSet = mSharedLibraries.keySet();
3662            int size = libSet.size();
3663            if (size > 0) {
3664                String[] libs = new String[size];
3665                libSet.toArray(libs);
3666                return libs;
3667            }
3668        }
3669        return null;
3670    }
3671
3672    @Override
3673    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3674        synchronized (mPackages) {
3675            return mServicesSystemSharedLibraryPackageName;
3676        }
3677    }
3678
3679    @Override
3680    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3681        synchronized (mPackages) {
3682            return mSharedSystemSharedLibraryPackageName;
3683        }
3684    }
3685
3686    @Override
3687    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3688        synchronized (mPackages) {
3689            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3690
3691            final FeatureInfo fi = new FeatureInfo();
3692            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3693                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3694            res.add(fi);
3695
3696            return new ParceledListSlice<>(res);
3697        }
3698    }
3699
3700    @Override
3701    public boolean hasSystemFeature(String name, int version) {
3702        synchronized (mPackages) {
3703            final FeatureInfo feat = mAvailableFeatures.get(name);
3704            if (feat == null) {
3705                return false;
3706            } else {
3707                return feat.version >= version;
3708            }
3709        }
3710    }
3711
3712    @Override
3713    public int checkPermission(String permName, String pkgName, int userId) {
3714        if (!sUserManager.exists(userId)) {
3715            return PackageManager.PERMISSION_DENIED;
3716        }
3717
3718        synchronized (mPackages) {
3719            final PackageParser.Package p = mPackages.get(pkgName);
3720            if (p != null && p.mExtras != null) {
3721                final PackageSetting ps = (PackageSetting) p.mExtras;
3722                final PermissionsState permissionsState = ps.getPermissionsState();
3723                if (permissionsState.hasPermission(permName, userId)) {
3724                    return PackageManager.PERMISSION_GRANTED;
3725                }
3726                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3727                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3728                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3729                    return PackageManager.PERMISSION_GRANTED;
3730                }
3731            }
3732        }
3733
3734        return PackageManager.PERMISSION_DENIED;
3735    }
3736
3737    @Override
3738    public int checkUidPermission(String permName, int uid) {
3739        final int userId = UserHandle.getUserId(uid);
3740
3741        if (!sUserManager.exists(userId)) {
3742            return PackageManager.PERMISSION_DENIED;
3743        }
3744
3745        synchronized (mPackages) {
3746            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3747            if (obj != null) {
3748                final SettingBase ps = (SettingBase) obj;
3749                final PermissionsState permissionsState = ps.getPermissionsState();
3750                if (permissionsState.hasPermission(permName, userId)) {
3751                    return PackageManager.PERMISSION_GRANTED;
3752                }
3753                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3754                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3755                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3756                    return PackageManager.PERMISSION_GRANTED;
3757                }
3758            } else {
3759                ArraySet<String> perms = mSystemPermissions.get(uid);
3760                if (perms != null) {
3761                    if (perms.contains(permName)) {
3762                        return PackageManager.PERMISSION_GRANTED;
3763                    }
3764                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3765                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3766                        return PackageManager.PERMISSION_GRANTED;
3767                    }
3768                }
3769            }
3770        }
3771
3772        return PackageManager.PERMISSION_DENIED;
3773    }
3774
3775    @Override
3776    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3777        if (UserHandle.getCallingUserId() != userId) {
3778            mContext.enforceCallingPermission(
3779                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3780                    "isPermissionRevokedByPolicy for user " + userId);
3781        }
3782
3783        if (checkPermission(permission, packageName, userId)
3784                == PackageManager.PERMISSION_GRANTED) {
3785            return false;
3786        }
3787
3788        final long identity = Binder.clearCallingIdentity();
3789        try {
3790            final int flags = getPermissionFlags(permission, packageName, userId);
3791            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3792        } finally {
3793            Binder.restoreCallingIdentity(identity);
3794        }
3795    }
3796
3797    @Override
3798    public String getPermissionControllerPackageName() {
3799        synchronized (mPackages) {
3800            return mRequiredInstallerPackage;
3801        }
3802    }
3803
3804    /**
3805     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3806     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3807     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3808     * @param message the message to log on security exception
3809     */
3810    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3811            boolean checkShell, String message) {
3812        if (userId < 0) {
3813            throw new IllegalArgumentException("Invalid userId " + userId);
3814        }
3815        if (checkShell) {
3816            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3817        }
3818        if (userId == UserHandle.getUserId(callingUid)) return;
3819        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3820            if (requireFullPermission) {
3821                mContext.enforceCallingOrSelfPermission(
3822                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3823            } else {
3824                try {
3825                    mContext.enforceCallingOrSelfPermission(
3826                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3827                } catch (SecurityException se) {
3828                    mContext.enforceCallingOrSelfPermission(
3829                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3830                }
3831            }
3832        }
3833    }
3834
3835    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3836        if (callingUid == Process.SHELL_UID) {
3837            if (userHandle >= 0
3838                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3839                throw new SecurityException("Shell does not have permission to access user "
3840                        + userHandle);
3841            } else if (userHandle < 0) {
3842                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3843                        + Debug.getCallers(3));
3844            }
3845        }
3846    }
3847
3848    private BasePermission findPermissionTreeLP(String permName) {
3849        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3850            if (permName.startsWith(bp.name) &&
3851                    permName.length() > bp.name.length() &&
3852                    permName.charAt(bp.name.length()) == '.') {
3853                return bp;
3854            }
3855        }
3856        return null;
3857    }
3858
3859    private BasePermission checkPermissionTreeLP(String permName) {
3860        if (permName != null) {
3861            BasePermission bp = findPermissionTreeLP(permName);
3862            if (bp != null) {
3863                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3864                    return bp;
3865                }
3866                throw new SecurityException("Calling uid "
3867                        + Binder.getCallingUid()
3868                        + " is not allowed to add to permission tree "
3869                        + bp.name + " owned by uid " + bp.uid);
3870            }
3871        }
3872        throw new SecurityException("No permission tree found for " + permName);
3873    }
3874
3875    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3876        if (s1 == null) {
3877            return s2 == null;
3878        }
3879        if (s2 == null) {
3880            return false;
3881        }
3882        if (s1.getClass() != s2.getClass()) {
3883            return false;
3884        }
3885        return s1.equals(s2);
3886    }
3887
3888    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3889        if (pi1.icon != pi2.icon) return false;
3890        if (pi1.logo != pi2.logo) return false;
3891        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3892        if (!compareStrings(pi1.name, pi2.name)) return false;
3893        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3894        // We'll take care of setting this one.
3895        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3896        // These are not currently stored in settings.
3897        //if (!compareStrings(pi1.group, pi2.group)) return false;
3898        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3899        //if (pi1.labelRes != pi2.labelRes) return false;
3900        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3901        return true;
3902    }
3903
3904    int permissionInfoFootprint(PermissionInfo info) {
3905        int size = info.name.length();
3906        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3907        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3908        return size;
3909    }
3910
3911    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3912        int size = 0;
3913        for (BasePermission perm : mSettings.mPermissions.values()) {
3914            if (perm.uid == tree.uid) {
3915                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3916            }
3917        }
3918        return size;
3919    }
3920
3921    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3922        // We calculate the max size of permissions defined by this uid and throw
3923        // if that plus the size of 'info' would exceed our stated maximum.
3924        if (tree.uid != Process.SYSTEM_UID) {
3925            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3926            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3927                throw new SecurityException("Permission tree size cap exceeded");
3928            }
3929        }
3930    }
3931
3932    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3933        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3934            throw new SecurityException("Label must be specified in permission");
3935        }
3936        BasePermission tree = checkPermissionTreeLP(info.name);
3937        BasePermission bp = mSettings.mPermissions.get(info.name);
3938        boolean added = bp == null;
3939        boolean changed = true;
3940        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3941        if (added) {
3942            enforcePermissionCapLocked(info, tree);
3943            bp = new BasePermission(info.name, tree.sourcePackage,
3944                    BasePermission.TYPE_DYNAMIC);
3945        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3946            throw new SecurityException(
3947                    "Not allowed to modify non-dynamic permission "
3948                    + info.name);
3949        } else {
3950            if (bp.protectionLevel == fixedLevel
3951                    && bp.perm.owner.equals(tree.perm.owner)
3952                    && bp.uid == tree.uid
3953                    && comparePermissionInfos(bp.perm.info, info)) {
3954                changed = false;
3955            }
3956        }
3957        bp.protectionLevel = fixedLevel;
3958        info = new PermissionInfo(info);
3959        info.protectionLevel = fixedLevel;
3960        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3961        bp.perm.info.packageName = tree.perm.info.packageName;
3962        bp.uid = tree.uid;
3963        if (added) {
3964            mSettings.mPermissions.put(info.name, bp);
3965        }
3966        if (changed) {
3967            if (!async) {
3968                mSettings.writeLPr();
3969            } else {
3970                scheduleWriteSettingsLocked();
3971            }
3972        }
3973        return added;
3974    }
3975
3976    @Override
3977    public boolean addPermission(PermissionInfo info) {
3978        synchronized (mPackages) {
3979            return addPermissionLocked(info, false);
3980        }
3981    }
3982
3983    @Override
3984    public boolean addPermissionAsync(PermissionInfo info) {
3985        synchronized (mPackages) {
3986            return addPermissionLocked(info, true);
3987        }
3988    }
3989
3990    @Override
3991    public void removePermission(String name) {
3992        synchronized (mPackages) {
3993            checkPermissionTreeLP(name);
3994            BasePermission bp = mSettings.mPermissions.get(name);
3995            if (bp != null) {
3996                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3997                    throw new SecurityException(
3998                            "Not allowed to modify non-dynamic permission "
3999                            + name);
4000                }
4001                mSettings.mPermissions.remove(name);
4002                mSettings.writeLPr();
4003            }
4004        }
4005    }
4006
4007    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4008            BasePermission bp) {
4009        int index = pkg.requestedPermissions.indexOf(bp.name);
4010        if (index == -1) {
4011            throw new SecurityException("Package " + pkg.packageName
4012                    + " has not requested permission " + bp.name);
4013        }
4014        if (!bp.isRuntime() && !bp.isDevelopment()) {
4015            throw new SecurityException("Permission " + bp.name
4016                    + " is not a changeable permission type");
4017        }
4018    }
4019
4020    @Override
4021    public void grantRuntimePermission(String packageName, String name, final int userId) {
4022        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4023    }
4024
4025    private void grantRuntimePermission(String packageName, String name, final int userId,
4026            boolean overridePolicy) {
4027        if (!sUserManager.exists(userId)) {
4028            Log.e(TAG, "No such user:" + userId);
4029            return;
4030        }
4031
4032        mContext.enforceCallingOrSelfPermission(
4033                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4034                "grantRuntimePermission");
4035
4036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4037                true /* requireFullPermission */, true /* checkShell */,
4038                "grantRuntimePermission");
4039
4040        final int uid;
4041        final SettingBase sb;
4042
4043        synchronized (mPackages) {
4044            final PackageParser.Package pkg = mPackages.get(packageName);
4045            if (pkg == null) {
4046                throw new IllegalArgumentException("Unknown package: " + packageName);
4047            }
4048
4049            final BasePermission bp = mSettings.mPermissions.get(name);
4050            if (bp == null) {
4051                throw new IllegalArgumentException("Unknown permission: " + name);
4052            }
4053
4054            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4055
4056            // If a permission review is required for legacy apps we represent
4057            // their permissions as always granted runtime ones since we need
4058            // to keep the review required permission flag per user while an
4059            // install permission's state is shared across all users.
4060            if (mPermissionReviewRequired
4061                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4062                    && bp.isRuntime()) {
4063                return;
4064            }
4065
4066            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4067            sb = (SettingBase) pkg.mExtras;
4068            if (sb == null) {
4069                throw new IllegalArgumentException("Unknown package: " + packageName);
4070            }
4071
4072            final PermissionsState permissionsState = sb.getPermissionsState();
4073
4074            final int flags = permissionsState.getPermissionFlags(name, userId);
4075            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4076                throw new SecurityException("Cannot grant system fixed permission "
4077                        + name + " for package " + packageName);
4078            }
4079            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4080                throw new SecurityException("Cannot grant policy fixed permission "
4081                        + name + " for package " + packageName);
4082            }
4083
4084            if (bp.isDevelopment()) {
4085                // Development permissions must be handled specially, since they are not
4086                // normal runtime permissions.  For now they apply to all users.
4087                if (permissionsState.grantInstallPermission(bp) !=
4088                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4089                    scheduleWriteSettingsLocked();
4090                }
4091                return;
4092            }
4093
4094            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4095                throw new SecurityException("Cannot grant non-ephemeral permission"
4096                        + name + " for package " + packageName);
4097            }
4098
4099            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4100                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4101                return;
4102            }
4103
4104            final int result = permissionsState.grantRuntimePermission(bp, userId);
4105            switch (result) {
4106                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4107                    return;
4108                }
4109
4110                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4111                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4112                    mHandler.post(new Runnable() {
4113                        @Override
4114                        public void run() {
4115                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4116                        }
4117                    });
4118                }
4119                break;
4120            }
4121
4122            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4123
4124            // Not critical if that is lost - app has to request again.
4125            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4126        }
4127
4128        // Only need to do this if user is initialized. Otherwise it's a new user
4129        // and there are no processes running as the user yet and there's no need
4130        // to make an expensive call to remount processes for the changed permissions.
4131        if (READ_EXTERNAL_STORAGE.equals(name)
4132                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4133            final long token = Binder.clearCallingIdentity();
4134            try {
4135                if (sUserManager.isInitialized(userId)) {
4136                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4137                            MountServiceInternal.class);
4138                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4139                }
4140            } finally {
4141                Binder.restoreCallingIdentity(token);
4142            }
4143        }
4144    }
4145
4146    @Override
4147    public void revokeRuntimePermission(String packageName, String name, int userId) {
4148        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4149    }
4150
4151    private void revokeRuntimePermission(String packageName, String name, int userId,
4152            boolean overridePolicy) {
4153        if (!sUserManager.exists(userId)) {
4154            Log.e(TAG, "No such user:" + userId);
4155            return;
4156        }
4157
4158        mContext.enforceCallingOrSelfPermission(
4159                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4160                "revokeRuntimePermission");
4161
4162        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4163                true /* requireFullPermission */, true /* checkShell */,
4164                "revokeRuntimePermission");
4165
4166        final int appId;
4167
4168        synchronized (mPackages) {
4169            final PackageParser.Package pkg = mPackages.get(packageName);
4170            if (pkg == null) {
4171                throw new IllegalArgumentException("Unknown package: " + packageName);
4172            }
4173
4174            final BasePermission bp = mSettings.mPermissions.get(name);
4175            if (bp == null) {
4176                throw new IllegalArgumentException("Unknown permission: " + name);
4177            }
4178
4179            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4180
4181            // If a permission review is required for legacy apps we represent
4182            // their permissions as always granted runtime ones since we need
4183            // to keep the review required permission flag per user while an
4184            // install permission's state is shared across all users.
4185            if (mPermissionReviewRequired
4186                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4187                    && bp.isRuntime()) {
4188                return;
4189            }
4190
4191            SettingBase sb = (SettingBase) pkg.mExtras;
4192            if (sb == null) {
4193                throw new IllegalArgumentException("Unknown package: " + packageName);
4194            }
4195
4196            final PermissionsState permissionsState = sb.getPermissionsState();
4197
4198            final int flags = permissionsState.getPermissionFlags(name, userId);
4199            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4200                throw new SecurityException("Cannot revoke system fixed permission "
4201                        + name + " for package " + packageName);
4202            }
4203            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4204                throw new SecurityException("Cannot revoke policy fixed permission "
4205                        + name + " for package " + packageName);
4206            }
4207
4208            if (bp.isDevelopment()) {
4209                // Development permissions must be handled specially, since they are not
4210                // normal runtime permissions.  For now they apply to all users.
4211                if (permissionsState.revokeInstallPermission(bp) !=
4212                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4213                    scheduleWriteSettingsLocked();
4214                }
4215                return;
4216            }
4217
4218            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4219                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4220                return;
4221            }
4222
4223            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4224
4225            // Critical, after this call app should never have the permission.
4226            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4227
4228            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4229        }
4230
4231        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4232    }
4233
4234    @Override
4235    public void resetRuntimePermissions() {
4236        mContext.enforceCallingOrSelfPermission(
4237                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4238                "revokeRuntimePermission");
4239
4240        int callingUid = Binder.getCallingUid();
4241        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4242            mContext.enforceCallingOrSelfPermission(
4243                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4244                    "resetRuntimePermissions");
4245        }
4246
4247        synchronized (mPackages) {
4248            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4249            for (int userId : UserManagerService.getInstance().getUserIds()) {
4250                final int packageCount = mPackages.size();
4251                for (int i = 0; i < packageCount; i++) {
4252                    PackageParser.Package pkg = mPackages.valueAt(i);
4253                    if (!(pkg.mExtras instanceof PackageSetting)) {
4254                        continue;
4255                    }
4256                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4257                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4258                }
4259            }
4260        }
4261    }
4262
4263    @Override
4264    public int getPermissionFlags(String name, String packageName, int userId) {
4265        if (!sUserManager.exists(userId)) {
4266            return 0;
4267        }
4268
4269        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4270
4271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4272                true /* requireFullPermission */, false /* checkShell */,
4273                "getPermissionFlags");
4274
4275        synchronized (mPackages) {
4276            final PackageParser.Package pkg = mPackages.get(packageName);
4277            if (pkg == null) {
4278                return 0;
4279            }
4280
4281            final BasePermission bp = mSettings.mPermissions.get(name);
4282            if (bp == null) {
4283                return 0;
4284            }
4285
4286            SettingBase sb = (SettingBase) pkg.mExtras;
4287            if (sb == null) {
4288                return 0;
4289            }
4290
4291            PermissionsState permissionsState = sb.getPermissionsState();
4292            return permissionsState.getPermissionFlags(name, userId);
4293        }
4294    }
4295
4296    @Override
4297    public void updatePermissionFlags(String name, String packageName, int flagMask,
4298            int flagValues, int userId) {
4299        if (!sUserManager.exists(userId)) {
4300            return;
4301        }
4302
4303        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4304
4305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4306                true /* requireFullPermission */, true /* checkShell */,
4307                "updatePermissionFlags");
4308
4309        // Only the system can change these flags and nothing else.
4310        if (getCallingUid() != Process.SYSTEM_UID) {
4311            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4312            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4313            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4314            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4315            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4316        }
4317
4318        synchronized (mPackages) {
4319            final PackageParser.Package pkg = mPackages.get(packageName);
4320            if (pkg == null) {
4321                throw new IllegalArgumentException("Unknown package: " + packageName);
4322            }
4323
4324            final BasePermission bp = mSettings.mPermissions.get(name);
4325            if (bp == null) {
4326                throw new IllegalArgumentException("Unknown permission: " + name);
4327            }
4328
4329            SettingBase sb = (SettingBase) pkg.mExtras;
4330            if (sb == null) {
4331                throw new IllegalArgumentException("Unknown package: " + packageName);
4332            }
4333
4334            PermissionsState permissionsState = sb.getPermissionsState();
4335
4336            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4337
4338            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4339                // Install and runtime permissions are stored in different places,
4340                // so figure out what permission changed and persist the change.
4341                if (permissionsState.getInstallPermissionState(name) != null) {
4342                    scheduleWriteSettingsLocked();
4343                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4344                        || hadState) {
4345                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4346                }
4347            }
4348        }
4349    }
4350
4351    /**
4352     * Update the permission flags for all packages and runtime permissions of a user in order
4353     * to allow device or profile owner to remove POLICY_FIXED.
4354     */
4355    @Override
4356    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4357        if (!sUserManager.exists(userId)) {
4358            return;
4359        }
4360
4361        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4362
4363        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4364                true /* requireFullPermission */, true /* checkShell */,
4365                "updatePermissionFlagsForAllApps");
4366
4367        // Only the system can change system fixed flags.
4368        if (getCallingUid() != Process.SYSTEM_UID) {
4369            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4370            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4371        }
4372
4373        synchronized (mPackages) {
4374            boolean changed = false;
4375            final int packageCount = mPackages.size();
4376            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4377                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4378                SettingBase sb = (SettingBase) pkg.mExtras;
4379                if (sb == null) {
4380                    continue;
4381                }
4382                PermissionsState permissionsState = sb.getPermissionsState();
4383                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4384                        userId, flagMask, flagValues);
4385            }
4386            if (changed) {
4387                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4388            }
4389        }
4390    }
4391
4392    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4393        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4394                != PackageManager.PERMISSION_GRANTED
4395            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4396                != PackageManager.PERMISSION_GRANTED) {
4397            throw new SecurityException(message + " requires "
4398                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4399                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4400        }
4401    }
4402
4403    @Override
4404    public boolean shouldShowRequestPermissionRationale(String permissionName,
4405            String packageName, int userId) {
4406        if (UserHandle.getCallingUserId() != userId) {
4407            mContext.enforceCallingPermission(
4408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4409                    "canShowRequestPermissionRationale for user " + userId);
4410        }
4411
4412        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4413        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4414            return false;
4415        }
4416
4417        if (checkPermission(permissionName, packageName, userId)
4418                == PackageManager.PERMISSION_GRANTED) {
4419            return false;
4420        }
4421
4422        final int flags;
4423
4424        final long identity = Binder.clearCallingIdentity();
4425        try {
4426            flags = getPermissionFlags(permissionName,
4427                    packageName, userId);
4428        } finally {
4429            Binder.restoreCallingIdentity(identity);
4430        }
4431
4432        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4433                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4434                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4435
4436        if ((flags & fixedFlags) != 0) {
4437            return false;
4438        }
4439
4440        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4441    }
4442
4443    @Override
4444    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4445        mContext.enforceCallingOrSelfPermission(
4446                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4447                "addOnPermissionsChangeListener");
4448
4449        synchronized (mPackages) {
4450            mOnPermissionChangeListeners.addListenerLocked(listener);
4451        }
4452    }
4453
4454    @Override
4455    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4456        synchronized (mPackages) {
4457            mOnPermissionChangeListeners.removeListenerLocked(listener);
4458        }
4459    }
4460
4461    @Override
4462    public boolean isProtectedBroadcast(String actionName) {
4463        synchronized (mPackages) {
4464            if (mProtectedBroadcasts.contains(actionName)) {
4465                return true;
4466            } else if (actionName != null) {
4467                // TODO: remove these terrible hacks
4468                if (actionName.startsWith("android.net.netmon.lingerExpired")
4469                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4470                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4471                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4472                    return true;
4473                }
4474            }
4475        }
4476        return false;
4477    }
4478
4479    @Override
4480    public int checkSignatures(String pkg1, String pkg2) {
4481        synchronized (mPackages) {
4482            final PackageParser.Package p1 = mPackages.get(pkg1);
4483            final PackageParser.Package p2 = mPackages.get(pkg2);
4484            if (p1 == null || p1.mExtras == null
4485                    || p2 == null || p2.mExtras == null) {
4486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4487            }
4488            return compareSignatures(p1.mSignatures, p2.mSignatures);
4489        }
4490    }
4491
4492    @Override
4493    public int checkUidSignatures(int uid1, int uid2) {
4494        // Map to base uids.
4495        uid1 = UserHandle.getAppId(uid1);
4496        uid2 = UserHandle.getAppId(uid2);
4497        // reader
4498        synchronized (mPackages) {
4499            Signature[] s1;
4500            Signature[] s2;
4501            Object obj = mSettings.getUserIdLPr(uid1);
4502            if (obj != null) {
4503                if (obj instanceof SharedUserSetting) {
4504                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4505                } else if (obj instanceof PackageSetting) {
4506                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4507                } else {
4508                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4509                }
4510            } else {
4511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4512            }
4513            obj = mSettings.getUserIdLPr(uid2);
4514            if (obj != null) {
4515                if (obj instanceof SharedUserSetting) {
4516                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4517                } else if (obj instanceof PackageSetting) {
4518                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4519                } else {
4520                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4521                }
4522            } else {
4523                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4524            }
4525            return compareSignatures(s1, s2);
4526        }
4527    }
4528
4529    /**
4530     * This method should typically only be used when granting or revoking
4531     * permissions, since the app may immediately restart after this call.
4532     * <p>
4533     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4534     * guard your work against the app being relaunched.
4535     */
4536    private void killUid(int appId, int userId, String reason) {
4537        final long identity = Binder.clearCallingIdentity();
4538        try {
4539            IActivityManager am = ActivityManager.getService();
4540            if (am != null) {
4541                try {
4542                    am.killUid(appId, userId, reason);
4543                } catch (RemoteException e) {
4544                    /* ignore - same process */
4545                }
4546            }
4547        } finally {
4548            Binder.restoreCallingIdentity(identity);
4549        }
4550    }
4551
4552    /**
4553     * Compares two sets of signatures. Returns:
4554     * <br />
4555     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4556     * <br />
4557     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4558     * <br />
4559     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4560     * <br />
4561     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4562     * <br />
4563     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4564     */
4565    static int compareSignatures(Signature[] s1, Signature[] s2) {
4566        if (s1 == null) {
4567            return s2 == null
4568                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4569                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4570        }
4571
4572        if (s2 == null) {
4573            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4574        }
4575
4576        if (s1.length != s2.length) {
4577            return PackageManager.SIGNATURE_NO_MATCH;
4578        }
4579
4580        // Since both signature sets are of size 1, we can compare without HashSets.
4581        if (s1.length == 1) {
4582            return s1[0].equals(s2[0]) ?
4583                    PackageManager.SIGNATURE_MATCH :
4584                    PackageManager.SIGNATURE_NO_MATCH;
4585        }
4586
4587        ArraySet<Signature> set1 = new ArraySet<Signature>();
4588        for (Signature sig : s1) {
4589            set1.add(sig);
4590        }
4591        ArraySet<Signature> set2 = new ArraySet<Signature>();
4592        for (Signature sig : s2) {
4593            set2.add(sig);
4594        }
4595        // Make sure s2 contains all signatures in s1.
4596        if (set1.equals(set2)) {
4597            return PackageManager.SIGNATURE_MATCH;
4598        }
4599        return PackageManager.SIGNATURE_NO_MATCH;
4600    }
4601
4602    /**
4603     * If the database version for this type of package (internal storage or
4604     * external storage) is less than the version where package signatures
4605     * were updated, return true.
4606     */
4607    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4608        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4609        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4610    }
4611
4612    /**
4613     * Used for backward compatibility to make sure any packages with
4614     * certificate chains get upgraded to the new style. {@code existingSigs}
4615     * will be in the old format (since they were stored on disk from before the
4616     * system upgrade) and {@code scannedSigs} will be in the newer format.
4617     */
4618    private int compareSignaturesCompat(PackageSignatures existingSigs,
4619            PackageParser.Package scannedPkg) {
4620        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4621            return PackageManager.SIGNATURE_NO_MATCH;
4622        }
4623
4624        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4625        for (Signature sig : existingSigs.mSignatures) {
4626            existingSet.add(sig);
4627        }
4628        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4629        for (Signature sig : scannedPkg.mSignatures) {
4630            try {
4631                Signature[] chainSignatures = sig.getChainSignatures();
4632                for (Signature chainSig : chainSignatures) {
4633                    scannedCompatSet.add(chainSig);
4634                }
4635            } catch (CertificateEncodingException e) {
4636                scannedCompatSet.add(sig);
4637            }
4638        }
4639        /*
4640         * Make sure the expanded scanned set contains all signatures in the
4641         * existing one.
4642         */
4643        if (scannedCompatSet.equals(existingSet)) {
4644            // Migrate the old signatures to the new scheme.
4645            existingSigs.assignSignatures(scannedPkg.mSignatures);
4646            // The new KeySets will be re-added later in the scanning process.
4647            synchronized (mPackages) {
4648                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4649            }
4650            return PackageManager.SIGNATURE_MATCH;
4651        }
4652        return PackageManager.SIGNATURE_NO_MATCH;
4653    }
4654
4655    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4656        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4657        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4658    }
4659
4660    private int compareSignaturesRecover(PackageSignatures existingSigs,
4661            PackageParser.Package scannedPkg) {
4662        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4663            return PackageManager.SIGNATURE_NO_MATCH;
4664        }
4665
4666        String msg = null;
4667        try {
4668            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4669                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4670                        + scannedPkg.packageName);
4671                return PackageManager.SIGNATURE_MATCH;
4672            }
4673        } catch (CertificateException e) {
4674            msg = e.getMessage();
4675        }
4676
4677        logCriticalInfo(Log.INFO,
4678                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4679        return PackageManager.SIGNATURE_NO_MATCH;
4680    }
4681
4682    @Override
4683    public List<String> getAllPackages() {
4684        synchronized (mPackages) {
4685            return new ArrayList<String>(mPackages.keySet());
4686        }
4687    }
4688
4689    @Override
4690    public String[] getPackagesForUid(int uid) {
4691        final int userId = UserHandle.getUserId(uid);
4692        uid = UserHandle.getAppId(uid);
4693        // reader
4694        synchronized (mPackages) {
4695            Object obj = mSettings.getUserIdLPr(uid);
4696            if (obj instanceof SharedUserSetting) {
4697                final SharedUserSetting sus = (SharedUserSetting) obj;
4698                final int N = sus.packages.size();
4699                String[] res = new String[N];
4700                final Iterator<PackageSetting> it = sus.packages.iterator();
4701                int i = 0;
4702                while (it.hasNext()) {
4703                    PackageSetting ps = it.next();
4704                    if (ps.getInstalled(userId)) {
4705                        res[i++] = ps.name;
4706                    } else {
4707                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4708                    }
4709                }
4710                return res;
4711            } else if (obj instanceof PackageSetting) {
4712                final PackageSetting ps = (PackageSetting) obj;
4713                return new String[] { ps.name };
4714            }
4715        }
4716        return null;
4717    }
4718
4719    @Override
4720    public String getNameForUid(int uid) {
4721        // reader
4722        synchronized (mPackages) {
4723            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4724            if (obj instanceof SharedUserSetting) {
4725                final SharedUserSetting sus = (SharedUserSetting) obj;
4726                return sus.name + ":" + sus.userId;
4727            } else if (obj instanceof PackageSetting) {
4728                final PackageSetting ps = (PackageSetting) obj;
4729                return ps.name;
4730            }
4731        }
4732        return null;
4733    }
4734
4735    @Override
4736    public int getUidForSharedUser(String sharedUserName) {
4737        if(sharedUserName == null) {
4738            return -1;
4739        }
4740        // reader
4741        synchronized (mPackages) {
4742            SharedUserSetting suid;
4743            try {
4744                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4745                if (suid != null) {
4746                    return suid.userId;
4747                }
4748            } catch (PackageManagerException ignore) {
4749                // can't happen, but, still need to catch it
4750            }
4751            return -1;
4752        }
4753    }
4754
4755    @Override
4756    public int getFlagsForUid(int uid) {
4757        synchronized (mPackages) {
4758            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4759            if (obj instanceof SharedUserSetting) {
4760                final SharedUserSetting sus = (SharedUserSetting) obj;
4761                return sus.pkgFlags;
4762            } else if (obj instanceof PackageSetting) {
4763                final PackageSetting ps = (PackageSetting) obj;
4764                return ps.pkgFlags;
4765            }
4766        }
4767        return 0;
4768    }
4769
4770    @Override
4771    public int getPrivateFlagsForUid(int uid) {
4772        synchronized (mPackages) {
4773            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4774            if (obj instanceof SharedUserSetting) {
4775                final SharedUserSetting sus = (SharedUserSetting) obj;
4776                return sus.pkgPrivateFlags;
4777            } else if (obj instanceof PackageSetting) {
4778                final PackageSetting ps = (PackageSetting) obj;
4779                return ps.pkgPrivateFlags;
4780            }
4781        }
4782        return 0;
4783    }
4784
4785    @Override
4786    public boolean isUidPrivileged(int uid) {
4787        uid = UserHandle.getAppId(uid);
4788        // reader
4789        synchronized (mPackages) {
4790            Object obj = mSettings.getUserIdLPr(uid);
4791            if (obj instanceof SharedUserSetting) {
4792                final SharedUserSetting sus = (SharedUserSetting) obj;
4793                final Iterator<PackageSetting> it = sus.packages.iterator();
4794                while (it.hasNext()) {
4795                    if (it.next().isPrivileged()) {
4796                        return true;
4797                    }
4798                }
4799            } else if (obj instanceof PackageSetting) {
4800                final PackageSetting ps = (PackageSetting) obj;
4801                return ps.isPrivileged();
4802            }
4803        }
4804        return false;
4805    }
4806
4807    @Override
4808    public String[] getAppOpPermissionPackages(String permissionName) {
4809        synchronized (mPackages) {
4810            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4811            if (pkgs == null) {
4812                return null;
4813            }
4814            return pkgs.toArray(new String[pkgs.size()]);
4815        }
4816    }
4817
4818    @Override
4819    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4820            int flags, int userId) {
4821        try {
4822            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4823
4824            if (!sUserManager.exists(userId)) return null;
4825            flags = updateFlagsForResolve(flags, userId, intent);
4826            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4827                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4828
4829            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4830            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4831                    flags, userId);
4832            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4833
4834            final ResolveInfo bestChoice =
4835                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4836            return bestChoice;
4837        } finally {
4838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4839        }
4840    }
4841
4842    @Override
4843    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4844            IntentFilter filter, int match, ComponentName activity) {
4845        final int userId = UserHandle.getCallingUserId();
4846        if (DEBUG_PREFERRED) {
4847            Log.v(TAG, "setLastChosenActivity intent=" + intent
4848                + " resolvedType=" + resolvedType
4849                + " flags=" + flags
4850                + " filter=" + filter
4851                + " match=" + match
4852                + " activity=" + activity);
4853            filter.dump(new PrintStreamPrinter(System.out), "    ");
4854        }
4855        intent.setComponent(null);
4856        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4857                userId);
4858        // Find any earlier preferred or last chosen entries and nuke them
4859        findPreferredActivity(intent, resolvedType,
4860                flags, query, 0, false, true, false, userId);
4861        // Add the new activity as the last chosen for this filter
4862        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4863                "Setting last chosen");
4864    }
4865
4866    @Override
4867    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4868        final int userId = UserHandle.getCallingUserId();
4869        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4870        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4871                userId);
4872        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4873                false, false, false, userId);
4874    }
4875
4876    private boolean isEphemeralDisabled() {
4877        // ephemeral apps have been disabled across the board
4878        if (DISABLE_EPHEMERAL_APPS) {
4879            return true;
4880        }
4881        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4882        if (!mSystemReady) {
4883            return true;
4884        }
4885        // we can't get a content resolver until the system is ready; these checks must happen last
4886        final ContentResolver resolver = mContext.getContentResolver();
4887        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4888            return true;
4889        }
4890        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4891    }
4892
4893    private boolean isEphemeralAllowed(
4894            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4895            boolean skipPackageCheck) {
4896        // Short circuit and return early if possible.
4897        if (isEphemeralDisabled()) {
4898            return false;
4899        }
4900        final int callingUser = UserHandle.getCallingUserId();
4901        if (callingUser != UserHandle.USER_SYSTEM) {
4902            return false;
4903        }
4904        if (mEphemeralResolverConnection == null) {
4905            return false;
4906        }
4907        if (intent.getComponent() != null) {
4908            return false;
4909        }
4910        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4911            return false;
4912        }
4913        if (!skipPackageCheck && intent.getPackage() != null) {
4914            return false;
4915        }
4916        final boolean isWebUri = hasWebURI(intent);
4917        if (!isWebUri || intent.getData().getHost() == null) {
4918            return false;
4919        }
4920        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4921        synchronized (mPackages) {
4922            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4923            for (int n = 0; n < count; n++) {
4924                ResolveInfo info = resolvedActivities.get(n);
4925                String packageName = info.activityInfo.packageName;
4926                PackageSetting ps = mSettings.mPackages.get(packageName);
4927                if (ps != null) {
4928                    // Try to get the status from User settings first
4929                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4930                    int status = (int) (packedStatus >> 32);
4931                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4932                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4933                        if (DEBUG_EPHEMERAL) {
4934                            Slog.v(TAG, "DENY ephemeral apps;"
4935                                + " pkg: " + packageName + ", status: " + status);
4936                        }
4937                        return false;
4938                    }
4939                }
4940            }
4941        }
4942        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4943        return true;
4944    }
4945
4946    private static EphemeralResolveIntentInfo getEphemeralIntentInfo(
4947            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4948            String resolvedType, int userId, String packageName) {
4949        final EphemeralDigest digest =
4950                new EphemeralDigest(intent.getData().getHost(), 5 /*maxDigests*/);
4951        final int[] shaPrefix = digest.getDigestPrefix();
4952        final byte[][] digestBytes = digest.getDigestBytes();
4953        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4954                resolverConnection.getEphemeralResolveInfoList(shaPrefix);
4955        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4956            // No hash prefix match; there are no ephemeral apps for this domain.
4957            return null;
4958        }
4959
4960        // Go in reverse order so we match the narrowest scope first.
4961        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4962            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4963                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4964                    continue;
4965                }
4966                final List<EphemeralIntentFilter> ephemeralFilters =
4967                        ephemeralApplication.getIntentFilters();
4968                // No filters; this should never happen.
4969                if (ephemeralFilters.isEmpty()) {
4970                    continue;
4971                }
4972                if (packageName != null
4973                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4974                    continue;
4975                }
4976                // We have a domain match; resolve the filters to see if anything matches.
4977                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4978                for (int j = ephemeralFilters.size() - 1; j >= 0; --j) {
4979                    final EphemeralIntentFilter ephemeralFilter = ephemeralFilters.get(j);
4980                    final List<IntentFilter> splitFilters = ephemeralFilter.getFilters();
4981                    if (splitFilters == null || splitFilters.isEmpty()) {
4982                        continue;
4983                    }
4984                    for (int k = splitFilters.size() - 1; k >= 0; --k) {
4985                        final EphemeralResolveIntentInfo intentInfo =
4986                                new EphemeralResolveIntentInfo(splitFilters.get(k),
4987                                        ephemeralApplication, ephemeralFilter.getSplitName());
4988                        ephemeralResolver.addFilter(intentInfo);
4989                    }
4990                }
4991                List<EphemeralResolveIntentInfo> matchedResolveInfoList = ephemeralResolver
4992                        .queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
4993                if (!matchedResolveInfoList.isEmpty()) {
4994                    return matchedResolveInfoList.get(0);
4995                }
4996            }
4997        }
4998        // Hash or filter mis-match; no ephemeral apps for this domain.
4999        return null;
5000    }
5001
5002    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5003            int flags, List<ResolveInfo> query, int userId) {
5004        if (query != null) {
5005            final int N = query.size();
5006            if (N == 1) {
5007                return query.get(0);
5008            } else if (N > 1) {
5009                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5010                // If there is more than one activity with the same priority,
5011                // then let the user decide between them.
5012                ResolveInfo r0 = query.get(0);
5013                ResolveInfo r1 = query.get(1);
5014                if (DEBUG_INTENT_MATCHING || debug) {
5015                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5016                            + r1.activityInfo.name + "=" + r1.priority);
5017                }
5018                // If the first activity has a higher priority, or a different
5019                // default, then it is always desirable to pick it.
5020                if (r0.priority != r1.priority
5021                        || r0.preferredOrder != r1.preferredOrder
5022                        || r0.isDefault != r1.isDefault) {
5023                    return query.get(0);
5024                }
5025                // If we have saved a preference for a preferred activity for
5026                // this Intent, use that.
5027                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5028                        flags, query, r0.priority, true, false, debug, userId);
5029                if (ri != null) {
5030                    return ri;
5031                }
5032                ri = new ResolveInfo(mResolveInfo);
5033                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5034                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5035                // If all of the options come from the same package, show the application's
5036                // label and icon instead of the generic resolver's.
5037                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5038                // and then throw away the ResolveInfo itself, meaning that the caller loses
5039                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5040                // a fallback for this case; we only set the target package's resources on
5041                // the ResolveInfo, not the ActivityInfo.
5042                final String intentPackage = intent.getPackage();
5043                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5044                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5045                    ri.resolvePackageName = intentPackage;
5046                    if (userNeedsBadging(userId)) {
5047                        ri.noResourceId = true;
5048                    } else {
5049                        ri.icon = appi.icon;
5050                    }
5051                    ri.iconResourceId = appi.icon;
5052                    ri.labelRes = appi.labelRes;
5053                }
5054                ri.activityInfo.applicationInfo = new ApplicationInfo(
5055                        ri.activityInfo.applicationInfo);
5056                if (userId != 0) {
5057                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5058                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5059                }
5060                // Make sure that the resolver is displayable in car mode
5061                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5062                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5063                return ri;
5064            }
5065        }
5066        return null;
5067    }
5068
5069    /**
5070     * Return true if the given list is not empty and all of its contents have
5071     * an activityInfo with the given package name.
5072     */
5073    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5074        if (ArrayUtils.isEmpty(list)) {
5075            return false;
5076        }
5077        for (int i = 0, N = list.size(); i < N; i++) {
5078            final ResolveInfo ri = list.get(i);
5079            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5080            if (ai == null || !packageName.equals(ai.packageName)) {
5081                return false;
5082            }
5083        }
5084        return true;
5085    }
5086
5087    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5088            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5089        final int N = query.size();
5090        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5091                .get(userId);
5092        // Get the list of persistent preferred activities that handle the intent
5093        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5094        List<PersistentPreferredActivity> pprefs = ppir != null
5095                ? ppir.queryIntent(intent, resolvedType,
5096                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5097                : null;
5098        if (pprefs != null && pprefs.size() > 0) {
5099            final int M = pprefs.size();
5100            for (int i=0; i<M; i++) {
5101                final PersistentPreferredActivity ppa = pprefs.get(i);
5102                if (DEBUG_PREFERRED || debug) {
5103                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5104                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5105                            + "\n  component=" + ppa.mComponent);
5106                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5107                }
5108                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5109                        flags | MATCH_DISABLED_COMPONENTS, userId);
5110                if (DEBUG_PREFERRED || debug) {
5111                    Slog.v(TAG, "Found persistent preferred activity:");
5112                    if (ai != null) {
5113                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5114                    } else {
5115                        Slog.v(TAG, "  null");
5116                    }
5117                }
5118                if (ai == null) {
5119                    // This previously registered persistent preferred activity
5120                    // component is no longer known. Ignore it and do NOT remove it.
5121                    continue;
5122                }
5123                for (int j=0; j<N; j++) {
5124                    final ResolveInfo ri = query.get(j);
5125                    if (!ri.activityInfo.applicationInfo.packageName
5126                            .equals(ai.applicationInfo.packageName)) {
5127                        continue;
5128                    }
5129                    if (!ri.activityInfo.name.equals(ai.name)) {
5130                        continue;
5131                    }
5132                    //  Found a persistent preference that can handle the intent.
5133                    if (DEBUG_PREFERRED || debug) {
5134                        Slog.v(TAG, "Returning persistent preferred activity: " +
5135                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5136                    }
5137                    return ri;
5138                }
5139            }
5140        }
5141        return null;
5142    }
5143
5144    // TODO: handle preferred activities missing while user has amnesia
5145    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5146            List<ResolveInfo> query, int priority, boolean always,
5147            boolean removeMatches, boolean debug, int userId) {
5148        if (!sUserManager.exists(userId)) return null;
5149        flags = updateFlagsForResolve(flags, userId, intent);
5150        // writer
5151        synchronized (mPackages) {
5152            if (intent.getSelector() != null) {
5153                intent = intent.getSelector();
5154            }
5155            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5156
5157            // Try to find a matching persistent preferred activity.
5158            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5159                    debug, userId);
5160
5161            // If a persistent preferred activity matched, use it.
5162            if (pri != null) {
5163                return pri;
5164            }
5165
5166            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5167            // Get the list of preferred activities that handle the intent
5168            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5169            List<PreferredActivity> prefs = pir != null
5170                    ? pir.queryIntent(intent, resolvedType,
5171                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5172                    : null;
5173            if (prefs != null && prefs.size() > 0) {
5174                boolean changed = false;
5175                try {
5176                    // First figure out how good the original match set is.
5177                    // We will only allow preferred activities that came
5178                    // from the same match quality.
5179                    int match = 0;
5180
5181                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5182
5183                    final int N = query.size();
5184                    for (int j=0; j<N; j++) {
5185                        final ResolveInfo ri = query.get(j);
5186                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5187                                + ": 0x" + Integer.toHexString(match));
5188                        if (ri.match > match) {
5189                            match = ri.match;
5190                        }
5191                    }
5192
5193                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5194                            + Integer.toHexString(match));
5195
5196                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5197                    final int M = prefs.size();
5198                    for (int i=0; i<M; i++) {
5199                        final PreferredActivity pa = prefs.get(i);
5200                        if (DEBUG_PREFERRED || debug) {
5201                            Slog.v(TAG, "Checking PreferredActivity ds="
5202                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5203                                    + "\n  component=" + pa.mPref.mComponent);
5204                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5205                        }
5206                        if (pa.mPref.mMatch != match) {
5207                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5208                                    + Integer.toHexString(pa.mPref.mMatch));
5209                            continue;
5210                        }
5211                        // If it's not an "always" type preferred activity and that's what we're
5212                        // looking for, skip it.
5213                        if (always && !pa.mPref.mAlways) {
5214                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5215                            continue;
5216                        }
5217                        final ActivityInfo ai = getActivityInfo(
5218                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5219                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5220                                userId);
5221                        if (DEBUG_PREFERRED || debug) {
5222                            Slog.v(TAG, "Found preferred activity:");
5223                            if (ai != null) {
5224                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5225                            } else {
5226                                Slog.v(TAG, "  null");
5227                            }
5228                        }
5229                        if (ai == null) {
5230                            // This previously registered preferred activity
5231                            // component is no longer known.  Most likely an update
5232                            // to the app was installed and in the new version this
5233                            // component no longer exists.  Clean it up by removing
5234                            // it from the preferred activities list, and skip it.
5235                            Slog.w(TAG, "Removing dangling preferred activity: "
5236                                    + pa.mPref.mComponent);
5237                            pir.removeFilter(pa);
5238                            changed = true;
5239                            continue;
5240                        }
5241                        for (int j=0; j<N; j++) {
5242                            final ResolveInfo ri = query.get(j);
5243                            if (!ri.activityInfo.applicationInfo.packageName
5244                                    .equals(ai.applicationInfo.packageName)) {
5245                                continue;
5246                            }
5247                            if (!ri.activityInfo.name.equals(ai.name)) {
5248                                continue;
5249                            }
5250
5251                            if (removeMatches) {
5252                                pir.removeFilter(pa);
5253                                changed = true;
5254                                if (DEBUG_PREFERRED) {
5255                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5256                                }
5257                                break;
5258                            }
5259
5260                            // Okay we found a previously set preferred or last chosen app.
5261                            // If the result set is different from when this
5262                            // was created, we need to clear it and re-ask the
5263                            // user their preference, if we're looking for an "always" type entry.
5264                            if (always && !pa.mPref.sameSet(query)) {
5265                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5266                                        + intent + " type " + resolvedType);
5267                                if (DEBUG_PREFERRED) {
5268                                    Slog.v(TAG, "Removing preferred activity since set changed "
5269                                            + pa.mPref.mComponent);
5270                                }
5271                                pir.removeFilter(pa);
5272                                // Re-add the filter as a "last chosen" entry (!always)
5273                                PreferredActivity lastChosen = new PreferredActivity(
5274                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5275                                pir.addFilter(lastChosen);
5276                                changed = true;
5277                                return null;
5278                            }
5279
5280                            // Yay! Either the set matched or we're looking for the last chosen
5281                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5282                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5283                            return ri;
5284                        }
5285                    }
5286                } finally {
5287                    if (changed) {
5288                        if (DEBUG_PREFERRED) {
5289                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5290                        }
5291                        scheduleWritePackageRestrictionsLocked(userId);
5292                    }
5293                }
5294            }
5295        }
5296        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5297        return null;
5298    }
5299
5300    /*
5301     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5302     */
5303    @Override
5304    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5305            int targetUserId) {
5306        mContext.enforceCallingOrSelfPermission(
5307                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5308        List<CrossProfileIntentFilter> matches =
5309                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5310        if (matches != null) {
5311            int size = matches.size();
5312            for (int i = 0; i < size; i++) {
5313                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5314            }
5315        }
5316        if (hasWebURI(intent)) {
5317            // cross-profile app linking works only towards the parent.
5318            final UserInfo parent = getProfileParent(sourceUserId);
5319            synchronized(mPackages) {
5320                int flags = updateFlagsForResolve(0, parent.id, intent);
5321                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5322                        intent, resolvedType, flags, sourceUserId, parent.id);
5323                return xpDomainInfo != null;
5324            }
5325        }
5326        return false;
5327    }
5328
5329    private UserInfo getProfileParent(int userId) {
5330        final long identity = Binder.clearCallingIdentity();
5331        try {
5332            return sUserManager.getProfileParent(userId);
5333        } finally {
5334            Binder.restoreCallingIdentity(identity);
5335        }
5336    }
5337
5338    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5339            String resolvedType, int userId) {
5340        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5341        if (resolver != null) {
5342            return resolver.queryIntent(intent, resolvedType, false, userId);
5343        }
5344        return null;
5345    }
5346
5347    @Override
5348    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5349            String resolvedType, int flags, int userId) {
5350        try {
5351            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5352
5353            return new ParceledListSlice<>(
5354                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5355        } finally {
5356            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5357        }
5358    }
5359
5360    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5361            String resolvedType, int flags, int userId) {
5362        if (!sUserManager.exists(userId)) return Collections.emptyList();
5363        flags = updateFlagsForResolve(flags, userId, intent);
5364        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5365                false /* requireFullPermission */, false /* checkShell */,
5366                "query intent activities");
5367        ComponentName comp = intent.getComponent();
5368        if (comp == null) {
5369            if (intent.getSelector() != null) {
5370                intent = intent.getSelector();
5371                comp = intent.getComponent();
5372            }
5373        }
5374
5375        if (comp != null) {
5376            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5377            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5378            if (ai != null) {
5379                final ResolveInfo ri = new ResolveInfo();
5380                ri.activityInfo = ai;
5381                list.add(ri);
5382            }
5383            return list;
5384        }
5385
5386        // reader
5387        boolean sortResult = false;
5388        boolean addEphemeral = false;
5389        boolean matchEphemeralPackage = false;
5390        List<ResolveInfo> result;
5391        final String pkgName = intent.getPackage();
5392        synchronized (mPackages) {
5393            if (pkgName == null) {
5394                List<CrossProfileIntentFilter> matchingFilters =
5395                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5396                // Check for results that need to skip the current profile.
5397                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5398                        resolvedType, flags, userId);
5399                if (xpResolveInfo != null) {
5400                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5401                    xpResult.add(xpResolveInfo);
5402                    return filterIfNotSystemUser(xpResult, userId);
5403                }
5404
5405                // Check for results in the current profile.
5406                result = filterIfNotSystemUser(mActivities.queryIntent(
5407                        intent, resolvedType, flags, userId), userId);
5408                addEphemeral =
5409                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5410
5411                // Check for cross profile results.
5412                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5413                xpResolveInfo = queryCrossProfileIntents(
5414                        matchingFilters, intent, resolvedType, flags, userId,
5415                        hasNonNegativePriorityResult);
5416                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5417                    boolean isVisibleToUser = filterIfNotSystemUser(
5418                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5419                    if (isVisibleToUser) {
5420                        result.add(xpResolveInfo);
5421                        sortResult = true;
5422                    }
5423                }
5424                if (hasWebURI(intent)) {
5425                    CrossProfileDomainInfo xpDomainInfo = null;
5426                    final UserInfo parent = getProfileParent(userId);
5427                    if (parent != null) {
5428                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5429                                flags, userId, parent.id);
5430                    }
5431                    if (xpDomainInfo != null) {
5432                        if (xpResolveInfo != null) {
5433                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5434                            // in the result.
5435                            result.remove(xpResolveInfo);
5436                        }
5437                        if (result.size() == 0 && !addEphemeral) {
5438                            // No result in current profile, but found candidate in parent user.
5439                            // And we are not going to add emphemeral app, so we can return the
5440                            // result straight away.
5441                            result.add(xpDomainInfo.resolveInfo);
5442                            return result;
5443                        }
5444                    } else if (result.size() <= 1 && !addEphemeral) {
5445                        // No result in parent user and <= 1 result in current profile, and we
5446                        // are not going to add emphemeral app, so we can return the result without
5447                        // further processing.
5448                        return result;
5449                    }
5450                    // We have more than one candidate (combining results from current and parent
5451                    // profile), so we need filtering and sorting.
5452                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5453                            intent, flags, result, xpDomainInfo, userId);
5454                    sortResult = true;
5455                }
5456            } else {
5457                final PackageParser.Package pkg = mPackages.get(pkgName);
5458                if (pkg != null) {
5459                    result = filterIfNotSystemUser(
5460                            mActivities.queryIntentForPackage(
5461                                    intent, resolvedType, flags, pkg.activities, userId),
5462                            userId);
5463                } else {
5464                    // the caller wants to resolve for a particular package; however, there
5465                    // were no installed results, so, try to find an ephemeral result
5466                    addEphemeral = isEphemeralAllowed(
5467                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5468                    matchEphemeralPackage = true;
5469                    result = new ArrayList<ResolveInfo>();
5470                }
5471            }
5472        }
5473        if (addEphemeral) {
5474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5475            final EphemeralResolveIntentInfo intentInfo = getEphemeralIntentInfo(
5476                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5477                    matchEphemeralPackage ? pkgName : null);
5478            if (intentInfo != null) {
5479                if (DEBUG_EPHEMERAL) {
5480                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5481                }
5482                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5483                ephemeralInstaller.ephemeralIntentInfo = intentInfo;
5484                // make sure this resolver is the default
5485                ephemeralInstaller.isDefault = true;
5486                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5487                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5488                // add a non-generic filter
5489                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5490                ephemeralInstaller.filter.addDataPath(
5491                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5492                result.add(ephemeralInstaller);
5493            }
5494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5495        }
5496        if (sortResult) {
5497            Collections.sort(result, mResolvePrioritySorter);
5498        }
5499        return result;
5500    }
5501
5502    private static class CrossProfileDomainInfo {
5503        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5504        ResolveInfo resolveInfo;
5505        /* Best domain verification status of the activities found in the other profile */
5506        int bestDomainVerificationStatus;
5507    }
5508
5509    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5510            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5511        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5512                sourceUserId)) {
5513            return null;
5514        }
5515        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5516                resolvedType, flags, parentUserId);
5517
5518        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5519            return null;
5520        }
5521        CrossProfileDomainInfo result = null;
5522        int size = resultTargetUser.size();
5523        for (int i = 0; i < size; i++) {
5524            ResolveInfo riTargetUser = resultTargetUser.get(i);
5525            // Intent filter verification is only for filters that specify a host. So don't return
5526            // those that handle all web uris.
5527            if (riTargetUser.handleAllWebDataURI) {
5528                continue;
5529            }
5530            String packageName = riTargetUser.activityInfo.packageName;
5531            PackageSetting ps = mSettings.mPackages.get(packageName);
5532            if (ps == null) {
5533                continue;
5534            }
5535            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5536            int status = (int)(verificationState >> 32);
5537            if (result == null) {
5538                result = new CrossProfileDomainInfo();
5539                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5540                        sourceUserId, parentUserId);
5541                result.bestDomainVerificationStatus = status;
5542            } else {
5543                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5544                        result.bestDomainVerificationStatus);
5545            }
5546        }
5547        // Don't consider matches with status NEVER across profiles.
5548        if (result != null && result.bestDomainVerificationStatus
5549                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5550            return null;
5551        }
5552        return result;
5553    }
5554
5555    /**
5556     * Verification statuses are ordered from the worse to the best, except for
5557     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5558     */
5559    private int bestDomainVerificationStatus(int status1, int status2) {
5560        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5561            return status2;
5562        }
5563        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5564            return status1;
5565        }
5566        return (int) MathUtils.max(status1, status2);
5567    }
5568
5569    private boolean isUserEnabled(int userId) {
5570        long callingId = Binder.clearCallingIdentity();
5571        try {
5572            UserInfo userInfo = sUserManager.getUserInfo(userId);
5573            return userInfo != null && userInfo.isEnabled();
5574        } finally {
5575            Binder.restoreCallingIdentity(callingId);
5576        }
5577    }
5578
5579    /**
5580     * Filter out activities with systemUserOnly flag set, when current user is not System.
5581     *
5582     * @return filtered list
5583     */
5584    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5585        if (userId == UserHandle.USER_SYSTEM) {
5586            return resolveInfos;
5587        }
5588        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5589            ResolveInfo info = resolveInfos.get(i);
5590            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5591                resolveInfos.remove(i);
5592            }
5593        }
5594        return resolveInfos;
5595    }
5596
5597    /**
5598     * @param resolveInfos list of resolve infos in descending priority order
5599     * @return if the list contains a resolve info with non-negative priority
5600     */
5601    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5602        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5603    }
5604
5605    private static boolean hasWebURI(Intent intent) {
5606        if (intent.getData() == null) {
5607            return false;
5608        }
5609        final String scheme = intent.getScheme();
5610        if (TextUtils.isEmpty(scheme)) {
5611            return false;
5612        }
5613        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5614    }
5615
5616    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5617            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5618            int userId) {
5619        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5620
5621        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5622            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5623                    candidates.size());
5624        }
5625
5626        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5627        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5628        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5629        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5630        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5631        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5632
5633        synchronized (mPackages) {
5634            final int count = candidates.size();
5635            // First, try to use linked apps. Partition the candidates into four lists:
5636            // one for the final results, one for the "do not use ever", one for "undefined status"
5637            // and finally one for "browser app type".
5638            for (int n=0; n<count; n++) {
5639                ResolveInfo info = candidates.get(n);
5640                String packageName = info.activityInfo.packageName;
5641                PackageSetting ps = mSettings.mPackages.get(packageName);
5642                if (ps != null) {
5643                    // Add to the special match all list (Browser use case)
5644                    if (info.handleAllWebDataURI) {
5645                        matchAllList.add(info);
5646                        continue;
5647                    }
5648                    // Try to get the status from User settings first
5649                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5650                    int status = (int)(packedStatus >> 32);
5651                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5652                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5653                        if (DEBUG_DOMAIN_VERIFICATION) {
5654                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5655                                    + " : linkgen=" + linkGeneration);
5656                        }
5657                        // Use link-enabled generation as preferredOrder, i.e.
5658                        // prefer newly-enabled over earlier-enabled.
5659                        info.preferredOrder = linkGeneration;
5660                        alwaysList.add(info);
5661                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5662                        if (DEBUG_DOMAIN_VERIFICATION) {
5663                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5664                        }
5665                        neverList.add(info);
5666                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5667                        if (DEBUG_DOMAIN_VERIFICATION) {
5668                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5669                        }
5670                        alwaysAskList.add(info);
5671                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5672                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5673                        if (DEBUG_DOMAIN_VERIFICATION) {
5674                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5675                        }
5676                        undefinedList.add(info);
5677                    }
5678                }
5679            }
5680
5681            // We'll want to include browser possibilities in a few cases
5682            boolean includeBrowser = false;
5683
5684            // First try to add the "always" resolution(s) for the current user, if any
5685            if (alwaysList.size() > 0) {
5686                result.addAll(alwaysList);
5687            } else {
5688                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5689                result.addAll(undefinedList);
5690                // Maybe add one for the other profile.
5691                if (xpDomainInfo != null && (
5692                        xpDomainInfo.bestDomainVerificationStatus
5693                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5694                    result.add(xpDomainInfo.resolveInfo);
5695                }
5696                includeBrowser = true;
5697            }
5698
5699            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5700            // If there were 'always' entries their preferred order has been set, so we also
5701            // back that off to make the alternatives equivalent
5702            if (alwaysAskList.size() > 0) {
5703                for (ResolveInfo i : result) {
5704                    i.preferredOrder = 0;
5705                }
5706                result.addAll(alwaysAskList);
5707                includeBrowser = true;
5708            }
5709
5710            if (includeBrowser) {
5711                // Also add browsers (all of them or only the default one)
5712                if (DEBUG_DOMAIN_VERIFICATION) {
5713                    Slog.v(TAG, "   ...including browsers in candidate set");
5714                }
5715                if ((matchFlags & MATCH_ALL) != 0) {
5716                    result.addAll(matchAllList);
5717                } else {
5718                    // Browser/generic handling case.  If there's a default browser, go straight
5719                    // to that (but only if there is no other higher-priority match).
5720                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5721                    int maxMatchPrio = 0;
5722                    ResolveInfo defaultBrowserMatch = null;
5723                    final int numCandidates = matchAllList.size();
5724                    for (int n = 0; n < numCandidates; n++) {
5725                        ResolveInfo info = matchAllList.get(n);
5726                        // track the highest overall match priority...
5727                        if (info.priority > maxMatchPrio) {
5728                            maxMatchPrio = info.priority;
5729                        }
5730                        // ...and the highest-priority default browser match
5731                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5732                            if (defaultBrowserMatch == null
5733                                    || (defaultBrowserMatch.priority < info.priority)) {
5734                                if (debug) {
5735                                    Slog.v(TAG, "Considering default browser match " + info);
5736                                }
5737                                defaultBrowserMatch = info;
5738                            }
5739                        }
5740                    }
5741                    if (defaultBrowserMatch != null
5742                            && defaultBrowserMatch.priority >= maxMatchPrio
5743                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5744                    {
5745                        if (debug) {
5746                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5747                        }
5748                        result.add(defaultBrowserMatch);
5749                    } else {
5750                        result.addAll(matchAllList);
5751                    }
5752                }
5753
5754                // If there is nothing selected, add all candidates and remove the ones that the user
5755                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5756                if (result.size() == 0) {
5757                    result.addAll(candidates);
5758                    result.removeAll(neverList);
5759                }
5760            }
5761        }
5762        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5763            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5764                    result.size());
5765            for (ResolveInfo info : result) {
5766                Slog.v(TAG, "  + " + info.activityInfo);
5767            }
5768        }
5769        return result;
5770    }
5771
5772    // Returns a packed value as a long:
5773    //
5774    // high 'int'-sized word: link status: undefined/ask/never/always.
5775    // low 'int'-sized word: relative priority among 'always' results.
5776    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5777        long result = ps.getDomainVerificationStatusForUser(userId);
5778        // if none available, get the master status
5779        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5780            if (ps.getIntentFilterVerificationInfo() != null) {
5781                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5782            }
5783        }
5784        return result;
5785    }
5786
5787    private ResolveInfo querySkipCurrentProfileIntents(
5788            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5789            int flags, int sourceUserId) {
5790        if (matchingFilters != null) {
5791            int size = matchingFilters.size();
5792            for (int i = 0; i < size; i ++) {
5793                CrossProfileIntentFilter filter = matchingFilters.get(i);
5794                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5795                    // Checking if there are activities in the target user that can handle the
5796                    // intent.
5797                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5798                            resolvedType, flags, sourceUserId);
5799                    if (resolveInfo != null) {
5800                        return resolveInfo;
5801                    }
5802                }
5803            }
5804        }
5805        return null;
5806    }
5807
5808    // Return matching ResolveInfo in target user if any.
5809    private ResolveInfo queryCrossProfileIntents(
5810            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5811            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5812        if (matchingFilters != null) {
5813            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5814            // match the same intent. For performance reasons, it is better not to
5815            // run queryIntent twice for the same userId
5816            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5817            int size = matchingFilters.size();
5818            for (int i = 0; i < size; i++) {
5819                CrossProfileIntentFilter filter = matchingFilters.get(i);
5820                int targetUserId = filter.getTargetUserId();
5821                boolean skipCurrentProfile =
5822                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5823                boolean skipCurrentProfileIfNoMatchFound =
5824                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5825                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5826                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5827                    // Checking if there are activities in the target user that can handle the
5828                    // intent.
5829                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5830                            resolvedType, flags, sourceUserId);
5831                    if (resolveInfo != null) return resolveInfo;
5832                    alreadyTriedUserIds.put(targetUserId, true);
5833                }
5834            }
5835        }
5836        return null;
5837    }
5838
5839    /**
5840     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5841     * will forward the intent to the filter's target user.
5842     * Otherwise, returns null.
5843     */
5844    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5845            String resolvedType, int flags, int sourceUserId) {
5846        int targetUserId = filter.getTargetUserId();
5847        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5848                resolvedType, flags, targetUserId);
5849        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5850            // If all the matches in the target profile are suspended, return null.
5851            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5852                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5853                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5854                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5855                            targetUserId);
5856                }
5857            }
5858        }
5859        return null;
5860    }
5861
5862    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5863            int sourceUserId, int targetUserId) {
5864        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5865        long ident = Binder.clearCallingIdentity();
5866        boolean targetIsProfile;
5867        try {
5868            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5869        } finally {
5870            Binder.restoreCallingIdentity(ident);
5871        }
5872        String className;
5873        if (targetIsProfile) {
5874            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5875        } else {
5876            className = FORWARD_INTENT_TO_PARENT;
5877        }
5878        ComponentName forwardingActivityComponentName = new ComponentName(
5879                mAndroidApplication.packageName, className);
5880        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5881                sourceUserId);
5882        if (!targetIsProfile) {
5883            forwardingActivityInfo.showUserIcon = targetUserId;
5884            forwardingResolveInfo.noResourceId = true;
5885        }
5886        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5887        forwardingResolveInfo.priority = 0;
5888        forwardingResolveInfo.preferredOrder = 0;
5889        forwardingResolveInfo.match = 0;
5890        forwardingResolveInfo.isDefault = true;
5891        forwardingResolveInfo.filter = filter;
5892        forwardingResolveInfo.targetUserId = targetUserId;
5893        return forwardingResolveInfo;
5894    }
5895
5896    @Override
5897    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5898            Intent[] specifics, String[] specificTypes, Intent intent,
5899            String resolvedType, int flags, int userId) {
5900        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5901                specificTypes, intent, resolvedType, flags, userId));
5902    }
5903
5904    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5905            Intent[] specifics, String[] specificTypes, Intent intent,
5906            String resolvedType, int flags, int userId) {
5907        if (!sUserManager.exists(userId)) return Collections.emptyList();
5908        flags = updateFlagsForResolve(flags, userId, intent);
5909        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5910                false /* requireFullPermission */, false /* checkShell */,
5911                "query intent activity options");
5912        final String resultsAction = intent.getAction();
5913
5914        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5915                | PackageManager.GET_RESOLVED_FILTER, userId);
5916
5917        if (DEBUG_INTENT_MATCHING) {
5918            Log.v(TAG, "Query " + intent + ": " + results);
5919        }
5920
5921        int specificsPos = 0;
5922        int N;
5923
5924        // todo: note that the algorithm used here is O(N^2).  This
5925        // isn't a problem in our current environment, but if we start running
5926        // into situations where we have more than 5 or 10 matches then this
5927        // should probably be changed to something smarter...
5928
5929        // First we go through and resolve each of the specific items
5930        // that were supplied, taking care of removing any corresponding
5931        // duplicate items in the generic resolve list.
5932        if (specifics != null) {
5933            for (int i=0; i<specifics.length; i++) {
5934                final Intent sintent = specifics[i];
5935                if (sintent == null) {
5936                    continue;
5937                }
5938
5939                if (DEBUG_INTENT_MATCHING) {
5940                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5941                }
5942
5943                String action = sintent.getAction();
5944                if (resultsAction != null && resultsAction.equals(action)) {
5945                    // If this action was explicitly requested, then don't
5946                    // remove things that have it.
5947                    action = null;
5948                }
5949
5950                ResolveInfo ri = null;
5951                ActivityInfo ai = null;
5952
5953                ComponentName comp = sintent.getComponent();
5954                if (comp == null) {
5955                    ri = resolveIntent(
5956                        sintent,
5957                        specificTypes != null ? specificTypes[i] : null,
5958                            flags, userId);
5959                    if (ri == null) {
5960                        continue;
5961                    }
5962                    if (ri == mResolveInfo) {
5963                        // ACK!  Must do something better with this.
5964                    }
5965                    ai = ri.activityInfo;
5966                    comp = new ComponentName(ai.applicationInfo.packageName,
5967                            ai.name);
5968                } else {
5969                    ai = getActivityInfo(comp, flags, userId);
5970                    if (ai == null) {
5971                        continue;
5972                    }
5973                }
5974
5975                // Look for any generic query activities that are duplicates
5976                // of this specific one, and remove them from the results.
5977                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5978                N = results.size();
5979                int j;
5980                for (j=specificsPos; j<N; j++) {
5981                    ResolveInfo sri = results.get(j);
5982                    if ((sri.activityInfo.name.equals(comp.getClassName())
5983                            && sri.activityInfo.applicationInfo.packageName.equals(
5984                                    comp.getPackageName()))
5985                        || (action != null && sri.filter.matchAction(action))) {
5986                        results.remove(j);
5987                        if (DEBUG_INTENT_MATCHING) Log.v(
5988                            TAG, "Removing duplicate item from " + j
5989                            + " due to specific " + specificsPos);
5990                        if (ri == null) {
5991                            ri = sri;
5992                        }
5993                        j--;
5994                        N--;
5995                    }
5996                }
5997
5998                // Add this specific item to its proper place.
5999                if (ri == null) {
6000                    ri = new ResolveInfo();
6001                    ri.activityInfo = ai;
6002                }
6003                results.add(specificsPos, ri);
6004                ri.specificIndex = i;
6005                specificsPos++;
6006            }
6007        }
6008
6009        // Now we go through the remaining generic results and remove any
6010        // duplicate actions that are found here.
6011        N = results.size();
6012        for (int i=specificsPos; i<N-1; i++) {
6013            final ResolveInfo rii = results.get(i);
6014            if (rii.filter == null) {
6015                continue;
6016            }
6017
6018            // Iterate over all of the actions of this result's intent
6019            // filter...  typically this should be just one.
6020            final Iterator<String> it = rii.filter.actionsIterator();
6021            if (it == null) {
6022                continue;
6023            }
6024            while (it.hasNext()) {
6025                final String action = it.next();
6026                if (resultsAction != null && resultsAction.equals(action)) {
6027                    // If this action was explicitly requested, then don't
6028                    // remove things that have it.
6029                    continue;
6030                }
6031                for (int j=i+1; j<N; j++) {
6032                    final ResolveInfo rij = results.get(j);
6033                    if (rij.filter != null && rij.filter.hasAction(action)) {
6034                        results.remove(j);
6035                        if (DEBUG_INTENT_MATCHING) Log.v(
6036                            TAG, "Removing duplicate item from " + j
6037                            + " due to action " + action + " at " + i);
6038                        j--;
6039                        N--;
6040                    }
6041                }
6042            }
6043
6044            // If the caller didn't request filter information, drop it now
6045            // so we don't have to marshall/unmarshall it.
6046            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6047                rii.filter = null;
6048            }
6049        }
6050
6051        // Filter out the caller activity if so requested.
6052        if (caller != null) {
6053            N = results.size();
6054            for (int i=0; i<N; i++) {
6055                ActivityInfo ainfo = results.get(i).activityInfo;
6056                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6057                        && caller.getClassName().equals(ainfo.name)) {
6058                    results.remove(i);
6059                    break;
6060                }
6061            }
6062        }
6063
6064        // If the caller didn't request filter information,
6065        // drop them now so we don't have to
6066        // marshall/unmarshall it.
6067        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6068            N = results.size();
6069            for (int i=0; i<N; i++) {
6070                results.get(i).filter = null;
6071            }
6072        }
6073
6074        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6075        return results;
6076    }
6077
6078    @Override
6079    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6080            String resolvedType, int flags, int userId) {
6081        return new ParceledListSlice<>(
6082                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6083    }
6084
6085    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6086            String resolvedType, int flags, int userId) {
6087        if (!sUserManager.exists(userId)) return Collections.emptyList();
6088        flags = updateFlagsForResolve(flags, userId, intent);
6089        ComponentName comp = intent.getComponent();
6090        if (comp == null) {
6091            if (intent.getSelector() != null) {
6092                intent = intent.getSelector();
6093                comp = intent.getComponent();
6094            }
6095        }
6096        if (comp != null) {
6097            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6098            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6099            if (ai != null) {
6100                ResolveInfo ri = new ResolveInfo();
6101                ri.activityInfo = ai;
6102                list.add(ri);
6103            }
6104            return list;
6105        }
6106
6107        // reader
6108        synchronized (mPackages) {
6109            String pkgName = intent.getPackage();
6110            if (pkgName == null) {
6111                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6112            }
6113            final PackageParser.Package pkg = mPackages.get(pkgName);
6114            if (pkg != null) {
6115                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6116                        userId);
6117            }
6118            return Collections.emptyList();
6119        }
6120    }
6121
6122    @Override
6123    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6124        if (!sUserManager.exists(userId)) return null;
6125        flags = updateFlagsForResolve(flags, userId, intent);
6126        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6127        if (query != null) {
6128            if (query.size() >= 1) {
6129                // If there is more than one service with the same priority,
6130                // just arbitrarily pick the first one.
6131                return query.get(0);
6132            }
6133        }
6134        return null;
6135    }
6136
6137    @Override
6138    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6139            String resolvedType, int flags, int userId) {
6140        return new ParceledListSlice<>(
6141                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6142    }
6143
6144    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6145            String resolvedType, int flags, int userId) {
6146        if (!sUserManager.exists(userId)) return Collections.emptyList();
6147        flags = updateFlagsForResolve(flags, userId, intent);
6148        ComponentName comp = intent.getComponent();
6149        if (comp == null) {
6150            if (intent.getSelector() != null) {
6151                intent = intent.getSelector();
6152                comp = intent.getComponent();
6153            }
6154        }
6155        if (comp != null) {
6156            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6157            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6158            if (si != null) {
6159                final ResolveInfo ri = new ResolveInfo();
6160                ri.serviceInfo = si;
6161                list.add(ri);
6162            }
6163            return list;
6164        }
6165
6166        // reader
6167        synchronized (mPackages) {
6168            String pkgName = intent.getPackage();
6169            if (pkgName == null) {
6170                return mServices.queryIntent(intent, resolvedType, flags, userId);
6171            }
6172            final PackageParser.Package pkg = mPackages.get(pkgName);
6173            if (pkg != null) {
6174                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6175                        userId);
6176            }
6177            return Collections.emptyList();
6178        }
6179    }
6180
6181    @Override
6182    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6183            String resolvedType, int flags, int userId) {
6184        return new ParceledListSlice<>(
6185                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6186    }
6187
6188    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6189            Intent intent, String resolvedType, int flags, int userId) {
6190        if (!sUserManager.exists(userId)) return Collections.emptyList();
6191        flags = updateFlagsForResolve(flags, userId, intent);
6192        ComponentName comp = intent.getComponent();
6193        if (comp == null) {
6194            if (intent.getSelector() != null) {
6195                intent = intent.getSelector();
6196                comp = intent.getComponent();
6197            }
6198        }
6199        if (comp != null) {
6200            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6201            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6202            if (pi != null) {
6203                final ResolveInfo ri = new ResolveInfo();
6204                ri.providerInfo = pi;
6205                list.add(ri);
6206            }
6207            return list;
6208        }
6209
6210        // reader
6211        synchronized (mPackages) {
6212            String pkgName = intent.getPackage();
6213            if (pkgName == null) {
6214                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6215            }
6216            final PackageParser.Package pkg = mPackages.get(pkgName);
6217            if (pkg != null) {
6218                return mProviders.queryIntentForPackage(
6219                        intent, resolvedType, flags, pkg.providers, userId);
6220            }
6221            return Collections.emptyList();
6222        }
6223    }
6224
6225    @Override
6226    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6227        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6228        flags = updateFlagsForPackage(flags, userId, null);
6229        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6230        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6231                true /* requireFullPermission */, false /* checkShell */,
6232                "get installed packages");
6233
6234        // writer
6235        synchronized (mPackages) {
6236            ArrayList<PackageInfo> list;
6237            if (listUninstalled) {
6238                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6239                for (PackageSetting ps : mSettings.mPackages.values()) {
6240                    final PackageInfo pi;
6241                    if (ps.pkg != null) {
6242                        pi = generatePackageInfo(ps, flags, userId);
6243                    } else {
6244                        pi = generatePackageInfo(ps, flags, userId);
6245                    }
6246                    if (pi != null) {
6247                        list.add(pi);
6248                    }
6249                }
6250            } else {
6251                list = new ArrayList<PackageInfo>(mPackages.size());
6252                for (PackageParser.Package p : mPackages.values()) {
6253                    final PackageInfo pi =
6254                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6255                    if (pi != null) {
6256                        list.add(pi);
6257                    }
6258                }
6259            }
6260
6261            return new ParceledListSlice<PackageInfo>(list);
6262        }
6263    }
6264
6265    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6266            String[] permissions, boolean[] tmp, int flags, int userId) {
6267        int numMatch = 0;
6268        final PermissionsState permissionsState = ps.getPermissionsState();
6269        for (int i=0; i<permissions.length; i++) {
6270            final String permission = permissions[i];
6271            if (permissionsState.hasPermission(permission, userId)) {
6272                tmp[i] = true;
6273                numMatch++;
6274            } else {
6275                tmp[i] = false;
6276            }
6277        }
6278        if (numMatch == 0) {
6279            return;
6280        }
6281        final PackageInfo pi;
6282        if (ps.pkg != null) {
6283            pi = generatePackageInfo(ps, flags, userId);
6284        } else {
6285            pi = generatePackageInfo(ps, flags, userId);
6286        }
6287        // The above might return null in cases of uninstalled apps or install-state
6288        // skew across users/profiles.
6289        if (pi != null) {
6290            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6291                if (numMatch == permissions.length) {
6292                    pi.requestedPermissions = permissions;
6293                } else {
6294                    pi.requestedPermissions = new String[numMatch];
6295                    numMatch = 0;
6296                    for (int i=0; i<permissions.length; i++) {
6297                        if (tmp[i]) {
6298                            pi.requestedPermissions[numMatch] = permissions[i];
6299                            numMatch++;
6300                        }
6301                    }
6302                }
6303            }
6304            list.add(pi);
6305        }
6306    }
6307
6308    @Override
6309    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6310            String[] permissions, int flags, int userId) {
6311        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6312        flags = updateFlagsForPackage(flags, userId, permissions);
6313        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6314
6315        // writer
6316        synchronized (mPackages) {
6317            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6318            boolean[] tmpBools = new boolean[permissions.length];
6319            if (listUninstalled) {
6320                for (PackageSetting ps : mSettings.mPackages.values()) {
6321                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6322                }
6323            } else {
6324                for (PackageParser.Package pkg : mPackages.values()) {
6325                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6326                    if (ps != null) {
6327                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6328                                userId);
6329                    }
6330                }
6331            }
6332
6333            return new ParceledListSlice<PackageInfo>(list);
6334        }
6335    }
6336
6337    @Override
6338    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6339        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6340        flags = updateFlagsForApplication(flags, userId, null);
6341        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6342
6343        // writer
6344        synchronized (mPackages) {
6345            ArrayList<ApplicationInfo> list;
6346            if (listUninstalled) {
6347                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6348                for (PackageSetting ps : mSettings.mPackages.values()) {
6349                    ApplicationInfo ai;
6350                    if (ps.pkg != null) {
6351                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6352                                ps.readUserState(userId), userId);
6353                    } else {
6354                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6355                    }
6356                    if (ai != null) {
6357                        list.add(ai);
6358                    }
6359                }
6360            } else {
6361                list = new ArrayList<ApplicationInfo>(mPackages.size());
6362                for (PackageParser.Package p : mPackages.values()) {
6363                    if (p.mExtras != null) {
6364                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6365                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6366                        if (ai != null) {
6367                            list.add(ai);
6368                        }
6369                    }
6370                }
6371            }
6372
6373            return new ParceledListSlice<ApplicationInfo>(list);
6374        }
6375    }
6376
6377    @Override
6378    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6379        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6380            return null;
6381        }
6382
6383        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6384                "getEphemeralApplications");
6385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6386                true /* requireFullPermission */, false /* checkShell */,
6387                "getEphemeralApplications");
6388        synchronized (mPackages) {
6389            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6390                    .getEphemeralApplicationsLPw(userId);
6391            if (ephemeralApps != null) {
6392                return new ParceledListSlice<>(ephemeralApps);
6393            }
6394        }
6395        return null;
6396    }
6397
6398    @Override
6399    public boolean isEphemeralApplication(String packageName, int userId) {
6400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6401                true /* requireFullPermission */, false /* checkShell */,
6402                "isEphemeral");
6403        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6404            return false;
6405        }
6406
6407        if (!isCallerSameApp(packageName)) {
6408            return false;
6409        }
6410        synchronized (mPackages) {
6411            PackageParser.Package pkg = mPackages.get(packageName);
6412            if (pkg != null) {
6413                return pkg.applicationInfo.isEphemeralApp();
6414            }
6415        }
6416        return false;
6417    }
6418
6419    @Override
6420    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6421        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6422            return null;
6423        }
6424
6425        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6426                true /* requireFullPermission */, false /* checkShell */,
6427                "getCookie");
6428        if (!isCallerSameApp(packageName)) {
6429            return null;
6430        }
6431        synchronized (mPackages) {
6432            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6433                    packageName, userId);
6434        }
6435    }
6436
6437    @Override
6438    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6439        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6440            return true;
6441        }
6442
6443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6444                true /* requireFullPermission */, true /* checkShell */,
6445                "setCookie");
6446        if (!isCallerSameApp(packageName)) {
6447            return false;
6448        }
6449        synchronized (mPackages) {
6450            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6451                    packageName, cookie, userId);
6452        }
6453    }
6454
6455    @Override
6456    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6457        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6458            return null;
6459        }
6460
6461        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6462                "getEphemeralApplicationIcon");
6463        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6464                true /* requireFullPermission */, false /* checkShell */,
6465                "getEphemeralApplicationIcon");
6466        synchronized (mPackages) {
6467            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6468                    packageName, userId);
6469        }
6470    }
6471
6472    private boolean isCallerSameApp(String packageName) {
6473        PackageParser.Package pkg = mPackages.get(packageName);
6474        return pkg != null
6475                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6476    }
6477
6478    @Override
6479    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6480        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6481    }
6482
6483    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6484        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6485
6486        // reader
6487        synchronized (mPackages) {
6488            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6489            final int userId = UserHandle.getCallingUserId();
6490            while (i.hasNext()) {
6491                final PackageParser.Package p = i.next();
6492                if (p.applicationInfo == null) continue;
6493
6494                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6495                        && !p.applicationInfo.isDirectBootAware();
6496                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6497                        && p.applicationInfo.isDirectBootAware();
6498
6499                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6500                        && (!mSafeMode || isSystemApp(p))
6501                        && (matchesUnaware || matchesAware)) {
6502                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6503                    if (ps != null) {
6504                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6505                                ps.readUserState(userId), userId);
6506                        if (ai != null) {
6507                            finalList.add(ai);
6508                        }
6509                    }
6510                }
6511            }
6512        }
6513
6514        return finalList;
6515    }
6516
6517    @Override
6518    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6519        if (!sUserManager.exists(userId)) return null;
6520        flags = updateFlagsForComponent(flags, userId, name);
6521        // reader
6522        synchronized (mPackages) {
6523            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6524            PackageSetting ps = provider != null
6525                    ? mSettings.mPackages.get(provider.owner.packageName)
6526                    : null;
6527            return ps != null
6528                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6529                    ? PackageParser.generateProviderInfo(provider, flags,
6530                            ps.readUserState(userId), userId)
6531                    : null;
6532        }
6533    }
6534
6535    /**
6536     * @deprecated
6537     */
6538    @Deprecated
6539    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6540        // reader
6541        synchronized (mPackages) {
6542            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6543                    .entrySet().iterator();
6544            final int userId = UserHandle.getCallingUserId();
6545            while (i.hasNext()) {
6546                Map.Entry<String, PackageParser.Provider> entry = i.next();
6547                PackageParser.Provider p = entry.getValue();
6548                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6549
6550                if (ps != null && p.syncable
6551                        && (!mSafeMode || (p.info.applicationInfo.flags
6552                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6553                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6554                            ps.readUserState(userId), userId);
6555                    if (info != null) {
6556                        outNames.add(entry.getKey());
6557                        outInfo.add(info);
6558                    }
6559                }
6560            }
6561        }
6562    }
6563
6564    @Override
6565    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6566            int uid, int flags) {
6567        final int userId = processName != null ? UserHandle.getUserId(uid)
6568                : UserHandle.getCallingUserId();
6569        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6570        flags = updateFlagsForComponent(flags, userId, processName);
6571
6572        ArrayList<ProviderInfo> finalList = null;
6573        // reader
6574        synchronized (mPackages) {
6575            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6576            while (i.hasNext()) {
6577                final PackageParser.Provider p = i.next();
6578                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6579                if (ps != null && p.info.authority != null
6580                        && (processName == null
6581                                || (p.info.processName.equals(processName)
6582                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6583                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6584                    if (finalList == null) {
6585                        finalList = new ArrayList<ProviderInfo>(3);
6586                    }
6587                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6588                            ps.readUserState(userId), userId);
6589                    if (info != null) {
6590                        finalList.add(info);
6591                    }
6592                }
6593            }
6594        }
6595
6596        if (finalList != null) {
6597            Collections.sort(finalList, mProviderInitOrderSorter);
6598            return new ParceledListSlice<ProviderInfo>(finalList);
6599        }
6600
6601        return ParceledListSlice.emptyList();
6602    }
6603
6604    @Override
6605    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6606        // reader
6607        synchronized (mPackages) {
6608            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6609            return PackageParser.generateInstrumentationInfo(i, flags);
6610        }
6611    }
6612
6613    @Override
6614    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6615            String targetPackage, int flags) {
6616        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6617    }
6618
6619    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6620            int flags) {
6621        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6622
6623        // reader
6624        synchronized (mPackages) {
6625            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6626            while (i.hasNext()) {
6627                final PackageParser.Instrumentation p = i.next();
6628                if (targetPackage == null
6629                        || targetPackage.equals(p.info.targetPackage)) {
6630                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6631                            flags);
6632                    if (ii != null) {
6633                        finalList.add(ii);
6634                    }
6635                }
6636            }
6637        }
6638
6639        return finalList;
6640    }
6641
6642    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6643        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6644        if (overlays == null) {
6645            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6646            return;
6647        }
6648        for (PackageParser.Package opkg : overlays.values()) {
6649            // Not much to do if idmap fails: we already logged the error
6650            // and we certainly don't want to abort installation of pkg simply
6651            // because an overlay didn't fit properly. For these reasons,
6652            // ignore the return value of createIdmapForPackagePairLI.
6653            createIdmapForPackagePairLI(pkg, opkg);
6654        }
6655    }
6656
6657    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6658            PackageParser.Package opkg) {
6659        if (!opkg.mTrustedOverlay) {
6660            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6661                    opkg.baseCodePath + ": overlay not trusted");
6662            return false;
6663        }
6664        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6665        if (overlaySet == null) {
6666            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6667                    opkg.baseCodePath + " but target package has no known overlays");
6668            return false;
6669        }
6670        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6671        // TODO: generate idmap for split APKs
6672        try {
6673            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6674        } catch (InstallerException e) {
6675            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6676                    + opkg.baseCodePath);
6677            return false;
6678        }
6679        PackageParser.Package[] overlayArray =
6680            overlaySet.values().toArray(new PackageParser.Package[0]);
6681        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6682            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6683                return p1.mOverlayPriority - p2.mOverlayPriority;
6684            }
6685        };
6686        Arrays.sort(overlayArray, cmp);
6687
6688        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6689        int i = 0;
6690        for (PackageParser.Package p : overlayArray) {
6691            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6692        }
6693        return true;
6694    }
6695
6696    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6697        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6698        try {
6699            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6700        } finally {
6701            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6702        }
6703    }
6704
6705    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6706        final File[] files = dir.listFiles();
6707        if (ArrayUtils.isEmpty(files)) {
6708            Log.d(TAG, "No files in app dir " + dir);
6709            return;
6710        }
6711
6712        if (DEBUG_PACKAGE_SCANNING) {
6713            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6714                    + " flags=0x" + Integer.toHexString(parseFlags));
6715        }
6716
6717        for (File file : files) {
6718            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6719                    && !PackageInstallerService.isStageName(file.getName());
6720            if (!isPackage) {
6721                // Ignore entries which are not packages
6722                continue;
6723            }
6724            try {
6725                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6726                        scanFlags, currentTime, null);
6727            } catch (PackageManagerException e) {
6728                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6729
6730                // Delete invalid userdata apps
6731                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6732                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6733                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6734                    removeCodePathLI(file);
6735                }
6736            }
6737        }
6738    }
6739
6740    private static File getSettingsProblemFile() {
6741        File dataDir = Environment.getDataDirectory();
6742        File systemDir = new File(dataDir, "system");
6743        File fname = new File(systemDir, "uiderrors.txt");
6744        return fname;
6745    }
6746
6747    static void reportSettingsProblem(int priority, String msg) {
6748        logCriticalInfo(priority, msg);
6749    }
6750
6751    static void logCriticalInfo(int priority, String msg) {
6752        Slog.println(priority, TAG, msg);
6753        EventLogTags.writePmCriticalInfo(msg);
6754        try {
6755            File fname = getSettingsProblemFile();
6756            FileOutputStream out = new FileOutputStream(fname, true);
6757            PrintWriter pw = new FastPrintWriter(out);
6758            SimpleDateFormat formatter = new SimpleDateFormat();
6759            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6760            pw.println(dateString + ": " + msg);
6761            pw.close();
6762            FileUtils.setPermissions(
6763                    fname.toString(),
6764                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6765                    -1, -1);
6766        } catch (java.io.IOException e) {
6767        }
6768    }
6769
6770    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6771        if (srcFile.isDirectory()) {
6772            final File baseFile = new File(pkg.baseCodePath);
6773            long maxModifiedTime = baseFile.lastModified();
6774            if (pkg.splitCodePaths != null) {
6775                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6776                    final File splitFile = new File(pkg.splitCodePaths[i]);
6777                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6778                }
6779            }
6780            return maxModifiedTime;
6781        }
6782        return srcFile.lastModified();
6783    }
6784
6785    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6786            final int policyFlags) throws PackageManagerException {
6787        // When upgrading from pre-N MR1, verify the package time stamp using the package
6788        // directory and not the APK file.
6789        final long lastModifiedTime = mIsPreNMR1Upgrade
6790                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6791        if (ps != null
6792                && ps.codePath.equals(srcFile)
6793                && ps.timeStamp == lastModifiedTime
6794                && !isCompatSignatureUpdateNeeded(pkg)
6795                && !isRecoverSignatureUpdateNeeded(pkg)) {
6796            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6797            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6798            ArraySet<PublicKey> signingKs;
6799            synchronized (mPackages) {
6800                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6801            }
6802            if (ps.signatures.mSignatures != null
6803                    && ps.signatures.mSignatures.length != 0
6804                    && signingKs != null) {
6805                // Optimization: reuse the existing cached certificates
6806                // if the package appears to be unchanged.
6807                pkg.mSignatures = ps.signatures.mSignatures;
6808                pkg.mSigningKeys = signingKs;
6809                return;
6810            }
6811
6812            Slog.w(TAG, "PackageSetting for " + ps.name
6813                    + " is missing signatures.  Collecting certs again to recover them.");
6814        } else {
6815            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6816        }
6817
6818        try {
6819            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6820            PackageParser.collectCertificates(pkg, policyFlags);
6821        } catch (PackageParserException e) {
6822            throw PackageManagerException.from(e);
6823        } finally {
6824            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6825        }
6826    }
6827
6828    /**
6829     *  Traces a package scan.
6830     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6831     */
6832    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6833            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6834        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6835        try {
6836            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6837        } finally {
6838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6839        }
6840    }
6841
6842    /**
6843     *  Scans a package and returns the newly parsed package.
6844     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6845     */
6846    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6847            long currentTime, UserHandle user) throws PackageManagerException {
6848        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6849        PackageParser pp = new PackageParser();
6850        pp.setSeparateProcesses(mSeparateProcesses);
6851        pp.setOnlyCoreApps(mOnlyCore);
6852        pp.setDisplayMetrics(mMetrics);
6853
6854        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6855            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6856        }
6857
6858        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6859        final PackageParser.Package pkg;
6860        try {
6861            pkg = pp.parsePackage(scanFile, parseFlags);
6862        } catch (PackageParserException e) {
6863            throw PackageManagerException.from(e);
6864        } finally {
6865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6866        }
6867
6868        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6869    }
6870
6871    /**
6872     *  Scans a package and returns the newly parsed package.
6873     *  @throws PackageManagerException on a parse error.
6874     */
6875    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6876            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6877            throws PackageManagerException {
6878        // If the package has children and this is the first dive in the function
6879        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6880        // packages (parent and children) would be successfully scanned before the
6881        // actual scan since scanning mutates internal state and we want to atomically
6882        // install the package and its children.
6883        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6884            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6885                scanFlags |= SCAN_CHECK_ONLY;
6886            }
6887        } else {
6888            scanFlags &= ~SCAN_CHECK_ONLY;
6889        }
6890
6891        // Scan the parent
6892        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6893                scanFlags, currentTime, user);
6894
6895        // Scan the children
6896        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6897        for (int i = 0; i < childCount; i++) {
6898            PackageParser.Package childPackage = pkg.childPackages.get(i);
6899            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6900                    currentTime, user);
6901        }
6902
6903
6904        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6905            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6906        }
6907
6908        return scannedPkg;
6909    }
6910
6911    /**
6912     *  Scans a package and returns the newly parsed package.
6913     *  @throws PackageManagerException on a parse error.
6914     */
6915    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6916            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6917            throws PackageManagerException {
6918        PackageSetting ps = null;
6919        PackageSetting updatedPkg;
6920        // reader
6921        synchronized (mPackages) {
6922            // Look to see if we already know about this package.
6923            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6924            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6925                // This package has been renamed to its original name.  Let's
6926                // use that.
6927                ps = mSettings.getPackageLPr(oldName);
6928            }
6929            // If there was no original package, see one for the real package name.
6930            if (ps == null) {
6931                ps = mSettings.getPackageLPr(pkg.packageName);
6932            }
6933            // Check to see if this package could be hiding/updating a system
6934            // package.  Must look for it either under the original or real
6935            // package name depending on our state.
6936            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6937            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6938
6939            // If this is a package we don't know about on the system partition, we
6940            // may need to remove disabled child packages on the system partition
6941            // or may need to not add child packages if the parent apk is updated
6942            // on the data partition and no longer defines this child package.
6943            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6944                // If this is a parent package for an updated system app and this system
6945                // app got an OTA update which no longer defines some of the child packages
6946                // we have to prune them from the disabled system packages.
6947                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6948                if (disabledPs != null) {
6949                    final int scannedChildCount = (pkg.childPackages != null)
6950                            ? pkg.childPackages.size() : 0;
6951                    final int disabledChildCount = disabledPs.childPackageNames != null
6952                            ? disabledPs.childPackageNames.size() : 0;
6953                    for (int i = 0; i < disabledChildCount; i++) {
6954                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6955                        boolean disabledPackageAvailable = false;
6956                        for (int j = 0; j < scannedChildCount; j++) {
6957                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6958                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6959                                disabledPackageAvailable = true;
6960                                break;
6961                            }
6962                         }
6963                         if (!disabledPackageAvailable) {
6964                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6965                         }
6966                    }
6967                }
6968            }
6969        }
6970
6971        boolean updatedPkgBetter = false;
6972        // First check if this is a system package that may involve an update
6973        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6974            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6975            // it needs to drop FLAG_PRIVILEGED.
6976            if (locationIsPrivileged(scanFile)) {
6977                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6978            } else {
6979                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6980            }
6981
6982            if (ps != null && !ps.codePath.equals(scanFile)) {
6983                // The path has changed from what was last scanned...  check the
6984                // version of the new path against what we have stored to determine
6985                // what to do.
6986                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6987                if (pkg.mVersionCode <= ps.versionCode) {
6988                    // The system package has been updated and the code path does not match
6989                    // Ignore entry. Skip it.
6990                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6991                            + " ignored: updated version " + ps.versionCode
6992                            + " better than this " + pkg.mVersionCode);
6993                    if (!updatedPkg.codePath.equals(scanFile)) {
6994                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6995                                + ps.name + " changing from " + updatedPkg.codePathString
6996                                + " to " + scanFile);
6997                        updatedPkg.codePath = scanFile;
6998                        updatedPkg.codePathString = scanFile.toString();
6999                        updatedPkg.resourcePath = scanFile;
7000                        updatedPkg.resourcePathString = scanFile.toString();
7001                    }
7002                    updatedPkg.pkg = pkg;
7003                    updatedPkg.versionCode = pkg.mVersionCode;
7004
7005                    // Update the disabled system child packages to point to the package too.
7006                    final int childCount = updatedPkg.childPackageNames != null
7007                            ? updatedPkg.childPackageNames.size() : 0;
7008                    for (int i = 0; i < childCount; i++) {
7009                        String childPackageName = updatedPkg.childPackageNames.get(i);
7010                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7011                                childPackageName);
7012                        if (updatedChildPkg != null) {
7013                            updatedChildPkg.pkg = pkg;
7014                            updatedChildPkg.versionCode = pkg.mVersionCode;
7015                        }
7016                    }
7017
7018                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7019                            + scanFile + " ignored: updated version " + ps.versionCode
7020                            + " better than this " + pkg.mVersionCode);
7021                } else {
7022                    // The current app on the system partition is better than
7023                    // what we have updated to on the data partition; switch
7024                    // back to the system partition version.
7025                    // At this point, its safely assumed that package installation for
7026                    // apps in system partition will go through. If not there won't be a working
7027                    // version of the app
7028                    // writer
7029                    synchronized (mPackages) {
7030                        // Just remove the loaded entries from package lists.
7031                        mPackages.remove(ps.name);
7032                    }
7033
7034                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7035                            + " reverting from " + ps.codePathString
7036                            + ": new version " + pkg.mVersionCode
7037                            + " better than installed " + ps.versionCode);
7038
7039                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7040                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7041                    synchronized (mInstallLock) {
7042                        args.cleanUpResourcesLI();
7043                    }
7044                    synchronized (mPackages) {
7045                        mSettings.enableSystemPackageLPw(ps.name);
7046                    }
7047                    updatedPkgBetter = true;
7048                }
7049            }
7050        }
7051
7052        if (updatedPkg != null) {
7053            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7054            // initially
7055            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7056
7057            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7058            // flag set initially
7059            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7060                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7061            }
7062        }
7063
7064        // Verify certificates against what was last scanned
7065        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7066
7067        /*
7068         * A new system app appeared, but we already had a non-system one of the
7069         * same name installed earlier.
7070         */
7071        boolean shouldHideSystemApp = false;
7072        if (updatedPkg == null && ps != null
7073                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7074            /*
7075             * Check to make sure the signatures match first. If they don't,
7076             * wipe the installed application and its data.
7077             */
7078            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7079                    != PackageManager.SIGNATURE_MATCH) {
7080                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7081                        + " signatures don't match existing userdata copy; removing");
7082                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7083                        "scanPackageInternalLI")) {
7084                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7085                }
7086                ps = null;
7087            } else {
7088                /*
7089                 * If the newly-added system app is an older version than the
7090                 * already installed version, hide it. It will be scanned later
7091                 * and re-added like an update.
7092                 */
7093                if (pkg.mVersionCode <= ps.versionCode) {
7094                    shouldHideSystemApp = true;
7095                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7096                            + " but new version " + pkg.mVersionCode + " better than installed "
7097                            + ps.versionCode + "; hiding system");
7098                } else {
7099                    /*
7100                     * The newly found system app is a newer version that the
7101                     * one previously installed. Simply remove the
7102                     * already-installed application and replace it with our own
7103                     * while keeping the application data.
7104                     */
7105                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7106                            + " reverting from " + ps.codePathString + ": new version "
7107                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7108                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7109                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7110                    synchronized (mInstallLock) {
7111                        args.cleanUpResourcesLI();
7112                    }
7113                }
7114            }
7115        }
7116
7117        // The apk is forward locked (not public) if its code and resources
7118        // are kept in different files. (except for app in either system or
7119        // vendor path).
7120        // TODO grab this value from PackageSettings
7121        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7122            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7123                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7124            }
7125        }
7126
7127        // TODO: extend to support forward-locked splits
7128        String resourcePath = null;
7129        String baseResourcePath = null;
7130        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7131            if (ps != null && ps.resourcePathString != null) {
7132                resourcePath = ps.resourcePathString;
7133                baseResourcePath = ps.resourcePathString;
7134            } else {
7135                // Should not happen at all. Just log an error.
7136                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7137            }
7138        } else {
7139            resourcePath = pkg.codePath;
7140            baseResourcePath = pkg.baseCodePath;
7141        }
7142
7143        // Set application objects path explicitly.
7144        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7145        pkg.setApplicationInfoCodePath(pkg.codePath);
7146        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7147        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7148        pkg.setApplicationInfoResourcePath(resourcePath);
7149        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7150        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7151
7152        // Note that we invoke the following method only if we are about to unpack an application
7153        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7154                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7155
7156        /*
7157         * If the system app should be overridden by a previously installed
7158         * data, hide the system app now and let the /data/app scan pick it up
7159         * again.
7160         */
7161        if (shouldHideSystemApp) {
7162            synchronized (mPackages) {
7163                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7164            }
7165        }
7166
7167        return scannedPkg;
7168    }
7169
7170    private static String fixProcessName(String defProcessName,
7171            String processName) {
7172        if (processName == null) {
7173            return defProcessName;
7174        }
7175        return processName;
7176    }
7177
7178    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7179            throws PackageManagerException {
7180        if (pkgSetting.signatures.mSignatures != null) {
7181            // Already existing package. Make sure signatures match
7182            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7183                    == PackageManager.SIGNATURE_MATCH;
7184            if (!match) {
7185                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7186                        == PackageManager.SIGNATURE_MATCH;
7187            }
7188            if (!match) {
7189                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7190                        == PackageManager.SIGNATURE_MATCH;
7191            }
7192            if (!match) {
7193                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7194                        + pkg.packageName + " signatures do not match the "
7195                        + "previously installed version; ignoring!");
7196            }
7197        }
7198
7199        // Check for shared user signatures
7200        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7201            // Already existing package. Make sure signatures match
7202            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7203                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7204            if (!match) {
7205                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7206                        == PackageManager.SIGNATURE_MATCH;
7207            }
7208            if (!match) {
7209                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7210                        == PackageManager.SIGNATURE_MATCH;
7211            }
7212            if (!match) {
7213                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7214                        "Package " + pkg.packageName
7215                        + " has no signatures that match those in shared user "
7216                        + pkgSetting.sharedUser.name + "; ignoring!");
7217            }
7218        }
7219    }
7220
7221    /**
7222     * Enforces that only the system UID or root's UID can call a method exposed
7223     * via Binder.
7224     *
7225     * @param message used as message if SecurityException is thrown
7226     * @throws SecurityException if the caller is not system or root
7227     */
7228    private static final void enforceSystemOrRoot(String message) {
7229        final int uid = Binder.getCallingUid();
7230        if (uid != Process.SYSTEM_UID && uid != 0) {
7231            throw new SecurityException(message);
7232        }
7233    }
7234
7235    @Override
7236    public void performFstrimIfNeeded() {
7237        enforceSystemOrRoot("Only the system can request fstrim");
7238
7239        // Before everything else, see whether we need to fstrim.
7240        try {
7241            IMountService ms = PackageHelper.getMountService();
7242            if (ms != null) {
7243                boolean doTrim = false;
7244                final long interval = android.provider.Settings.Global.getLong(
7245                        mContext.getContentResolver(),
7246                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7247                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7248                if (interval > 0) {
7249                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7250                    if (timeSinceLast > interval) {
7251                        doTrim = true;
7252                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7253                                + "; running immediately");
7254                    }
7255                }
7256                if (doTrim) {
7257                    final boolean dexOptDialogShown;
7258                    synchronized (mPackages) {
7259                        dexOptDialogShown = mDexOptDialogShown;
7260                    }
7261                    if (!isFirstBoot() && dexOptDialogShown) {
7262                        try {
7263                            ActivityManager.getService().showBootMessage(
7264                                    mContext.getResources().getString(
7265                                            R.string.android_upgrading_fstrim), true);
7266                        } catch (RemoteException e) {
7267                        }
7268                    }
7269                    ms.runMaintenance();
7270                }
7271            } else {
7272                Slog.e(TAG, "Mount service unavailable!");
7273            }
7274        } catch (RemoteException e) {
7275            // Can't happen; MountService is local
7276        }
7277    }
7278
7279    @Override
7280    public void updatePackagesIfNeeded() {
7281        enforceSystemOrRoot("Only the system can request package update");
7282
7283        // We need to re-extract after an OTA.
7284        boolean causeUpgrade = isUpgrade();
7285
7286        // First boot or factory reset.
7287        // Note: we also handle devices that are upgrading to N right now as if it is their
7288        //       first boot, as they do not have profile data.
7289        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7290
7291        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7292        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7293
7294        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7295            return;
7296        }
7297
7298        List<PackageParser.Package> pkgs;
7299        synchronized (mPackages) {
7300            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7301        }
7302
7303        final long startTime = System.nanoTime();
7304        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7305                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7306
7307        final int elapsedTimeSeconds =
7308                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7309
7310        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7311        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7312        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7313        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7314        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7315    }
7316
7317    /**
7318     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7319     * containing statistics about the invocation. The array consists of three elements,
7320     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7321     * and {@code numberOfPackagesFailed}.
7322     */
7323    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7324            String compilerFilter) {
7325
7326        int numberOfPackagesVisited = 0;
7327        int numberOfPackagesOptimized = 0;
7328        int numberOfPackagesSkipped = 0;
7329        int numberOfPackagesFailed = 0;
7330        final int numberOfPackagesToDexopt = pkgs.size();
7331
7332        for (PackageParser.Package pkg : pkgs) {
7333            numberOfPackagesVisited++;
7334
7335            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7336                if (DEBUG_DEXOPT) {
7337                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7338                }
7339                numberOfPackagesSkipped++;
7340                continue;
7341            }
7342
7343            if (DEBUG_DEXOPT) {
7344                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7345                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7346            }
7347
7348            if (showDialog) {
7349                try {
7350                    ActivityManager.getService().showBootMessage(
7351                            mContext.getResources().getString(R.string.android_upgrading_apk,
7352                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7353                } catch (RemoteException e) {
7354                }
7355                synchronized (mPackages) {
7356                    mDexOptDialogShown = true;
7357                }
7358            }
7359
7360            // If the OTA updates a system app which was previously preopted to a non-preopted state
7361            // the app might end up being verified at runtime. That's because by default the apps
7362            // are verify-profile but for preopted apps there's no profile.
7363            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7364            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7365            // filter (by default interpret-only).
7366            // Note that at this stage unused apps are already filtered.
7367            if (isSystemApp(pkg) &&
7368                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7369                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7370                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7371            }
7372
7373            // If the OTA updates a system app which was previously preopted to a non-preopted state
7374            // the app might end up being verified at runtime. That's because by default the apps
7375            // are verify-profile but for preopted apps there's no profile.
7376            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7377            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7378            // filter (by default interpret-only).
7379            // Note that at this stage unused apps are already filtered.
7380            if (isSystemApp(pkg) &&
7381                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7382                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7383                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7384            }
7385
7386            // checkProfiles is false to avoid merging profiles during boot which
7387            // might interfere with background compilation (b/28612421).
7388            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7389            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7390            // trade-off worth doing to save boot time work.
7391            int dexOptStatus = performDexOptTraced(pkg.packageName,
7392                    false /* checkProfiles */,
7393                    compilerFilter,
7394                    false /* force */);
7395            switch (dexOptStatus) {
7396                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7397                    numberOfPackagesOptimized++;
7398                    break;
7399                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7400                    numberOfPackagesSkipped++;
7401                    break;
7402                case PackageDexOptimizer.DEX_OPT_FAILED:
7403                    numberOfPackagesFailed++;
7404                    break;
7405                default:
7406                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7407                    break;
7408            }
7409        }
7410
7411        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7412                numberOfPackagesFailed };
7413    }
7414
7415    @Override
7416    public void notifyPackageUse(String packageName, int reason) {
7417        synchronized (mPackages) {
7418            PackageParser.Package p = mPackages.get(packageName);
7419            if (p == null) {
7420                return;
7421            }
7422            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7423        }
7424    }
7425
7426    // TODO: this is not used nor needed. Delete it.
7427    @Override
7428    public boolean performDexOptIfNeeded(String packageName) {
7429        int dexOptStatus = performDexOptTraced(packageName,
7430                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7431        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7432    }
7433
7434    @Override
7435    public boolean performDexOpt(String packageName,
7436            boolean checkProfiles, int compileReason, boolean force) {
7437        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7438                getCompilerFilterForReason(compileReason), force);
7439        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7440    }
7441
7442    @Override
7443    public boolean performDexOptMode(String packageName,
7444            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7445        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7446                targetCompilerFilter, force);
7447        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7448    }
7449
7450    private int performDexOptTraced(String packageName,
7451                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7452        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7453        try {
7454            return performDexOptInternal(packageName, checkProfiles,
7455                    targetCompilerFilter, force);
7456        } finally {
7457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7458        }
7459    }
7460
7461    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7462    // if the package can now be considered up to date for the given filter.
7463    private int performDexOptInternal(String packageName,
7464                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7465        PackageParser.Package p;
7466        synchronized (mPackages) {
7467            p = mPackages.get(packageName);
7468            if (p == null) {
7469                // Package could not be found. Report failure.
7470                return PackageDexOptimizer.DEX_OPT_FAILED;
7471            }
7472            mPackageUsage.maybeWriteAsync(mPackages);
7473            mCompilerStats.maybeWriteAsync();
7474        }
7475        long callingId = Binder.clearCallingIdentity();
7476        try {
7477            synchronized (mInstallLock) {
7478                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7479                        targetCompilerFilter, force);
7480            }
7481        } finally {
7482            Binder.restoreCallingIdentity(callingId);
7483        }
7484    }
7485
7486    public ArraySet<String> getOptimizablePackages() {
7487        ArraySet<String> pkgs = new ArraySet<String>();
7488        synchronized (mPackages) {
7489            for (PackageParser.Package p : mPackages.values()) {
7490                if (PackageDexOptimizer.canOptimizePackage(p)) {
7491                    pkgs.add(p.packageName);
7492                }
7493            }
7494        }
7495        return pkgs;
7496    }
7497
7498    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7499            boolean checkProfiles, String targetCompilerFilter,
7500            boolean force) {
7501        // Select the dex optimizer based on the force parameter.
7502        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7503        //       allocate an object here.
7504        PackageDexOptimizer pdo = force
7505                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7506                : mPackageDexOptimizer;
7507
7508        // Optimize all dependencies first. Note: we ignore the return value and march on
7509        // on errors.
7510        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7511        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7512        if (!deps.isEmpty()) {
7513            for (PackageParser.Package depPackage : deps) {
7514                // TODO: Analyze and investigate if we (should) profile libraries.
7515                // Currently this will do a full compilation of the library by default.
7516                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7517                        false /* checkProfiles */,
7518                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7519                        getOrCreateCompilerPackageStats(depPackage));
7520            }
7521        }
7522        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7523                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7524    }
7525
7526    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7527        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7528            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7529            Set<String> collectedNames = new HashSet<>();
7530            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7531
7532            retValue.remove(p);
7533
7534            return retValue;
7535        } else {
7536            return Collections.emptyList();
7537        }
7538    }
7539
7540    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7541            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7542        if (!collectedNames.contains(p.packageName)) {
7543            collectedNames.add(p.packageName);
7544            collected.add(p);
7545
7546            if (p.usesLibraries != null) {
7547                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7548            }
7549            if (p.usesOptionalLibraries != null) {
7550                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7551                        collectedNames);
7552            }
7553        }
7554    }
7555
7556    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7557            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7558        for (String libName : libs) {
7559            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7560            if (libPkg != null) {
7561                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7562            }
7563        }
7564    }
7565
7566    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7567        synchronized (mPackages) {
7568            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7569            if (lib != null && lib.apk != null) {
7570                return mPackages.get(lib.apk);
7571            }
7572        }
7573        return null;
7574    }
7575
7576    public void shutdown() {
7577        mPackageUsage.writeNow(mPackages);
7578        mCompilerStats.writeNow();
7579    }
7580
7581    @Override
7582    public void dumpProfiles(String packageName) {
7583        PackageParser.Package pkg;
7584        synchronized (mPackages) {
7585            pkg = mPackages.get(packageName);
7586            if (pkg == null) {
7587                throw new IllegalArgumentException("Unknown package: " + packageName);
7588            }
7589        }
7590        /* Only the shell, root, or the app user should be able to dump profiles. */
7591        int callingUid = Binder.getCallingUid();
7592        if (callingUid != Process.SHELL_UID &&
7593            callingUid != Process.ROOT_UID &&
7594            callingUid != pkg.applicationInfo.uid) {
7595            throw new SecurityException("dumpProfiles");
7596        }
7597
7598        synchronized (mInstallLock) {
7599            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7600            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7601            try {
7602                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7603                String gid = Integer.toString(sharedGid);
7604                String codePaths = TextUtils.join(";", allCodePaths);
7605                mInstaller.dumpProfiles(gid, packageName, codePaths);
7606            } catch (InstallerException e) {
7607                Slog.w(TAG, "Failed to dump profiles", e);
7608            }
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610        }
7611    }
7612
7613    @Override
7614    public void forceDexOpt(String packageName) {
7615        enforceSystemOrRoot("forceDexOpt");
7616
7617        PackageParser.Package pkg;
7618        synchronized (mPackages) {
7619            pkg = mPackages.get(packageName);
7620            if (pkg == null) {
7621                throw new IllegalArgumentException("Unknown package: " + packageName);
7622            }
7623        }
7624
7625        synchronized (mInstallLock) {
7626            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7627
7628            // Whoever is calling forceDexOpt wants a fully compiled package.
7629            // Don't use profiles since that may cause compilation to be skipped.
7630            final int res = performDexOptInternalWithDependenciesLI(pkg,
7631                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7632                    true /* force */);
7633
7634            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7635            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7636                throw new IllegalStateException("Failed to dexopt: " + res);
7637            }
7638        }
7639    }
7640
7641    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7642        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7643            Slog.w(TAG, "Unable to update from " + oldPkg.name
7644                    + " to " + newPkg.packageName
7645                    + ": old package not in system partition");
7646            return false;
7647        } else if (mPackages.get(oldPkg.name) != null) {
7648            Slog.w(TAG, "Unable to update from " + oldPkg.name
7649                    + " to " + newPkg.packageName
7650                    + ": old package still exists");
7651            return false;
7652        }
7653        return true;
7654    }
7655
7656    void removeCodePathLI(File codePath) {
7657        if (codePath.isDirectory()) {
7658            try {
7659                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7660            } catch (InstallerException e) {
7661                Slog.w(TAG, "Failed to remove code path", e);
7662            }
7663        } else {
7664            codePath.delete();
7665        }
7666    }
7667
7668    private int[] resolveUserIds(int userId) {
7669        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7670    }
7671
7672    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7673        if (pkg == null) {
7674            Slog.wtf(TAG, "Package was null!", new Throwable());
7675            return;
7676        }
7677        clearAppDataLeafLIF(pkg, userId, flags);
7678        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7679        for (int i = 0; i < childCount; i++) {
7680            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7681        }
7682    }
7683
7684    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7685        final PackageSetting ps;
7686        synchronized (mPackages) {
7687            ps = mSettings.mPackages.get(pkg.packageName);
7688        }
7689        for (int realUserId : resolveUserIds(userId)) {
7690            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7691            try {
7692                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7693                        ceDataInode);
7694            } catch (InstallerException e) {
7695                Slog.w(TAG, String.valueOf(e));
7696            }
7697        }
7698    }
7699
7700    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7701        if (pkg == null) {
7702            Slog.wtf(TAG, "Package was null!", new Throwable());
7703            return;
7704        }
7705        destroyAppDataLeafLIF(pkg, userId, flags);
7706        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7707        for (int i = 0; i < childCount; i++) {
7708            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7709        }
7710    }
7711
7712    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7713        final PackageSetting ps;
7714        synchronized (mPackages) {
7715            ps = mSettings.mPackages.get(pkg.packageName);
7716        }
7717        for (int realUserId : resolveUserIds(userId)) {
7718            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7719            try {
7720                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7721                        ceDataInode);
7722            } catch (InstallerException e) {
7723                Slog.w(TAG, String.valueOf(e));
7724            }
7725        }
7726    }
7727
7728    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7729        if (pkg == null) {
7730            Slog.wtf(TAG, "Package was null!", new Throwable());
7731            return;
7732        }
7733        destroyAppProfilesLeafLIF(pkg);
7734        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7735        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7736        for (int i = 0; i < childCount; i++) {
7737            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7738            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7739                    true /* removeBaseMarker */);
7740        }
7741    }
7742
7743    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7744            boolean removeBaseMarker) {
7745        if (pkg.isForwardLocked()) {
7746            return;
7747        }
7748
7749        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7750            try {
7751                path = PackageManagerServiceUtils.realpath(new File(path));
7752            } catch (IOException e) {
7753                // TODO: Should we return early here ?
7754                Slog.w(TAG, "Failed to get canonical path", e);
7755                continue;
7756            }
7757
7758            final String useMarker = path.replace('/', '@');
7759            for (int realUserId : resolveUserIds(userId)) {
7760                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7761                if (removeBaseMarker) {
7762                    File foreignUseMark = new File(profileDir, useMarker);
7763                    if (foreignUseMark.exists()) {
7764                        if (!foreignUseMark.delete()) {
7765                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7766                                    + pkg.packageName);
7767                        }
7768                    }
7769                }
7770
7771                File[] markers = profileDir.listFiles();
7772                if (markers != null) {
7773                    final String searchString = "@" + pkg.packageName + "@";
7774                    // We also delete all markers that contain the package name we're
7775                    // uninstalling. These are associated with secondary dex-files belonging
7776                    // to the package. Reconstructing the path of these dex files is messy
7777                    // in general.
7778                    for (File marker : markers) {
7779                        if (marker.getName().indexOf(searchString) > 0) {
7780                            if (!marker.delete()) {
7781                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7782                                    + pkg.packageName);
7783                            }
7784                        }
7785                    }
7786                }
7787            }
7788        }
7789    }
7790
7791    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7792        try {
7793            mInstaller.destroyAppProfiles(pkg.packageName);
7794        } catch (InstallerException e) {
7795            Slog.w(TAG, String.valueOf(e));
7796        }
7797    }
7798
7799    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7800        if (pkg == null) {
7801            Slog.wtf(TAG, "Package was null!", new Throwable());
7802            return;
7803        }
7804        clearAppProfilesLeafLIF(pkg);
7805        // We don't remove the base foreign use marker when clearing profiles because
7806        // we will rename it when the app is updated. Unlike the actual profile contents,
7807        // the foreign use marker is good across installs.
7808        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7809        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7810        for (int i = 0; i < childCount; i++) {
7811            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7812        }
7813    }
7814
7815    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7816        try {
7817            mInstaller.clearAppProfiles(pkg.packageName);
7818        } catch (InstallerException e) {
7819            Slog.w(TAG, String.valueOf(e));
7820        }
7821    }
7822
7823    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7824            long lastUpdateTime) {
7825        // Set parent install/update time
7826        PackageSetting ps = (PackageSetting) pkg.mExtras;
7827        if (ps != null) {
7828            ps.firstInstallTime = firstInstallTime;
7829            ps.lastUpdateTime = lastUpdateTime;
7830        }
7831        // Set children install/update time
7832        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7833        for (int i = 0; i < childCount; i++) {
7834            PackageParser.Package childPkg = pkg.childPackages.get(i);
7835            ps = (PackageSetting) childPkg.mExtras;
7836            if (ps != null) {
7837                ps.firstInstallTime = firstInstallTime;
7838                ps.lastUpdateTime = lastUpdateTime;
7839            }
7840        }
7841    }
7842
7843    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7844            PackageParser.Package changingLib) {
7845        if (file.path != null) {
7846            usesLibraryFiles.add(file.path);
7847            return;
7848        }
7849        PackageParser.Package p = mPackages.get(file.apk);
7850        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7851            // If we are doing this while in the middle of updating a library apk,
7852            // then we need to make sure to use that new apk for determining the
7853            // dependencies here.  (We haven't yet finished committing the new apk
7854            // to the package manager state.)
7855            if (p == null || p.packageName.equals(changingLib.packageName)) {
7856                p = changingLib;
7857            }
7858        }
7859        if (p != null) {
7860            usesLibraryFiles.addAll(p.getAllCodePaths());
7861        }
7862    }
7863
7864    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7865            PackageParser.Package changingLib) throws PackageManagerException {
7866        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7867            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7868            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7869            for (int i=0; i<N; i++) {
7870                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7871                if (file == null) {
7872                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7873                            "Package " + pkg.packageName + " requires unavailable shared library "
7874                            + pkg.usesLibraries.get(i) + "; failing!");
7875                }
7876                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7877            }
7878            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7879            for (int i=0; i<N; i++) {
7880                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7881                if (file == null) {
7882                    Slog.w(TAG, "Package " + pkg.packageName
7883                            + " desires unavailable shared library "
7884                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7885                } else {
7886                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7887                }
7888            }
7889            N = usesLibraryFiles.size();
7890            if (N > 0) {
7891                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7892            } else {
7893                pkg.usesLibraryFiles = null;
7894            }
7895        }
7896    }
7897
7898    private static boolean hasString(List<String> list, List<String> which) {
7899        if (list == null) {
7900            return false;
7901        }
7902        for (int i=list.size()-1; i>=0; i--) {
7903            for (int j=which.size()-1; j>=0; j--) {
7904                if (which.get(j).equals(list.get(i))) {
7905                    return true;
7906                }
7907            }
7908        }
7909        return false;
7910    }
7911
7912    private void updateAllSharedLibrariesLPw() {
7913        for (PackageParser.Package pkg : mPackages.values()) {
7914            try {
7915                updateSharedLibrariesLPr(pkg, null);
7916            } catch (PackageManagerException e) {
7917                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7918            }
7919        }
7920    }
7921
7922    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7923            PackageParser.Package changingPkg) {
7924        ArrayList<PackageParser.Package> res = null;
7925        for (PackageParser.Package pkg : mPackages.values()) {
7926            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7927                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7928                if (res == null) {
7929                    res = new ArrayList<PackageParser.Package>();
7930                }
7931                res.add(pkg);
7932                try {
7933                    updateSharedLibrariesLPr(pkg, changingPkg);
7934                } catch (PackageManagerException e) {
7935                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7936                }
7937            }
7938        }
7939        return res;
7940    }
7941
7942    /**
7943     * Derive the value of the {@code cpuAbiOverride} based on the provided
7944     * value and an optional stored value from the package settings.
7945     */
7946    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7947        String cpuAbiOverride = null;
7948
7949        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7950            cpuAbiOverride = null;
7951        } else if (abiOverride != null) {
7952            cpuAbiOverride = abiOverride;
7953        } else if (settings != null) {
7954            cpuAbiOverride = settings.cpuAbiOverrideString;
7955        }
7956
7957        return cpuAbiOverride;
7958    }
7959
7960    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7961            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7962                    throws PackageManagerException {
7963        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7964        // If the package has children and this is the first dive in the function
7965        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7966        // whether all packages (parent and children) would be successfully scanned
7967        // before the actual scan since scanning mutates internal state and we want
7968        // to atomically install the package and its children.
7969        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7970            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7971                scanFlags |= SCAN_CHECK_ONLY;
7972            }
7973        } else {
7974            scanFlags &= ~SCAN_CHECK_ONLY;
7975        }
7976
7977        final PackageParser.Package scannedPkg;
7978        try {
7979            // Scan the parent
7980            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7981            // Scan the children
7982            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7983            for (int i = 0; i < childCount; i++) {
7984                PackageParser.Package childPkg = pkg.childPackages.get(i);
7985                scanPackageLI(childPkg, policyFlags,
7986                        scanFlags, currentTime, user);
7987            }
7988        } finally {
7989            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7990        }
7991
7992        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7993            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7994        }
7995
7996        return scannedPkg;
7997    }
7998
7999    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8000            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8001        boolean success = false;
8002        try {
8003            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8004                    currentTime, user);
8005            success = true;
8006            return res;
8007        } finally {
8008            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8009                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8010                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8011                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8012                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8013            }
8014        }
8015    }
8016
8017    /**
8018     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8019     */
8020    private static boolean apkHasCode(String fileName) {
8021        StrictJarFile jarFile = null;
8022        try {
8023            jarFile = new StrictJarFile(fileName,
8024                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8025            return jarFile.findEntry("classes.dex") != null;
8026        } catch (IOException ignore) {
8027        } finally {
8028            try {
8029                if (jarFile != null) {
8030                    jarFile.close();
8031                }
8032            } catch (IOException ignore) {}
8033        }
8034        return false;
8035    }
8036
8037    /**
8038     * Enforces code policy for the package. This ensures that if an APK has
8039     * declared hasCode="true" in its manifest that the APK actually contains
8040     * code.
8041     *
8042     * @throws PackageManagerException If bytecode could not be found when it should exist
8043     */
8044    private static void assertCodePolicy(PackageParser.Package pkg)
8045            throws PackageManagerException {
8046        final boolean shouldHaveCode =
8047                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8048        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8049            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8050                    "Package " + pkg.baseCodePath + " code is missing");
8051        }
8052
8053        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8054            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8055                final boolean splitShouldHaveCode =
8056                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8057                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8058                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8059                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8060                }
8061            }
8062        }
8063    }
8064
8065    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8066            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8067                    throws PackageManagerException {
8068        if (DEBUG_PACKAGE_SCANNING) {
8069            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8070                Log.d(TAG, "Scanning package " + pkg.packageName);
8071        }
8072
8073        applyPolicy(pkg, policyFlags);
8074
8075        assertPackageIsValid(pkg, policyFlags);
8076
8077        // Initialize package source and resource directories
8078        final File scanFile = new File(pkg.codePath);
8079        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8080        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8081
8082        SharedUserSetting suid = null;
8083        PackageSetting pkgSetting = null;
8084
8085        // Getting the package setting may have a side-effect, so if we
8086        // are only checking if scan would succeed, stash a copy of the
8087        // old setting to restore at the end.
8088        PackageSetting nonMutatedPs = null;
8089
8090        // writer
8091        synchronized (mPackages) {
8092            if (pkg.mSharedUserId != null) {
8093                // SIDE EFFECTS; may potentially allocate a new shared user
8094                suid = mSettings.getSharedUserLPw(
8095                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8096                if (DEBUG_PACKAGE_SCANNING) {
8097                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8098                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8099                                + "): packages=" + suid.packages);
8100                }
8101            }
8102
8103            // Check if we are renaming from an original package name.
8104            PackageSetting origPackage = null;
8105            String realName = null;
8106            if (pkg.mOriginalPackages != null) {
8107                // This package may need to be renamed to a previously
8108                // installed name.  Let's check on that...
8109                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8110                if (pkg.mOriginalPackages.contains(renamed)) {
8111                    // This package had originally been installed as the
8112                    // original name, and we have already taken care of
8113                    // transitioning to the new one.  Just update the new
8114                    // one to continue using the old name.
8115                    realName = pkg.mRealPackage;
8116                    if (!pkg.packageName.equals(renamed)) {
8117                        // Callers into this function may have already taken
8118                        // care of renaming the package; only do it here if
8119                        // it is not already done.
8120                        pkg.setPackageName(renamed);
8121                    }
8122                } else {
8123                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8124                        if ((origPackage = mSettings.getPackageLPr(
8125                                pkg.mOriginalPackages.get(i))) != null) {
8126                            // We do have the package already installed under its
8127                            // original name...  should we use it?
8128                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8129                                // New package is not compatible with original.
8130                                origPackage = null;
8131                                continue;
8132                            } else if (origPackage.sharedUser != null) {
8133                                // Make sure uid is compatible between packages.
8134                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8135                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8136                                            + " to " + pkg.packageName + ": old uid "
8137                                            + origPackage.sharedUser.name
8138                                            + " differs from " + pkg.mSharedUserId);
8139                                    origPackage = null;
8140                                    continue;
8141                                }
8142                                // TODO: Add case when shared user id is added [b/28144775]
8143                            } else {
8144                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8145                                        + pkg.packageName + " to old name " + origPackage.name);
8146                            }
8147                            break;
8148                        }
8149                    }
8150                }
8151            }
8152
8153            if (mTransferedPackages.contains(pkg.packageName)) {
8154                Slog.w(TAG, "Package " + pkg.packageName
8155                        + " was transferred to another, but its .apk remains");
8156            }
8157
8158            // See comments in nonMutatedPs declaration
8159            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8160                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8161                if (foundPs != null) {
8162                    nonMutatedPs = new PackageSetting(foundPs);
8163                }
8164            }
8165
8166            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8167            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8168                PackageManagerService.reportSettingsProblem(Log.WARN,
8169                        "Package " + pkg.packageName + " shared user changed from "
8170                                + (pkgSetting.sharedUser != null
8171                                        ? pkgSetting.sharedUser.name : "<nothing>")
8172                                + " to "
8173                                + (suid != null ? suid.name : "<nothing>")
8174                                + "; replacing with new");
8175                pkgSetting = null;
8176            }
8177            final PackageSetting oldPkgSetting =
8178                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8179            final PackageSetting disabledPkgSetting =
8180                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8181            if (pkgSetting == null) {
8182                final String parentPackageName = (pkg.parentPackage != null)
8183                        ? pkg.parentPackage.packageName : null;
8184                // REMOVE SharedUserSetting from method; update in a separate call
8185                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8186                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8187                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8188                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8189                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8190                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8191                        UserManagerService.getInstance());
8192                // SIDE EFFECTS; updates system state; move elsewhere
8193                if (origPackage != null) {
8194                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8195                }
8196                mSettings.addUserToSettingLPw(pkgSetting);
8197            } else {
8198                // REMOVE SharedUserSetting from method; update in a separate call
8199                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8200                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8201                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8202                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8203                        UserManagerService.getInstance());
8204            }
8205            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8206            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8207
8208            // SIDE EFFECTS; modifies system state; move elsewhere
8209            if (pkgSetting.origPackage != null) {
8210                // If we are first transitioning from an original package,
8211                // fix up the new package's name now.  We need to do this after
8212                // looking up the package under its new name, so getPackageLP
8213                // can take care of fiddling things correctly.
8214                pkg.setPackageName(origPackage.name);
8215
8216                // File a report about this.
8217                String msg = "New package " + pkgSetting.realName
8218                        + " renamed to replace old package " + pkgSetting.name;
8219                reportSettingsProblem(Log.WARN, msg);
8220
8221                // Make a note of it.
8222                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8223                    mTransferedPackages.add(origPackage.name);
8224                }
8225
8226                // No longer need to retain this.
8227                pkgSetting.origPackage = null;
8228            }
8229
8230            // SIDE EFFECTS; modifies system state; move elsewhere
8231            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8232                // Make a note of it.
8233                mTransferedPackages.add(pkg.packageName);
8234            }
8235
8236            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8237                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8238            }
8239
8240            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8241                // Check all shared libraries and map to their actual file path.
8242                // We only do this here for apps not on a system dir, because those
8243                // are the only ones that can fail an install due to this.  We
8244                // will take care of the system apps by updating all of their
8245                // library paths after the scan is done.
8246                updateSharedLibrariesLPr(pkg, null);
8247            }
8248
8249            if (mFoundPolicyFile) {
8250                SELinuxMMAC.assignSeinfoValue(pkg);
8251            }
8252
8253            pkg.applicationInfo.uid = pkgSetting.appId;
8254            pkg.mExtras = pkgSetting;
8255            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8256                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8257                    // We just determined the app is signed correctly, so bring
8258                    // over the latest parsed certs.
8259                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8260                } else {
8261                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8262                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8263                                "Package " + pkg.packageName + " upgrade keys do not match the "
8264                                + "previously installed version");
8265                    } else {
8266                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8267                        String msg = "System package " + pkg.packageName
8268                                + " signature changed; retaining data.";
8269                        reportSettingsProblem(Log.WARN, msg);
8270                    }
8271                }
8272            } else {
8273                try {
8274                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8275                    verifySignaturesLP(pkgSetting, pkg);
8276                    // We just determined the app is signed correctly, so bring
8277                    // over the latest parsed certs.
8278                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8279                } catch (PackageManagerException e) {
8280                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8281                        throw e;
8282                    }
8283                    // The signature has changed, but this package is in the system
8284                    // image...  let's recover!
8285                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8286                    // However...  if this package is part of a shared user, but it
8287                    // doesn't match the signature of the shared user, let's fail.
8288                    // What this means is that you can't change the signatures
8289                    // associated with an overall shared user, which doesn't seem all
8290                    // that unreasonable.
8291                    if (pkgSetting.sharedUser != null) {
8292                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8293                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8294                            throw new PackageManagerException(
8295                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8296                                    "Signature mismatch for shared user: "
8297                                            + pkgSetting.sharedUser);
8298                        }
8299                    }
8300                    // File a report about this.
8301                    String msg = "System package " + pkg.packageName
8302                            + " signature changed; retaining data.";
8303                    reportSettingsProblem(Log.WARN, msg);
8304                }
8305            }
8306
8307            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8308                // This package wants to adopt ownership of permissions from
8309                // another package.
8310                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8311                    final String origName = pkg.mAdoptPermissions.get(i);
8312                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8313                    if (orig != null) {
8314                        if (verifyPackageUpdateLPr(orig, pkg)) {
8315                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8316                                    + pkg.packageName);
8317                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8318                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8319                        }
8320                    }
8321                }
8322            }
8323        }
8324
8325        pkg.applicationInfo.processName = fixProcessName(
8326                pkg.applicationInfo.packageName,
8327                pkg.applicationInfo.processName);
8328
8329        if (pkg != mPlatformPackage) {
8330            // Get all of our default paths setup
8331            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8332        }
8333
8334        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8335
8336        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8337            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8338            derivePackageAbi(
8339                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8340            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8341
8342            // Some system apps still use directory structure for native libraries
8343            // in which case we might end up not detecting abi solely based on apk
8344            // structure. Try to detect abi based on directory structure.
8345            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8346                    pkg.applicationInfo.primaryCpuAbi == null) {
8347                setBundledAppAbisAndRoots(pkg, pkgSetting);
8348                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8349            }
8350        } else {
8351            if ((scanFlags & SCAN_MOVE) != 0) {
8352                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8353                // but we already have this packages package info in the PackageSetting. We just
8354                // use that and derive the native library path based on the new codepath.
8355                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8356                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8357            }
8358
8359            // Set native library paths again. For moves, the path will be updated based on the
8360            // ABIs we've determined above. For non-moves, the path will be updated based on the
8361            // ABIs we determined during compilation, but the path will depend on the final
8362            // package path (after the rename away from the stage path).
8363            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8364        }
8365
8366        // This is a special case for the "system" package, where the ABI is
8367        // dictated by the zygote configuration (and init.rc). We should keep track
8368        // of this ABI so that we can deal with "normal" applications that run under
8369        // the same UID correctly.
8370        if (mPlatformPackage == pkg) {
8371            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8372                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8373        }
8374
8375        // If there's a mismatch between the abi-override in the package setting
8376        // and the abiOverride specified for the install. Warn about this because we
8377        // would've already compiled the app without taking the package setting into
8378        // account.
8379        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8380            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8381                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8382                        " for package " + pkg.packageName);
8383            }
8384        }
8385
8386        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8387        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8388        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8389
8390        // Copy the derived override back to the parsed package, so that we can
8391        // update the package settings accordingly.
8392        pkg.cpuAbiOverride = cpuAbiOverride;
8393
8394        if (DEBUG_ABI_SELECTION) {
8395            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8396                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8397                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8398        }
8399
8400        // Push the derived path down into PackageSettings so we know what to
8401        // clean up at uninstall time.
8402        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8403
8404        if (DEBUG_ABI_SELECTION) {
8405            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8406                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8407                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8408        }
8409
8410        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8411        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8412            // We don't do this here during boot because we can do it all
8413            // at once after scanning all existing packages.
8414            //
8415            // We also do this *before* we perform dexopt on this package, so that
8416            // we can avoid redundant dexopts, and also to make sure we've got the
8417            // code and package path correct.
8418            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8419        }
8420
8421        if (mFactoryTest && pkg.requestedPermissions.contains(
8422                android.Manifest.permission.FACTORY_TEST)) {
8423            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8424        }
8425
8426        if (isSystemApp(pkg)) {
8427            pkgSetting.isOrphaned = true;
8428        }
8429
8430        // Take care of first install / last update times.
8431        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8432        if (currentTime != 0) {
8433            if (pkgSetting.firstInstallTime == 0) {
8434                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8435            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8436                pkgSetting.lastUpdateTime = currentTime;
8437            }
8438        } else if (pkgSetting.firstInstallTime == 0) {
8439            // We need *something*.  Take time time stamp of the file.
8440            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8441        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8442            if (scanFileTime != pkgSetting.timeStamp) {
8443                // A package on the system image has changed; consider this
8444                // to be an update.
8445                pkgSetting.lastUpdateTime = scanFileTime;
8446            }
8447        }
8448        pkgSetting.setTimeStamp(scanFileTime);
8449
8450        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8451            if (nonMutatedPs != null) {
8452                synchronized (mPackages) {
8453                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8454                }
8455            }
8456        } else {
8457            // Modify state for the given package setting
8458            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8459                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8460        }
8461        return pkg;
8462    }
8463
8464    /**
8465     * Applies policy to the parsed package based upon the given policy flags.
8466     * Ensures the package is in a good state.
8467     * <p>
8468     * Implementation detail: This method must NOT have any side effect. It would
8469     * ideally be static, but, it requires locks to read system state.
8470     */
8471    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8472        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8473            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8474            if (pkg.applicationInfo.isDirectBootAware()) {
8475                // we're direct boot aware; set for all components
8476                for (PackageParser.Service s : pkg.services) {
8477                    s.info.encryptionAware = s.info.directBootAware = true;
8478                }
8479                for (PackageParser.Provider p : pkg.providers) {
8480                    p.info.encryptionAware = p.info.directBootAware = true;
8481                }
8482                for (PackageParser.Activity a : pkg.activities) {
8483                    a.info.encryptionAware = a.info.directBootAware = true;
8484                }
8485                for (PackageParser.Activity r : pkg.receivers) {
8486                    r.info.encryptionAware = r.info.directBootAware = true;
8487                }
8488            }
8489        } else {
8490            // Only allow system apps to be flagged as core apps.
8491            pkg.coreApp = false;
8492            // clear flags not applicable to regular apps
8493            pkg.applicationInfo.privateFlags &=
8494                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8495            pkg.applicationInfo.privateFlags &=
8496                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8497        }
8498        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8499
8500        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8501            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8502        }
8503
8504        if (!isSystemApp(pkg)) {
8505            // Only system apps can use these features.
8506            pkg.mOriginalPackages = null;
8507            pkg.mRealPackage = null;
8508            pkg.mAdoptPermissions = null;
8509        }
8510    }
8511
8512    /**
8513     * Asserts the parsed package is valid according to teh given policy. If the
8514     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8515     * <p>
8516     * Implementation detail: This method must NOT have any side effects. It would
8517     * ideally be static, but, it requires locks to read system state.
8518     *
8519     * @throws PackageManagerException If the package fails any of the validation checks
8520     */
8521    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8522            throws PackageManagerException {
8523        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8524            assertCodePolicy(pkg);
8525        }
8526
8527        if (pkg.applicationInfo.getCodePath() == null ||
8528                pkg.applicationInfo.getResourcePath() == null) {
8529            // Bail out. The resource and code paths haven't been set.
8530            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8531                    "Code and resource paths haven't been set correctly");
8532        }
8533
8534        // Make sure we're not adding any bogus keyset info
8535        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8536        ksms.assertScannedPackageValid(pkg);
8537
8538        synchronized (mPackages) {
8539            // The special "android" package can only be defined once
8540            if (pkg.packageName.equals("android")) {
8541                if (mAndroidApplication != null) {
8542                    Slog.w(TAG, "*************************************************");
8543                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8544                    Slog.w(TAG, " codePath=" + pkg.codePath);
8545                    Slog.w(TAG, "*************************************************");
8546                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8547                            "Core android package being redefined.  Skipping.");
8548                }
8549            }
8550
8551            // A package name must be unique; don't allow duplicates
8552            if (mPackages.containsKey(pkg.packageName)
8553                    || mSharedLibraries.containsKey(pkg.packageName)) {
8554                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8555                        "Application package " + pkg.packageName
8556                        + " already installed.  Skipping duplicate.");
8557            }
8558
8559            // Only privileged apps and updated privileged apps can add child packages.
8560            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8561                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8562                    throw new PackageManagerException("Only privileged apps can add child "
8563                            + "packages. Ignoring package " + pkg.packageName);
8564                }
8565                final int childCount = pkg.childPackages.size();
8566                for (int i = 0; i < childCount; i++) {
8567                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8568                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8569                            childPkg.packageName)) {
8570                        throw new PackageManagerException("Can't override child of "
8571                                + "another disabled app. Ignoring package " + pkg.packageName);
8572                    }
8573                }
8574            }
8575
8576            // If we're only installing presumed-existing packages, require that the
8577            // scanned APK is both already known and at the path previously established
8578            // for it.  Previously unknown packages we pick up normally, but if we have an
8579            // a priori expectation about this package's install presence, enforce it.
8580            // With a singular exception for new system packages. When an OTA contains
8581            // a new system package, we allow the codepath to change from a system location
8582            // to the user-installed location. If we don't allow this change, any newer,
8583            // user-installed version of the application will be ignored.
8584            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8585                if (mExpectingBetter.containsKey(pkg.packageName)) {
8586                    logCriticalInfo(Log.WARN,
8587                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8588                } else {
8589                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8590                    if (known != null) {
8591                        if (DEBUG_PACKAGE_SCANNING) {
8592                            Log.d(TAG, "Examining " + pkg.codePath
8593                                    + " and requiring known paths " + known.codePathString
8594                                    + " & " + known.resourcePathString);
8595                        }
8596                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8597                                || !pkg.applicationInfo.getResourcePath().equals(
8598                                        known.resourcePathString)) {
8599                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8600                                    "Application package " + pkg.packageName
8601                                    + " found at " + pkg.applicationInfo.getCodePath()
8602                                    + " but expected at " + known.codePathString
8603                                    + "; ignoring.");
8604                        }
8605                    }
8606                }
8607            }
8608
8609            // Verify that this new package doesn't have any content providers
8610            // that conflict with existing packages.  Only do this if the
8611            // package isn't already installed, since we don't want to break
8612            // things that are installed.
8613            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8614                final int N = pkg.providers.size();
8615                int i;
8616                for (i=0; i<N; i++) {
8617                    PackageParser.Provider p = pkg.providers.get(i);
8618                    if (p.info.authority != null) {
8619                        String names[] = p.info.authority.split(";");
8620                        for (int j = 0; j < names.length; j++) {
8621                            if (mProvidersByAuthority.containsKey(names[j])) {
8622                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8623                                final String otherPackageName =
8624                                        ((other != null && other.getComponentName() != null) ?
8625                                                other.getComponentName().getPackageName() : "?");
8626                                throw new PackageManagerException(
8627                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8628                                        "Can't install because provider name " + names[j]
8629                                                + " (in package " + pkg.applicationInfo.packageName
8630                                                + ") is already used by " + otherPackageName);
8631                            }
8632                        }
8633                    }
8634                }
8635            }
8636        }
8637    }
8638
8639    /**
8640     * Adds a scanned package to the system. When this method is finished, the package will
8641     * be available for query, resolution, etc...
8642     */
8643    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8644            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8645        final String pkgName = pkg.packageName;
8646        if (mCustomResolverComponentName != null &&
8647                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8648            setUpCustomResolverActivity(pkg);
8649        }
8650
8651        if (pkg.packageName.equals("android")) {
8652            synchronized (mPackages) {
8653                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8654                    // Set up information for our fall-back user intent resolution activity.
8655                    mPlatformPackage = pkg;
8656                    pkg.mVersionCode = mSdkVersion;
8657                    mAndroidApplication = pkg.applicationInfo;
8658
8659                    if (!mResolverReplaced) {
8660                        mResolveActivity.applicationInfo = mAndroidApplication;
8661                        mResolveActivity.name = ResolverActivity.class.getName();
8662                        mResolveActivity.packageName = mAndroidApplication.packageName;
8663                        mResolveActivity.processName = "system:ui";
8664                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8665                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8666                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8667                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8668                        mResolveActivity.exported = true;
8669                        mResolveActivity.enabled = true;
8670                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8671                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8672                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8673                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8674                                | ActivityInfo.CONFIG_ORIENTATION
8675                                | ActivityInfo.CONFIG_KEYBOARD
8676                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8677                        mResolveInfo.activityInfo = mResolveActivity;
8678                        mResolveInfo.priority = 0;
8679                        mResolveInfo.preferredOrder = 0;
8680                        mResolveInfo.match = 0;
8681                        mResolveComponentName = new ComponentName(
8682                                mAndroidApplication.packageName, mResolveActivity.name);
8683                    }
8684                }
8685            }
8686        }
8687
8688        ArrayList<PackageParser.Package> clientLibPkgs = null;
8689        // writer
8690        synchronized (mPackages) {
8691            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8692                // Only system apps can add new shared libraries.
8693                if (pkg.libraryNames != null) {
8694                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8695                        String name = pkg.libraryNames.get(i);
8696                        boolean allowed = false;
8697                        if (pkg.isUpdatedSystemApp()) {
8698                            // New library entries can only be added through the
8699                            // system image.  This is important to get rid of a lot
8700                            // of nasty edge cases: for example if we allowed a non-
8701                            // system update of the app to add a library, then uninstalling
8702                            // the update would make the library go away, and assumptions
8703                            // we made such as through app install filtering would now
8704                            // have allowed apps on the device which aren't compatible
8705                            // with it.  Better to just have the restriction here, be
8706                            // conservative, and create many fewer cases that can negatively
8707                            // impact the user experience.
8708                            final PackageSetting sysPs = mSettings
8709                                    .getDisabledSystemPkgLPr(pkg.packageName);
8710                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8711                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8712                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8713                                        allowed = true;
8714                                        break;
8715                                    }
8716                                }
8717                            }
8718                        } else {
8719                            allowed = true;
8720                        }
8721                        if (allowed) {
8722                            if (!mSharedLibraries.containsKey(name)) {
8723                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8724                            } else if (!name.equals(pkg.packageName)) {
8725                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8726                                        + name + " already exists; skipping");
8727                            }
8728                        } else {
8729                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8730                                    + name + " that is not declared on system image; skipping");
8731                        }
8732                    }
8733                    if ((scanFlags & SCAN_BOOTING) == 0) {
8734                        // If we are not booting, we need to update any applications
8735                        // that are clients of our shared library.  If we are booting,
8736                        // this will all be done once the scan is complete.
8737                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8738                    }
8739                }
8740            }
8741        }
8742
8743        if ((scanFlags & SCAN_BOOTING) != 0) {
8744            // No apps can run during boot scan, so they don't need to be frozen
8745        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8746            // Caller asked to not kill app, so it's probably not frozen
8747        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8748            // Caller asked us to ignore frozen check for some reason; they
8749            // probably didn't know the package name
8750        } else {
8751            // We're doing major surgery on this package, so it better be frozen
8752            // right now to keep it from launching
8753            checkPackageFrozen(pkgName);
8754        }
8755
8756        // Also need to kill any apps that are dependent on the library.
8757        if (clientLibPkgs != null) {
8758            for (int i=0; i<clientLibPkgs.size(); i++) {
8759                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8760                killApplication(clientPkg.applicationInfo.packageName,
8761                        clientPkg.applicationInfo.uid, "update lib");
8762            }
8763        }
8764
8765        // writer
8766        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8767
8768        boolean createIdmapFailed = false;
8769        synchronized (mPackages) {
8770            // We don't expect installation to fail beyond this point
8771
8772            if (pkgSetting.pkg != null) {
8773                // Note that |user| might be null during the initial boot scan. If a codePath
8774                // for an app has changed during a boot scan, it's due to an app update that's
8775                // part of the system partition and marker changes must be applied to all users.
8776                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8777                final int[] userIds = resolveUserIds(userId);
8778                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8779            }
8780
8781            // Add the new setting to mSettings
8782            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8783            // Add the new setting to mPackages
8784            mPackages.put(pkg.applicationInfo.packageName, pkg);
8785            // Make sure we don't accidentally delete its data.
8786            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8787            while (iter.hasNext()) {
8788                PackageCleanItem item = iter.next();
8789                if (pkgName.equals(item.packageName)) {
8790                    iter.remove();
8791                }
8792            }
8793
8794            // Add the package's KeySets to the global KeySetManagerService
8795            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8796            ksms.addScannedPackageLPw(pkg);
8797
8798            int N = pkg.providers.size();
8799            StringBuilder r = null;
8800            int i;
8801            for (i=0; i<N; i++) {
8802                PackageParser.Provider p = pkg.providers.get(i);
8803                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8804                        p.info.processName);
8805                mProviders.addProvider(p);
8806                p.syncable = p.info.isSyncable;
8807                if (p.info.authority != null) {
8808                    String names[] = p.info.authority.split(";");
8809                    p.info.authority = null;
8810                    for (int j = 0; j < names.length; j++) {
8811                        if (j == 1 && p.syncable) {
8812                            // We only want the first authority for a provider to possibly be
8813                            // syncable, so if we already added this provider using a different
8814                            // authority clear the syncable flag. We copy the provider before
8815                            // changing it because the mProviders object contains a reference
8816                            // to a provider that we don't want to change.
8817                            // Only do this for the second authority since the resulting provider
8818                            // object can be the same for all future authorities for this provider.
8819                            p = new PackageParser.Provider(p);
8820                            p.syncable = false;
8821                        }
8822                        if (!mProvidersByAuthority.containsKey(names[j])) {
8823                            mProvidersByAuthority.put(names[j], p);
8824                            if (p.info.authority == null) {
8825                                p.info.authority = names[j];
8826                            } else {
8827                                p.info.authority = p.info.authority + ";" + names[j];
8828                            }
8829                            if (DEBUG_PACKAGE_SCANNING) {
8830                                if (chatty)
8831                                    Log.d(TAG, "Registered content provider: " + names[j]
8832                                            + ", className = " + p.info.name + ", isSyncable = "
8833                                            + p.info.isSyncable);
8834                            }
8835                        } else {
8836                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8837                            Slog.w(TAG, "Skipping provider name " + names[j] +
8838                                    " (in package " + pkg.applicationInfo.packageName +
8839                                    "): name already used by "
8840                                    + ((other != null && other.getComponentName() != null)
8841                                            ? other.getComponentName().getPackageName() : "?"));
8842                        }
8843                    }
8844                }
8845                if (chatty) {
8846                    if (r == null) {
8847                        r = new StringBuilder(256);
8848                    } else {
8849                        r.append(' ');
8850                    }
8851                    r.append(p.info.name);
8852                }
8853            }
8854            if (r != null) {
8855                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8856            }
8857
8858            N = pkg.services.size();
8859            r = null;
8860            for (i=0; i<N; i++) {
8861                PackageParser.Service s = pkg.services.get(i);
8862                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8863                        s.info.processName);
8864                mServices.addService(s);
8865                if (chatty) {
8866                    if (r == null) {
8867                        r = new StringBuilder(256);
8868                    } else {
8869                        r.append(' ');
8870                    }
8871                    r.append(s.info.name);
8872                }
8873            }
8874            if (r != null) {
8875                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8876            }
8877
8878            N = pkg.receivers.size();
8879            r = null;
8880            for (i=0; i<N; i++) {
8881                PackageParser.Activity a = pkg.receivers.get(i);
8882                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8883                        a.info.processName);
8884                mReceivers.addActivity(a, "receiver");
8885                if (chatty) {
8886                    if (r == null) {
8887                        r = new StringBuilder(256);
8888                    } else {
8889                        r.append(' ');
8890                    }
8891                    r.append(a.info.name);
8892                }
8893            }
8894            if (r != null) {
8895                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8896            }
8897
8898            N = pkg.activities.size();
8899            r = null;
8900            for (i=0; i<N; i++) {
8901                PackageParser.Activity a = pkg.activities.get(i);
8902                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8903                        a.info.processName);
8904                mActivities.addActivity(a, "activity");
8905                if (chatty) {
8906                    if (r == null) {
8907                        r = new StringBuilder(256);
8908                    } else {
8909                        r.append(' ');
8910                    }
8911                    r.append(a.info.name);
8912                }
8913            }
8914            if (r != null) {
8915                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8916            }
8917
8918            N = pkg.permissionGroups.size();
8919            r = null;
8920            for (i=0; i<N; i++) {
8921                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8922                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8923                final String curPackageName = cur == null ? null : cur.info.packageName;
8924                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8925                if (cur == null || isPackageUpdate) {
8926                    mPermissionGroups.put(pg.info.name, pg);
8927                    if (chatty) {
8928                        if (r == null) {
8929                            r = new StringBuilder(256);
8930                        } else {
8931                            r.append(' ');
8932                        }
8933                        if (isPackageUpdate) {
8934                            r.append("UPD:");
8935                        }
8936                        r.append(pg.info.name);
8937                    }
8938                } else {
8939                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8940                            + pg.info.packageName + " ignored: original from "
8941                            + cur.info.packageName);
8942                    if (chatty) {
8943                        if (r == null) {
8944                            r = new StringBuilder(256);
8945                        } else {
8946                            r.append(' ');
8947                        }
8948                        r.append("DUP:");
8949                        r.append(pg.info.name);
8950                    }
8951                }
8952            }
8953            if (r != null) {
8954                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8955            }
8956
8957            N = pkg.permissions.size();
8958            r = null;
8959            for (i=0; i<N; i++) {
8960                PackageParser.Permission p = pkg.permissions.get(i);
8961
8962                // Assume by default that we did not install this permission into the system.
8963                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8964
8965                // Now that permission groups have a special meaning, we ignore permission
8966                // groups for legacy apps to prevent unexpected behavior. In particular,
8967                // permissions for one app being granted to someone just becase they happen
8968                // to be in a group defined by another app (before this had no implications).
8969                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8970                    p.group = mPermissionGroups.get(p.info.group);
8971                    // Warn for a permission in an unknown group.
8972                    if (p.info.group != null && p.group == null) {
8973                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8974                                + p.info.packageName + " in an unknown group " + p.info.group);
8975                    }
8976                }
8977
8978                ArrayMap<String, BasePermission> permissionMap =
8979                        p.tree ? mSettings.mPermissionTrees
8980                                : mSettings.mPermissions;
8981                BasePermission bp = permissionMap.get(p.info.name);
8982
8983                // Allow system apps to redefine non-system permissions
8984                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8985                    final boolean currentOwnerIsSystem = (bp.perm != null
8986                            && isSystemApp(bp.perm.owner));
8987                    if (isSystemApp(p.owner)) {
8988                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8989                            // It's a built-in permission and no owner, take ownership now
8990                            bp.packageSetting = pkgSetting;
8991                            bp.perm = p;
8992                            bp.uid = pkg.applicationInfo.uid;
8993                            bp.sourcePackage = p.info.packageName;
8994                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8995                        } else if (!currentOwnerIsSystem) {
8996                            String msg = "New decl " + p.owner + " of permission  "
8997                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8998                            reportSettingsProblem(Log.WARN, msg);
8999                            bp = null;
9000                        }
9001                    }
9002                }
9003
9004                if (bp == null) {
9005                    bp = new BasePermission(p.info.name, p.info.packageName,
9006                            BasePermission.TYPE_NORMAL);
9007                    permissionMap.put(p.info.name, bp);
9008                }
9009
9010                if (bp.perm == null) {
9011                    if (bp.sourcePackage == null
9012                            || bp.sourcePackage.equals(p.info.packageName)) {
9013                        BasePermission tree = findPermissionTreeLP(p.info.name);
9014                        if (tree == null
9015                                || tree.sourcePackage.equals(p.info.packageName)) {
9016                            bp.packageSetting = pkgSetting;
9017                            bp.perm = p;
9018                            bp.uid = pkg.applicationInfo.uid;
9019                            bp.sourcePackage = p.info.packageName;
9020                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9021                            if (chatty) {
9022                                if (r == null) {
9023                                    r = new StringBuilder(256);
9024                                } else {
9025                                    r.append(' ');
9026                                }
9027                                r.append(p.info.name);
9028                            }
9029                        } else {
9030                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9031                                    + p.info.packageName + " ignored: base tree "
9032                                    + tree.name + " is from package "
9033                                    + tree.sourcePackage);
9034                        }
9035                    } else {
9036                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9037                                + p.info.packageName + " ignored: original from "
9038                                + bp.sourcePackage);
9039                    }
9040                } else if (chatty) {
9041                    if (r == null) {
9042                        r = new StringBuilder(256);
9043                    } else {
9044                        r.append(' ');
9045                    }
9046                    r.append("DUP:");
9047                    r.append(p.info.name);
9048                }
9049                if (bp.perm == p) {
9050                    bp.protectionLevel = p.info.protectionLevel;
9051                }
9052            }
9053
9054            if (r != null) {
9055                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9056            }
9057
9058            N = pkg.instrumentation.size();
9059            r = null;
9060            for (i=0; i<N; i++) {
9061                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9062                a.info.packageName = pkg.applicationInfo.packageName;
9063                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9064                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9065                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9066                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9067                a.info.dataDir = pkg.applicationInfo.dataDir;
9068                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9069                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9070                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9071                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9072                mInstrumentation.put(a.getComponentName(), a);
9073                if (chatty) {
9074                    if (r == null) {
9075                        r = new StringBuilder(256);
9076                    } else {
9077                        r.append(' ');
9078                    }
9079                    r.append(a.info.name);
9080                }
9081            }
9082            if (r != null) {
9083                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9084            }
9085
9086            if (pkg.protectedBroadcasts != null) {
9087                N = pkg.protectedBroadcasts.size();
9088                for (i=0; i<N; i++) {
9089                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9090                }
9091            }
9092
9093            // Create idmap files for pairs of (packages, overlay packages).
9094            // Note: "android", ie framework-res.apk, is handled by native layers.
9095            if (pkg.mOverlayTarget != null) {
9096                // This is an overlay package.
9097                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9098                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9099                        mOverlays.put(pkg.mOverlayTarget,
9100                                new ArrayMap<String, PackageParser.Package>());
9101                    }
9102                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9103                    map.put(pkg.packageName, pkg);
9104                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9105                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9106                        createIdmapFailed = true;
9107                    }
9108                }
9109            } else if (mOverlays.containsKey(pkg.packageName) &&
9110                    !pkg.packageName.equals("android")) {
9111                // This is a regular package, with one or more known overlay packages.
9112                createIdmapsForPackageLI(pkg);
9113            }
9114        }
9115
9116        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9117
9118        if (createIdmapFailed) {
9119            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9120                    "scanPackageLI failed to createIdmap");
9121        }
9122    }
9123
9124    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9125            PackageParser.Package update, int[] userIds) {
9126        if (existing.applicationInfo == null || update.applicationInfo == null) {
9127            // This isn't due to an app installation.
9128            return;
9129        }
9130
9131        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9132        final File newCodePath = new File(update.applicationInfo.getCodePath());
9133
9134        // The codePath hasn't changed, so there's nothing for us to do.
9135        if (Objects.equals(oldCodePath, newCodePath)) {
9136            return;
9137        }
9138
9139        File canonicalNewCodePath;
9140        try {
9141            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9142        } catch (IOException e) {
9143            Slog.w(TAG, "Failed to get canonical path.", e);
9144            return;
9145        }
9146
9147        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9148        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9149        // that the last component of the path (i.e, the name) doesn't need canonicalization
9150        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9151        // but may change in the future. Hopefully this function won't exist at that point.
9152        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9153                oldCodePath.getName());
9154
9155        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9156        // with "@".
9157        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9158        if (!oldMarkerPrefix.endsWith("@")) {
9159            oldMarkerPrefix += "@";
9160        }
9161        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9162        if (!newMarkerPrefix.endsWith("@")) {
9163            newMarkerPrefix += "@";
9164        }
9165
9166        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9167        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9168        for (String updatedPath : updatedPaths) {
9169            String updatedPathName = new File(updatedPath).getName();
9170            markerSuffixes.add(updatedPathName.replace('/', '@'));
9171        }
9172
9173        for (int userId : userIds) {
9174            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9175
9176            for (String markerSuffix : markerSuffixes) {
9177                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9178                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9179                if (oldForeignUseMark.exists()) {
9180                    try {
9181                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9182                                newForeignUseMark.getAbsolutePath());
9183                    } catch (ErrnoException e) {
9184                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9185                        oldForeignUseMark.delete();
9186                    }
9187                }
9188            }
9189        }
9190    }
9191
9192    /**
9193     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9194     * is derived purely on the basis of the contents of {@code scanFile} and
9195     * {@code cpuAbiOverride}.
9196     *
9197     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9198     */
9199    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9200                                 String cpuAbiOverride, boolean extractLibs,
9201                                 File appLib32InstallDir)
9202            throws PackageManagerException {
9203        // TODO: We can probably be smarter about this stuff. For installed apps,
9204        // we can calculate this information at install time once and for all. For
9205        // system apps, we can probably assume that this information doesn't change
9206        // after the first boot scan. As things stand, we do lots of unnecessary work.
9207
9208        // Give ourselves some initial paths; we'll come back for another
9209        // pass once we've determined ABI below.
9210        setNativeLibraryPaths(pkg, appLib32InstallDir);
9211
9212        // We would never need to extract libs for forward-locked and external packages,
9213        // since the container service will do it for us. We shouldn't attempt to
9214        // extract libs from system app when it was not updated.
9215        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9216                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9217            extractLibs = false;
9218        }
9219
9220        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9221        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9222
9223        NativeLibraryHelper.Handle handle = null;
9224        try {
9225            handle = NativeLibraryHelper.Handle.create(pkg);
9226            // TODO(multiArch): This can be null for apps that didn't go through the
9227            // usual installation process. We can calculate it again, like we
9228            // do during install time.
9229            //
9230            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9231            // unnecessary.
9232            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9233
9234            // Null out the abis so that they can be recalculated.
9235            pkg.applicationInfo.primaryCpuAbi = null;
9236            pkg.applicationInfo.secondaryCpuAbi = null;
9237            if (isMultiArch(pkg.applicationInfo)) {
9238                // Warn if we've set an abiOverride for multi-lib packages..
9239                // By definition, we need to copy both 32 and 64 bit libraries for
9240                // such packages.
9241                if (pkg.cpuAbiOverride != null
9242                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9243                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9244                }
9245
9246                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9247                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9248                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9249                    if (extractLibs) {
9250                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9251                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9252                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9253                                useIsaSpecificSubdirs);
9254                    } else {
9255                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9256                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9257                    }
9258                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9259                }
9260
9261                maybeThrowExceptionForMultiArchCopy(
9262                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9263
9264                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9265                    if (extractLibs) {
9266                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9267                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9268                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9269                                useIsaSpecificSubdirs);
9270                    } else {
9271                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9272                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9273                    }
9274                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9275                }
9276
9277                maybeThrowExceptionForMultiArchCopy(
9278                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9279
9280                if (abi64 >= 0) {
9281                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9282                }
9283
9284                if (abi32 >= 0) {
9285                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9286                    if (abi64 >= 0) {
9287                        if (pkg.use32bitAbi) {
9288                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9289                            pkg.applicationInfo.primaryCpuAbi = abi;
9290                        } else {
9291                            pkg.applicationInfo.secondaryCpuAbi = abi;
9292                        }
9293                    } else {
9294                        pkg.applicationInfo.primaryCpuAbi = abi;
9295                    }
9296                }
9297
9298            } else {
9299                String[] abiList = (cpuAbiOverride != null) ?
9300                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9301
9302                // Enable gross and lame hacks for apps that are built with old
9303                // SDK tools. We must scan their APKs for renderscript bitcode and
9304                // not launch them if it's present. Don't bother checking on devices
9305                // that don't have 64 bit support.
9306                boolean needsRenderScriptOverride = false;
9307                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9308                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9309                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9310                    needsRenderScriptOverride = true;
9311                }
9312
9313                final int copyRet;
9314                if (extractLibs) {
9315                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9316                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9317                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9318                } else {
9319                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9320                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9321                }
9322                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9323
9324                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9325                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9326                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9327                }
9328
9329                if (copyRet >= 0) {
9330                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9331                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9332                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9333                } else if (needsRenderScriptOverride) {
9334                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9335                }
9336            }
9337        } catch (IOException ioe) {
9338            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9339        } finally {
9340            IoUtils.closeQuietly(handle);
9341        }
9342
9343        // Now that we've calculated the ABIs and determined if it's an internal app,
9344        // we will go ahead and populate the nativeLibraryPath.
9345        setNativeLibraryPaths(pkg, appLib32InstallDir);
9346    }
9347
9348    /**
9349     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9350     * i.e, so that all packages can be run inside a single process if required.
9351     *
9352     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9353     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9354     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9355     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9356     * updating a package that belongs to a shared user.
9357     *
9358     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9359     * adds unnecessary complexity.
9360     */
9361    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9362            PackageParser.Package scannedPackage) {
9363        String requiredInstructionSet = null;
9364        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9365            requiredInstructionSet = VMRuntime.getInstructionSet(
9366                     scannedPackage.applicationInfo.primaryCpuAbi);
9367        }
9368
9369        PackageSetting requirer = null;
9370        for (PackageSetting ps : packagesForUser) {
9371            // If packagesForUser contains scannedPackage, we skip it. This will happen
9372            // when scannedPackage is an update of an existing package. Without this check,
9373            // we will never be able to change the ABI of any package belonging to a shared
9374            // user, even if it's compatible with other packages.
9375            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9376                if (ps.primaryCpuAbiString == null) {
9377                    continue;
9378                }
9379
9380                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9381                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9382                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9383                    // this but there's not much we can do.
9384                    String errorMessage = "Instruction set mismatch, "
9385                            + ((requirer == null) ? "[caller]" : requirer)
9386                            + " requires " + requiredInstructionSet + " whereas " + ps
9387                            + " requires " + instructionSet;
9388                    Slog.w(TAG, errorMessage);
9389                }
9390
9391                if (requiredInstructionSet == null) {
9392                    requiredInstructionSet = instructionSet;
9393                    requirer = ps;
9394                }
9395            }
9396        }
9397
9398        if (requiredInstructionSet != null) {
9399            String adjustedAbi;
9400            if (requirer != null) {
9401                // requirer != null implies that either scannedPackage was null or that scannedPackage
9402                // did not require an ABI, in which case we have to adjust scannedPackage to match
9403                // the ABI of the set (which is the same as requirer's ABI)
9404                adjustedAbi = requirer.primaryCpuAbiString;
9405                if (scannedPackage != null) {
9406                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9407                }
9408            } else {
9409                // requirer == null implies that we're updating all ABIs in the set to
9410                // match scannedPackage.
9411                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9412            }
9413
9414            for (PackageSetting ps : packagesForUser) {
9415                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9416                    if (ps.primaryCpuAbiString != null) {
9417                        continue;
9418                    }
9419
9420                    ps.primaryCpuAbiString = adjustedAbi;
9421                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9422                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9423                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9424                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9425                                + " (requirer="
9426                                + (requirer == null ? "null" : requirer.pkg.packageName)
9427                                + ", scannedPackage="
9428                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9429                                + ")");
9430                        try {
9431                            mInstaller.rmdex(ps.codePathString,
9432                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9433                        } catch (InstallerException ignored) {
9434                        }
9435                    }
9436                }
9437            }
9438        }
9439    }
9440
9441    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9442        synchronized (mPackages) {
9443            mResolverReplaced = true;
9444            // Set up information for custom user intent resolution activity.
9445            mResolveActivity.applicationInfo = pkg.applicationInfo;
9446            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9447            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9448            mResolveActivity.processName = pkg.applicationInfo.packageName;
9449            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9450            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9451                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9452            mResolveActivity.theme = 0;
9453            mResolveActivity.exported = true;
9454            mResolveActivity.enabled = true;
9455            mResolveInfo.activityInfo = mResolveActivity;
9456            mResolveInfo.priority = 0;
9457            mResolveInfo.preferredOrder = 0;
9458            mResolveInfo.match = 0;
9459            mResolveComponentName = mCustomResolverComponentName;
9460            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9461                    mResolveComponentName);
9462        }
9463    }
9464
9465    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9466        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9467
9468        // Set up information for ephemeral installer activity
9469        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9470        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9471        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9472        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9473        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9474        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9475                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9476        mEphemeralInstallerActivity.theme = 0;
9477        mEphemeralInstallerActivity.exported = true;
9478        mEphemeralInstallerActivity.enabled = true;
9479        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9480        mEphemeralInstallerInfo.priority = 0;
9481        mEphemeralInstallerInfo.preferredOrder = 1;
9482        mEphemeralInstallerInfo.isDefault = true;
9483        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9484                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9485
9486        if (DEBUG_EPHEMERAL) {
9487            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9488        }
9489    }
9490
9491    private static String calculateBundledApkRoot(final String codePathString) {
9492        final File codePath = new File(codePathString);
9493        final File codeRoot;
9494        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9495            codeRoot = Environment.getRootDirectory();
9496        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9497            codeRoot = Environment.getOemDirectory();
9498        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9499            codeRoot = Environment.getVendorDirectory();
9500        } else {
9501            // Unrecognized code path; take its top real segment as the apk root:
9502            // e.g. /something/app/blah.apk => /something
9503            try {
9504                File f = codePath.getCanonicalFile();
9505                File parent = f.getParentFile();    // non-null because codePath is a file
9506                File tmp;
9507                while ((tmp = parent.getParentFile()) != null) {
9508                    f = parent;
9509                    parent = tmp;
9510                }
9511                codeRoot = f;
9512                Slog.w(TAG, "Unrecognized code path "
9513                        + codePath + " - using " + codeRoot);
9514            } catch (IOException e) {
9515                // Can't canonicalize the code path -- shenanigans?
9516                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9517                return Environment.getRootDirectory().getPath();
9518            }
9519        }
9520        return codeRoot.getPath();
9521    }
9522
9523    /**
9524     * Derive and set the location of native libraries for the given package,
9525     * which varies depending on where and how the package was installed.
9526     */
9527    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9528        final ApplicationInfo info = pkg.applicationInfo;
9529        final String codePath = pkg.codePath;
9530        final File codeFile = new File(codePath);
9531        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9532        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9533
9534        info.nativeLibraryRootDir = null;
9535        info.nativeLibraryRootRequiresIsa = false;
9536        info.nativeLibraryDir = null;
9537        info.secondaryNativeLibraryDir = null;
9538
9539        if (isApkFile(codeFile)) {
9540            // Monolithic install
9541            if (bundledApp) {
9542                // If "/system/lib64/apkname" exists, assume that is the per-package
9543                // native library directory to use; otherwise use "/system/lib/apkname".
9544                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9545                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9546                        getPrimaryInstructionSet(info));
9547
9548                // This is a bundled system app so choose the path based on the ABI.
9549                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9550                // is just the default path.
9551                final String apkName = deriveCodePathName(codePath);
9552                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9553                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9554                        apkName).getAbsolutePath();
9555
9556                if (info.secondaryCpuAbi != null) {
9557                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9558                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9559                            secondaryLibDir, apkName).getAbsolutePath();
9560                }
9561            } else if (asecApp) {
9562                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9563                        .getAbsolutePath();
9564            } else {
9565                final String apkName = deriveCodePathName(codePath);
9566                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9567                        .getAbsolutePath();
9568            }
9569
9570            info.nativeLibraryRootRequiresIsa = false;
9571            info.nativeLibraryDir = info.nativeLibraryRootDir;
9572        } else {
9573            // Cluster install
9574            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9575            info.nativeLibraryRootRequiresIsa = true;
9576
9577            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9578                    getPrimaryInstructionSet(info)).getAbsolutePath();
9579
9580            if (info.secondaryCpuAbi != null) {
9581                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9582                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9583            }
9584        }
9585    }
9586
9587    /**
9588     * Calculate the abis and roots for a bundled app. These can uniquely
9589     * be determined from the contents of the system partition, i.e whether
9590     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9591     * of this information, and instead assume that the system was built
9592     * sensibly.
9593     */
9594    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9595                                           PackageSetting pkgSetting) {
9596        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9597
9598        // If "/system/lib64/apkname" exists, assume that is the per-package
9599        // native library directory to use; otherwise use "/system/lib/apkname".
9600        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9601        setBundledAppAbi(pkg, apkRoot, apkName);
9602        // pkgSetting might be null during rescan following uninstall of updates
9603        // to a bundled app, so accommodate that possibility.  The settings in
9604        // that case will be established later from the parsed package.
9605        //
9606        // If the settings aren't null, sync them up with what we've just derived.
9607        // note that apkRoot isn't stored in the package settings.
9608        if (pkgSetting != null) {
9609            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9610            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9611        }
9612    }
9613
9614    /**
9615     * Deduces the ABI of a bundled app and sets the relevant fields on the
9616     * parsed pkg object.
9617     *
9618     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9619     *        under which system libraries are installed.
9620     * @param apkName the name of the installed package.
9621     */
9622    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9623        final File codeFile = new File(pkg.codePath);
9624
9625        final boolean has64BitLibs;
9626        final boolean has32BitLibs;
9627        if (isApkFile(codeFile)) {
9628            // Monolithic install
9629            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9630            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9631        } else {
9632            // Cluster install
9633            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9634            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9635                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9636                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9637                has64BitLibs = (new File(rootDir, isa)).exists();
9638            } else {
9639                has64BitLibs = false;
9640            }
9641            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9642                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9643                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9644                has32BitLibs = (new File(rootDir, isa)).exists();
9645            } else {
9646                has32BitLibs = false;
9647            }
9648        }
9649
9650        if (has64BitLibs && !has32BitLibs) {
9651            // The package has 64 bit libs, but not 32 bit libs. Its primary
9652            // ABI should be 64 bit. We can safely assume here that the bundled
9653            // native libraries correspond to the most preferred ABI in the list.
9654
9655            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9656            pkg.applicationInfo.secondaryCpuAbi = null;
9657        } else if (has32BitLibs && !has64BitLibs) {
9658            // The package has 32 bit libs but not 64 bit libs. Its primary
9659            // ABI should be 32 bit.
9660
9661            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9662            pkg.applicationInfo.secondaryCpuAbi = null;
9663        } else if (has32BitLibs && has64BitLibs) {
9664            // The application has both 64 and 32 bit bundled libraries. We check
9665            // here that the app declares multiArch support, and warn if it doesn't.
9666            //
9667            // We will be lenient here and record both ABIs. The primary will be the
9668            // ABI that's higher on the list, i.e, a device that's configured to prefer
9669            // 64 bit apps will see a 64 bit primary ABI,
9670
9671            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9672                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9673            }
9674
9675            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9676                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9677                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9678            } else {
9679                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9680                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9681            }
9682        } else {
9683            pkg.applicationInfo.primaryCpuAbi = null;
9684            pkg.applicationInfo.secondaryCpuAbi = null;
9685        }
9686    }
9687
9688    private void killApplication(String pkgName, int appId, String reason) {
9689        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9690    }
9691
9692    private void killApplication(String pkgName, int appId, int userId, String reason) {
9693        // Request the ActivityManager to kill the process(only for existing packages)
9694        // so that we do not end up in a confused state while the user is still using the older
9695        // version of the application while the new one gets installed.
9696        final long token = Binder.clearCallingIdentity();
9697        try {
9698            IActivityManager am = ActivityManager.getService();
9699            if (am != null) {
9700                try {
9701                    am.killApplication(pkgName, appId, userId, reason);
9702                } catch (RemoteException e) {
9703                }
9704            }
9705        } finally {
9706            Binder.restoreCallingIdentity(token);
9707        }
9708    }
9709
9710    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9711        // Remove the parent package setting
9712        PackageSetting ps = (PackageSetting) pkg.mExtras;
9713        if (ps != null) {
9714            removePackageLI(ps, chatty);
9715        }
9716        // Remove the child package setting
9717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9718        for (int i = 0; i < childCount; i++) {
9719            PackageParser.Package childPkg = pkg.childPackages.get(i);
9720            ps = (PackageSetting) childPkg.mExtras;
9721            if (ps != null) {
9722                removePackageLI(ps, chatty);
9723            }
9724        }
9725    }
9726
9727    void removePackageLI(PackageSetting ps, boolean chatty) {
9728        if (DEBUG_INSTALL) {
9729            if (chatty)
9730                Log.d(TAG, "Removing package " + ps.name);
9731        }
9732
9733        // writer
9734        synchronized (mPackages) {
9735            mPackages.remove(ps.name);
9736            final PackageParser.Package pkg = ps.pkg;
9737            if (pkg != null) {
9738                cleanPackageDataStructuresLILPw(pkg, chatty);
9739            }
9740        }
9741    }
9742
9743    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9744        if (DEBUG_INSTALL) {
9745            if (chatty)
9746                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9747        }
9748
9749        // writer
9750        synchronized (mPackages) {
9751            // Remove the parent package
9752            mPackages.remove(pkg.applicationInfo.packageName);
9753            cleanPackageDataStructuresLILPw(pkg, chatty);
9754
9755            // Remove the child packages
9756            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9757            for (int i = 0; i < childCount; i++) {
9758                PackageParser.Package childPkg = pkg.childPackages.get(i);
9759                mPackages.remove(childPkg.applicationInfo.packageName);
9760                cleanPackageDataStructuresLILPw(childPkg, chatty);
9761            }
9762        }
9763    }
9764
9765    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9766        int N = pkg.providers.size();
9767        StringBuilder r = null;
9768        int i;
9769        for (i=0; i<N; i++) {
9770            PackageParser.Provider p = pkg.providers.get(i);
9771            mProviders.removeProvider(p);
9772            if (p.info.authority == null) {
9773
9774                /* There was another ContentProvider with this authority when
9775                 * this app was installed so this authority is null,
9776                 * Ignore it as we don't have to unregister the provider.
9777                 */
9778                continue;
9779            }
9780            String names[] = p.info.authority.split(";");
9781            for (int j = 0; j < names.length; j++) {
9782                if (mProvidersByAuthority.get(names[j]) == p) {
9783                    mProvidersByAuthority.remove(names[j]);
9784                    if (DEBUG_REMOVE) {
9785                        if (chatty)
9786                            Log.d(TAG, "Unregistered content provider: " + names[j]
9787                                    + ", className = " + p.info.name + ", isSyncable = "
9788                                    + p.info.isSyncable);
9789                    }
9790                }
9791            }
9792            if (DEBUG_REMOVE && chatty) {
9793                if (r == null) {
9794                    r = new StringBuilder(256);
9795                } else {
9796                    r.append(' ');
9797                }
9798                r.append(p.info.name);
9799            }
9800        }
9801        if (r != null) {
9802            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9803        }
9804
9805        N = pkg.services.size();
9806        r = null;
9807        for (i=0; i<N; i++) {
9808            PackageParser.Service s = pkg.services.get(i);
9809            mServices.removeService(s);
9810            if (chatty) {
9811                if (r == null) {
9812                    r = new StringBuilder(256);
9813                } else {
9814                    r.append(' ');
9815                }
9816                r.append(s.info.name);
9817            }
9818        }
9819        if (r != null) {
9820            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9821        }
9822
9823        N = pkg.receivers.size();
9824        r = null;
9825        for (i=0; i<N; i++) {
9826            PackageParser.Activity a = pkg.receivers.get(i);
9827            mReceivers.removeActivity(a, "receiver");
9828            if (DEBUG_REMOVE && chatty) {
9829                if (r == null) {
9830                    r = new StringBuilder(256);
9831                } else {
9832                    r.append(' ');
9833                }
9834                r.append(a.info.name);
9835            }
9836        }
9837        if (r != null) {
9838            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9839        }
9840
9841        N = pkg.activities.size();
9842        r = null;
9843        for (i=0; i<N; i++) {
9844            PackageParser.Activity a = pkg.activities.get(i);
9845            mActivities.removeActivity(a, "activity");
9846            if (DEBUG_REMOVE && chatty) {
9847                if (r == null) {
9848                    r = new StringBuilder(256);
9849                } else {
9850                    r.append(' ');
9851                }
9852                r.append(a.info.name);
9853            }
9854        }
9855        if (r != null) {
9856            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9857        }
9858
9859        N = pkg.permissions.size();
9860        r = null;
9861        for (i=0; i<N; i++) {
9862            PackageParser.Permission p = pkg.permissions.get(i);
9863            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9864            if (bp == null) {
9865                bp = mSettings.mPermissionTrees.get(p.info.name);
9866            }
9867            if (bp != null && bp.perm == p) {
9868                bp.perm = null;
9869                if (DEBUG_REMOVE && chatty) {
9870                    if (r == null) {
9871                        r = new StringBuilder(256);
9872                    } else {
9873                        r.append(' ');
9874                    }
9875                    r.append(p.info.name);
9876                }
9877            }
9878            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9879                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9880                if (appOpPkgs != null) {
9881                    appOpPkgs.remove(pkg.packageName);
9882                }
9883            }
9884        }
9885        if (r != null) {
9886            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9887        }
9888
9889        N = pkg.requestedPermissions.size();
9890        r = null;
9891        for (i=0; i<N; i++) {
9892            String perm = pkg.requestedPermissions.get(i);
9893            BasePermission bp = mSettings.mPermissions.get(perm);
9894            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9895                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9896                if (appOpPkgs != null) {
9897                    appOpPkgs.remove(pkg.packageName);
9898                    if (appOpPkgs.isEmpty()) {
9899                        mAppOpPermissionPackages.remove(perm);
9900                    }
9901                }
9902            }
9903        }
9904        if (r != null) {
9905            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9906        }
9907
9908        N = pkg.instrumentation.size();
9909        r = null;
9910        for (i=0; i<N; i++) {
9911            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9912            mInstrumentation.remove(a.getComponentName());
9913            if (DEBUG_REMOVE && chatty) {
9914                if (r == null) {
9915                    r = new StringBuilder(256);
9916                } else {
9917                    r.append(' ');
9918                }
9919                r.append(a.info.name);
9920            }
9921        }
9922        if (r != null) {
9923            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9924        }
9925
9926        r = null;
9927        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9928            // Only system apps can hold shared libraries.
9929            if (pkg.libraryNames != null) {
9930                for (i=0; i<pkg.libraryNames.size(); i++) {
9931                    String name = pkg.libraryNames.get(i);
9932                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9933                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9934                        mSharedLibraries.remove(name);
9935                        if (DEBUG_REMOVE && chatty) {
9936                            if (r == null) {
9937                                r = new StringBuilder(256);
9938                            } else {
9939                                r.append(' ');
9940                            }
9941                            r.append(name);
9942                        }
9943                    }
9944                }
9945            }
9946        }
9947        if (r != null) {
9948            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9949        }
9950    }
9951
9952    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9953        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9954            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9955                return true;
9956            }
9957        }
9958        return false;
9959    }
9960
9961    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9962    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9963    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9964
9965    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9966        // Update the parent permissions
9967        updatePermissionsLPw(pkg.packageName, pkg, flags);
9968        // Update the child permissions
9969        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9970        for (int i = 0; i < childCount; i++) {
9971            PackageParser.Package childPkg = pkg.childPackages.get(i);
9972            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9973        }
9974    }
9975
9976    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9977            int flags) {
9978        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9979        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9980    }
9981
9982    private void updatePermissionsLPw(String changingPkg,
9983            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9984        // Make sure there are no dangling permission trees.
9985        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9986        while (it.hasNext()) {
9987            final BasePermission bp = it.next();
9988            if (bp.packageSetting == null) {
9989                // We may not yet have parsed the package, so just see if
9990                // we still know about its settings.
9991                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9992            }
9993            if (bp.packageSetting == null) {
9994                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9995                        + " from package " + bp.sourcePackage);
9996                it.remove();
9997            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9998                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9999                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10000                            + " from package " + bp.sourcePackage);
10001                    flags |= UPDATE_PERMISSIONS_ALL;
10002                    it.remove();
10003                }
10004            }
10005        }
10006
10007        // Make sure all dynamic permissions have been assigned to a package,
10008        // and make sure there are no dangling permissions.
10009        it = mSettings.mPermissions.values().iterator();
10010        while (it.hasNext()) {
10011            final BasePermission bp = it.next();
10012            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10013                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10014                        + bp.name + " pkg=" + bp.sourcePackage
10015                        + " info=" + bp.pendingInfo);
10016                if (bp.packageSetting == null && bp.pendingInfo != null) {
10017                    final BasePermission tree = findPermissionTreeLP(bp.name);
10018                    if (tree != null && tree.perm != null) {
10019                        bp.packageSetting = tree.packageSetting;
10020                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10021                                new PermissionInfo(bp.pendingInfo));
10022                        bp.perm.info.packageName = tree.perm.info.packageName;
10023                        bp.perm.info.name = bp.name;
10024                        bp.uid = tree.uid;
10025                    }
10026                }
10027            }
10028            if (bp.packageSetting == null) {
10029                // We may not yet have parsed the package, so just see if
10030                // we still know about its settings.
10031                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10032            }
10033            if (bp.packageSetting == null) {
10034                Slog.w(TAG, "Removing dangling permission: " + bp.name
10035                        + " from package " + bp.sourcePackage);
10036                it.remove();
10037            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10038                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10039                    Slog.i(TAG, "Removing old permission: " + bp.name
10040                            + " from package " + bp.sourcePackage);
10041                    flags |= UPDATE_PERMISSIONS_ALL;
10042                    it.remove();
10043                }
10044            }
10045        }
10046
10047        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10048        // Now update the permissions for all packages, in particular
10049        // replace the granted permissions of the system packages.
10050        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10051            for (PackageParser.Package pkg : mPackages.values()) {
10052                if (pkg != pkgInfo) {
10053                    // Only replace for packages on requested volume
10054                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10055                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10056                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10057                    grantPermissionsLPw(pkg, replace, changingPkg);
10058                }
10059            }
10060        }
10061
10062        if (pkgInfo != null) {
10063            // Only replace for packages on requested volume
10064            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10065            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10066                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10067            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10068        }
10069        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10070    }
10071
10072    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10073            String packageOfInterest) {
10074        // IMPORTANT: There are two types of permissions: install and runtime.
10075        // Install time permissions are granted when the app is installed to
10076        // all device users and users added in the future. Runtime permissions
10077        // are granted at runtime explicitly to specific users. Normal and signature
10078        // protected permissions are install time permissions. Dangerous permissions
10079        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10080        // otherwise they are runtime permissions. This function does not manage
10081        // runtime permissions except for the case an app targeting Lollipop MR1
10082        // being upgraded to target a newer SDK, in which case dangerous permissions
10083        // are transformed from install time to runtime ones.
10084
10085        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10086        if (ps == null) {
10087            return;
10088        }
10089
10090        PermissionsState permissionsState = ps.getPermissionsState();
10091        PermissionsState origPermissions = permissionsState;
10092
10093        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10094
10095        boolean runtimePermissionsRevoked = false;
10096        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10097
10098        boolean changedInstallPermission = false;
10099
10100        if (replace) {
10101            ps.installPermissionsFixed = false;
10102            if (!ps.isSharedUser()) {
10103                origPermissions = new PermissionsState(permissionsState);
10104                permissionsState.reset();
10105            } else {
10106                // We need to know only about runtime permission changes since the
10107                // calling code always writes the install permissions state but
10108                // the runtime ones are written only if changed. The only cases of
10109                // changed runtime permissions here are promotion of an install to
10110                // runtime and revocation of a runtime from a shared user.
10111                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10112                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10113                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10114                    runtimePermissionsRevoked = true;
10115                }
10116            }
10117        }
10118
10119        permissionsState.setGlobalGids(mGlobalGids);
10120
10121        final int N = pkg.requestedPermissions.size();
10122        for (int i=0; i<N; i++) {
10123            final String name = pkg.requestedPermissions.get(i);
10124            final BasePermission bp = mSettings.mPermissions.get(name);
10125
10126            if (DEBUG_INSTALL) {
10127                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10128            }
10129
10130            if (bp == null || bp.packageSetting == null) {
10131                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10132                    Slog.w(TAG, "Unknown permission " + name
10133                            + " in package " + pkg.packageName);
10134                }
10135                continue;
10136            }
10137
10138
10139            // Limit ephemeral apps to ephemeral allowed permissions.
10140            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10141                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10142                        + pkg.packageName);
10143                continue;
10144            }
10145
10146            final String perm = bp.name;
10147            boolean allowedSig = false;
10148            int grant = GRANT_DENIED;
10149
10150            // Keep track of app op permissions.
10151            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10152                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10153                if (pkgs == null) {
10154                    pkgs = new ArraySet<>();
10155                    mAppOpPermissionPackages.put(bp.name, pkgs);
10156                }
10157                pkgs.add(pkg.packageName);
10158            }
10159
10160            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10161            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10162                    >= Build.VERSION_CODES.M;
10163            switch (level) {
10164                case PermissionInfo.PROTECTION_NORMAL: {
10165                    // For all apps normal permissions are install time ones.
10166                    grant = GRANT_INSTALL;
10167                } break;
10168
10169                case PermissionInfo.PROTECTION_DANGEROUS: {
10170                    // If a permission review is required for legacy apps we represent
10171                    // their permissions as always granted runtime ones since we need
10172                    // to keep the review required permission flag per user while an
10173                    // install permission's state is shared across all users.
10174                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10175                        // For legacy apps dangerous permissions are install time ones.
10176                        grant = GRANT_INSTALL;
10177                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10178                        // For legacy apps that became modern, install becomes runtime.
10179                        grant = GRANT_UPGRADE;
10180                    } else if (mPromoteSystemApps
10181                            && isSystemApp(ps)
10182                            && mExistingSystemPackages.contains(ps.name)) {
10183                        // For legacy system apps, install becomes runtime.
10184                        // We cannot check hasInstallPermission() for system apps since those
10185                        // permissions were granted implicitly and not persisted pre-M.
10186                        grant = GRANT_UPGRADE;
10187                    } else {
10188                        // For modern apps keep runtime permissions unchanged.
10189                        grant = GRANT_RUNTIME;
10190                    }
10191                } break;
10192
10193                case PermissionInfo.PROTECTION_SIGNATURE: {
10194                    // For all apps signature permissions are install time ones.
10195                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10196                    if (allowedSig) {
10197                        grant = GRANT_INSTALL;
10198                    }
10199                } break;
10200            }
10201
10202            if (DEBUG_INSTALL) {
10203                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10204            }
10205
10206            if (grant != GRANT_DENIED) {
10207                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10208                    // If this is an existing, non-system package, then
10209                    // we can't add any new permissions to it.
10210                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10211                        // Except...  if this is a permission that was added
10212                        // to the platform (note: need to only do this when
10213                        // updating the platform).
10214                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10215                            grant = GRANT_DENIED;
10216                        }
10217                    }
10218                }
10219
10220                switch (grant) {
10221                    case GRANT_INSTALL: {
10222                        // Revoke this as runtime permission to handle the case of
10223                        // a runtime permission being downgraded to an install one.
10224                        // Also in permission review mode we keep dangerous permissions
10225                        // for legacy apps
10226                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10227                            if (origPermissions.getRuntimePermissionState(
10228                                    bp.name, userId) != null) {
10229                                // Revoke the runtime permission and clear the flags.
10230                                origPermissions.revokeRuntimePermission(bp, userId);
10231                                origPermissions.updatePermissionFlags(bp, userId,
10232                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10233                                // If we revoked a permission permission, we have to write.
10234                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10235                                        changedRuntimePermissionUserIds, userId);
10236                            }
10237                        }
10238                        // Grant an install permission.
10239                        if (permissionsState.grantInstallPermission(bp) !=
10240                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10241                            changedInstallPermission = true;
10242                        }
10243                    } break;
10244
10245                    case GRANT_RUNTIME: {
10246                        // Grant previously granted runtime permissions.
10247                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10248                            PermissionState permissionState = origPermissions
10249                                    .getRuntimePermissionState(bp.name, userId);
10250                            int flags = permissionState != null
10251                                    ? permissionState.getFlags() : 0;
10252                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10253                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10254                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10255                                    // If we cannot put the permission as it was, we have to write.
10256                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10257                                            changedRuntimePermissionUserIds, userId);
10258                                }
10259                                // If the app supports runtime permissions no need for a review.
10260                                if (mPermissionReviewRequired
10261                                        && appSupportsRuntimePermissions
10262                                        && (flags & PackageManager
10263                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10264                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10265                                    // Since we changed the flags, we have to write.
10266                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10267                                            changedRuntimePermissionUserIds, userId);
10268                                }
10269                            } else if (mPermissionReviewRequired
10270                                    && !appSupportsRuntimePermissions) {
10271                                // For legacy apps that need a permission review, every new
10272                                // runtime permission is granted but it is pending a review.
10273                                // We also need to review only platform defined runtime
10274                                // permissions as these are the only ones the platform knows
10275                                // how to disable the API to simulate revocation as legacy
10276                                // apps don't expect to run with revoked permissions.
10277                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10278                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10279                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10280                                        // We changed the flags, hence have to write.
10281                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10282                                                changedRuntimePermissionUserIds, userId);
10283                                    }
10284                                }
10285                                if (permissionsState.grantRuntimePermission(bp, userId)
10286                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10287                                    // We changed the permission, hence have to write.
10288                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10289                                            changedRuntimePermissionUserIds, userId);
10290                                }
10291                            }
10292                            // Propagate the permission flags.
10293                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10294                        }
10295                    } break;
10296
10297                    case GRANT_UPGRADE: {
10298                        // Grant runtime permissions for a previously held install permission.
10299                        PermissionState permissionState = origPermissions
10300                                .getInstallPermissionState(bp.name);
10301                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10302
10303                        if (origPermissions.revokeInstallPermission(bp)
10304                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10305                            // We will be transferring the permission flags, so clear them.
10306                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10307                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10308                            changedInstallPermission = true;
10309                        }
10310
10311                        // If the permission is not to be promoted to runtime we ignore it and
10312                        // also its other flags as they are not applicable to install permissions.
10313                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10314                            for (int userId : currentUserIds) {
10315                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10316                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10317                                    // Transfer the permission flags.
10318                                    permissionsState.updatePermissionFlags(bp, userId,
10319                                            flags, flags);
10320                                    // If we granted the permission, we have to write.
10321                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10322                                            changedRuntimePermissionUserIds, userId);
10323                                }
10324                            }
10325                        }
10326                    } break;
10327
10328                    default: {
10329                        if (packageOfInterest == null
10330                                || packageOfInterest.equals(pkg.packageName)) {
10331                            Slog.w(TAG, "Not granting permission " + perm
10332                                    + " to package " + pkg.packageName
10333                                    + " because it was previously installed without");
10334                        }
10335                    } break;
10336                }
10337            } else {
10338                if (permissionsState.revokeInstallPermission(bp) !=
10339                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10340                    // Also drop the permission flags.
10341                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10342                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10343                    changedInstallPermission = true;
10344                    Slog.i(TAG, "Un-granting permission " + perm
10345                            + " from package " + pkg.packageName
10346                            + " (protectionLevel=" + bp.protectionLevel
10347                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10348                            + ")");
10349                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10350                    // Don't print warning for app op permissions, since it is fine for them
10351                    // not to be granted, there is a UI for the user to decide.
10352                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10353                        Slog.w(TAG, "Not granting permission " + perm
10354                                + " to package " + pkg.packageName
10355                                + " (protectionLevel=" + bp.protectionLevel
10356                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10357                                + ")");
10358                    }
10359                }
10360            }
10361        }
10362
10363        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10364                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10365            // This is the first that we have heard about this package, so the
10366            // permissions we have now selected are fixed until explicitly
10367            // changed.
10368            ps.installPermissionsFixed = true;
10369        }
10370
10371        // Persist the runtime permissions state for users with changes. If permissions
10372        // were revoked because no app in the shared user declares them we have to
10373        // write synchronously to avoid losing runtime permissions state.
10374        for (int userId : changedRuntimePermissionUserIds) {
10375            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10376        }
10377    }
10378
10379    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10380        boolean allowed = false;
10381        final int NP = PackageParser.NEW_PERMISSIONS.length;
10382        for (int ip=0; ip<NP; ip++) {
10383            final PackageParser.NewPermissionInfo npi
10384                    = PackageParser.NEW_PERMISSIONS[ip];
10385            if (npi.name.equals(perm)
10386                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10387                allowed = true;
10388                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10389                        + pkg.packageName);
10390                break;
10391            }
10392        }
10393        return allowed;
10394    }
10395
10396    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10397            BasePermission bp, PermissionsState origPermissions) {
10398        boolean privilegedPermission = (bp.protectionLevel
10399                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10400        boolean controlPrivappPermissions = RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS;
10401        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10402        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10403        if (controlPrivappPermissions && privilegedPermission && pkg.isPrivilegedApp()
10404                && !platformPackage && platformPermission) {
10405            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10406                    .getPrivAppPermissions(pkg.packageName);
10407            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10408            if (!whitelisted) {
10409                Slog.e(TAG, "Not granting privileged permission " + perm + " for package "
10410                        + pkg.packageName + " - not in privapp-permissions whitelist");
10411                return false;
10412            }
10413        }
10414        boolean allowed = (compareSignatures(
10415                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10416                        == PackageManager.SIGNATURE_MATCH)
10417                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10418                        == PackageManager.SIGNATURE_MATCH);
10419        if (!allowed && privilegedPermission) {
10420            if (isSystemApp(pkg)) {
10421                // For updated system applications, a system permission
10422                // is granted only if it had been defined by the original application.
10423                if (pkg.isUpdatedSystemApp()) {
10424                    final PackageSetting sysPs = mSettings
10425                            .getDisabledSystemPkgLPr(pkg.packageName);
10426                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10427                        // If the original was granted this permission, we take
10428                        // that grant decision as read and propagate it to the
10429                        // update.
10430                        if (sysPs.isPrivileged()) {
10431                            allowed = true;
10432                        }
10433                    } else {
10434                        // The system apk may have been updated with an older
10435                        // version of the one on the data partition, but which
10436                        // granted a new system permission that it didn't have
10437                        // before.  In this case we do want to allow the app to
10438                        // now get the new permission if the ancestral apk is
10439                        // privileged to get it.
10440                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10441                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10442                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10443                                    allowed = true;
10444                                    break;
10445                                }
10446                            }
10447                        }
10448                        // Also if a privileged parent package on the system image or any of
10449                        // its children requested a privileged permission, the updated child
10450                        // packages can also get the permission.
10451                        if (pkg.parentPackage != null) {
10452                            final PackageSetting disabledSysParentPs = mSettings
10453                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10454                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10455                                    && disabledSysParentPs.isPrivileged()) {
10456                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10457                                    allowed = true;
10458                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10459                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10460                                    for (int i = 0; i < count; i++) {
10461                                        PackageParser.Package disabledSysChildPkg =
10462                                                disabledSysParentPs.pkg.childPackages.get(i);
10463                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10464                                                perm)) {
10465                                            allowed = true;
10466                                            break;
10467                                        }
10468                                    }
10469                                }
10470                            }
10471                        }
10472                    }
10473                } else {
10474                    allowed = isPrivilegedApp(pkg);
10475                }
10476            }
10477        }
10478        if (!allowed) {
10479            if (!allowed && (bp.protectionLevel
10480                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10481                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10482                // If this was a previously normal/dangerous permission that got moved
10483                // to a system permission as part of the runtime permission redesign, then
10484                // we still want to blindly grant it to old apps.
10485                allowed = true;
10486            }
10487            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10488                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10489                // If this permission is to be granted to the system installer and
10490                // this app is an installer, then it gets the permission.
10491                allowed = true;
10492            }
10493            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10494                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10495                // If this permission is to be granted to the system verifier and
10496                // this app is a verifier, then it gets the permission.
10497                allowed = true;
10498            }
10499            if (!allowed && (bp.protectionLevel
10500                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10501                    && isSystemApp(pkg)) {
10502                // Any pre-installed system app is allowed to get this permission.
10503                allowed = true;
10504            }
10505            if (!allowed && (bp.protectionLevel
10506                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10507                // For development permissions, a development permission
10508                // is granted only if it was already granted.
10509                allowed = origPermissions.hasInstallPermission(perm);
10510            }
10511            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10512                    && pkg.packageName.equals(mSetupWizardPackage)) {
10513                // If this permission is to be granted to the system setup wizard and
10514                // this app is a setup wizard, then it gets the permission.
10515                allowed = true;
10516            }
10517        }
10518        return allowed;
10519    }
10520
10521    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10522        final int permCount = pkg.requestedPermissions.size();
10523        for (int j = 0; j < permCount; j++) {
10524            String requestedPermission = pkg.requestedPermissions.get(j);
10525            if (permission.equals(requestedPermission)) {
10526                return true;
10527            }
10528        }
10529        return false;
10530    }
10531
10532    final class ActivityIntentResolver
10533            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10534        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10535                boolean defaultOnly, int userId) {
10536            if (!sUserManager.exists(userId)) return null;
10537            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10538            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10539        }
10540
10541        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10542                int userId) {
10543            if (!sUserManager.exists(userId)) return null;
10544            mFlags = flags;
10545            return super.queryIntent(intent, resolvedType,
10546                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10547        }
10548
10549        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10550                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10551            if (!sUserManager.exists(userId)) return null;
10552            if (packageActivities == null) {
10553                return null;
10554            }
10555            mFlags = flags;
10556            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10557            final int N = packageActivities.size();
10558            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10559                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10560
10561            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10562            for (int i = 0; i < N; ++i) {
10563                intentFilters = packageActivities.get(i).intents;
10564                if (intentFilters != null && intentFilters.size() > 0) {
10565                    PackageParser.ActivityIntentInfo[] array =
10566                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10567                    intentFilters.toArray(array);
10568                    listCut.add(array);
10569                }
10570            }
10571            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10572        }
10573
10574        /**
10575         * Finds a privileged activity that matches the specified activity names.
10576         */
10577        private PackageParser.Activity findMatchingActivity(
10578                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10579            for (PackageParser.Activity sysActivity : activityList) {
10580                if (sysActivity.info.name.equals(activityInfo.name)) {
10581                    return sysActivity;
10582                }
10583                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10584                    return sysActivity;
10585                }
10586                if (sysActivity.info.targetActivity != null) {
10587                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10588                        return sysActivity;
10589                    }
10590                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10591                        return sysActivity;
10592                    }
10593                }
10594            }
10595            return null;
10596        }
10597
10598        public class IterGenerator<E> {
10599            public Iterator<E> generate(ActivityIntentInfo info) {
10600                return null;
10601            }
10602        }
10603
10604        public class ActionIterGenerator extends IterGenerator<String> {
10605            @Override
10606            public Iterator<String> generate(ActivityIntentInfo info) {
10607                return info.actionsIterator();
10608            }
10609        }
10610
10611        public class CategoriesIterGenerator extends IterGenerator<String> {
10612            @Override
10613            public Iterator<String> generate(ActivityIntentInfo info) {
10614                return info.categoriesIterator();
10615            }
10616        }
10617
10618        public class SchemesIterGenerator extends IterGenerator<String> {
10619            @Override
10620            public Iterator<String> generate(ActivityIntentInfo info) {
10621                return info.schemesIterator();
10622            }
10623        }
10624
10625        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10626            @Override
10627            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10628                return info.authoritiesIterator();
10629            }
10630        }
10631
10632        /**
10633         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10634         * MODIFIED. Do not pass in a list that should not be changed.
10635         */
10636        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10637                IterGenerator<T> generator, Iterator<T> searchIterator) {
10638            // loop through the set of actions; every one must be found in the intent filter
10639            while (searchIterator.hasNext()) {
10640                // we must have at least one filter in the list to consider a match
10641                if (intentList.size() == 0) {
10642                    break;
10643                }
10644
10645                final T searchAction = searchIterator.next();
10646
10647                // loop through the set of intent filters
10648                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10649                while (intentIter.hasNext()) {
10650                    final ActivityIntentInfo intentInfo = intentIter.next();
10651                    boolean selectionFound = false;
10652
10653                    // loop through the intent filter's selection criteria; at least one
10654                    // of them must match the searched criteria
10655                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10656                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10657                        final T intentSelection = intentSelectionIter.next();
10658                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10659                            selectionFound = true;
10660                            break;
10661                        }
10662                    }
10663
10664                    // the selection criteria wasn't found in this filter's set; this filter
10665                    // is not a potential match
10666                    if (!selectionFound) {
10667                        intentIter.remove();
10668                    }
10669                }
10670            }
10671        }
10672
10673        private boolean isProtectedAction(ActivityIntentInfo filter) {
10674            final Iterator<String> actionsIter = filter.actionsIterator();
10675            while (actionsIter != null && actionsIter.hasNext()) {
10676                final String filterAction = actionsIter.next();
10677                if (PROTECTED_ACTIONS.contains(filterAction)) {
10678                    return true;
10679                }
10680            }
10681            return false;
10682        }
10683
10684        /**
10685         * Adjusts the priority of the given intent filter according to policy.
10686         * <p>
10687         * <ul>
10688         * <li>The priority for non privileged applications is capped to '0'</li>
10689         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10690         * <li>The priority for unbundled updates to privileged applications is capped to the
10691         *      priority defined on the system partition</li>
10692         * </ul>
10693         * <p>
10694         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10695         * allowed to obtain any priority on any action.
10696         */
10697        private void adjustPriority(
10698                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10699            // nothing to do; priority is fine as-is
10700            if (intent.getPriority() <= 0) {
10701                return;
10702            }
10703
10704            final ActivityInfo activityInfo = intent.activity.info;
10705            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10706
10707            final boolean privilegedApp =
10708                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10709            if (!privilegedApp) {
10710                // non-privileged applications can never define a priority >0
10711                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10712                        + " package: " + applicationInfo.packageName
10713                        + " activity: " + intent.activity.className
10714                        + " origPrio: " + intent.getPriority());
10715                intent.setPriority(0);
10716                return;
10717            }
10718
10719            if (systemActivities == null) {
10720                // the system package is not disabled; we're parsing the system partition
10721                if (isProtectedAction(intent)) {
10722                    if (mDeferProtectedFilters) {
10723                        // We can't deal with these just yet. No component should ever obtain a
10724                        // >0 priority for a protected actions, with ONE exception -- the setup
10725                        // wizard. The setup wizard, however, cannot be known until we're able to
10726                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10727                        // until all intent filters have been processed. Chicken, meet egg.
10728                        // Let the filter temporarily have a high priority and rectify the
10729                        // priorities after all system packages have been scanned.
10730                        mProtectedFilters.add(intent);
10731                        if (DEBUG_FILTERS) {
10732                            Slog.i(TAG, "Protected action; save for later;"
10733                                    + " package: " + applicationInfo.packageName
10734                                    + " activity: " + intent.activity.className
10735                                    + " origPrio: " + intent.getPriority());
10736                        }
10737                        return;
10738                    } else {
10739                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10740                            Slog.i(TAG, "No setup wizard;"
10741                                + " All protected intents capped to priority 0");
10742                        }
10743                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10744                            if (DEBUG_FILTERS) {
10745                                Slog.i(TAG, "Found setup wizard;"
10746                                    + " allow priority " + intent.getPriority() + ";"
10747                                    + " package: " + intent.activity.info.packageName
10748                                    + " activity: " + intent.activity.className
10749                                    + " priority: " + intent.getPriority());
10750                            }
10751                            // setup wizard gets whatever it wants
10752                            return;
10753                        }
10754                        Slog.w(TAG, "Protected action; cap priority to 0;"
10755                                + " package: " + intent.activity.info.packageName
10756                                + " activity: " + intent.activity.className
10757                                + " origPrio: " + intent.getPriority());
10758                        intent.setPriority(0);
10759                        return;
10760                    }
10761                }
10762                // privileged apps on the system image get whatever priority they request
10763                return;
10764            }
10765
10766            // privileged app unbundled update ... try to find the same activity
10767            final PackageParser.Activity foundActivity =
10768                    findMatchingActivity(systemActivities, activityInfo);
10769            if (foundActivity == null) {
10770                // this is a new activity; it cannot obtain >0 priority
10771                if (DEBUG_FILTERS) {
10772                    Slog.i(TAG, "New activity; cap priority to 0;"
10773                            + " package: " + applicationInfo.packageName
10774                            + " activity: " + intent.activity.className
10775                            + " origPrio: " + intent.getPriority());
10776                }
10777                intent.setPriority(0);
10778                return;
10779            }
10780
10781            // found activity, now check for filter equivalence
10782
10783            // a shallow copy is enough; we modify the list, not its contents
10784            final List<ActivityIntentInfo> intentListCopy =
10785                    new ArrayList<>(foundActivity.intents);
10786            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10787
10788            // find matching action subsets
10789            final Iterator<String> actionsIterator = intent.actionsIterator();
10790            if (actionsIterator != null) {
10791                getIntentListSubset(
10792                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10793                if (intentListCopy.size() == 0) {
10794                    // no more intents to match; we're not equivalent
10795                    if (DEBUG_FILTERS) {
10796                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10797                                + " package: " + applicationInfo.packageName
10798                                + " activity: " + intent.activity.className
10799                                + " origPrio: " + intent.getPriority());
10800                    }
10801                    intent.setPriority(0);
10802                    return;
10803                }
10804            }
10805
10806            // find matching category subsets
10807            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10808            if (categoriesIterator != null) {
10809                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10810                        categoriesIterator);
10811                if (intentListCopy.size() == 0) {
10812                    // no more intents to match; we're not equivalent
10813                    if (DEBUG_FILTERS) {
10814                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10815                                + " package: " + applicationInfo.packageName
10816                                + " activity: " + intent.activity.className
10817                                + " origPrio: " + intent.getPriority());
10818                    }
10819                    intent.setPriority(0);
10820                    return;
10821                }
10822            }
10823
10824            // find matching schemes subsets
10825            final Iterator<String> schemesIterator = intent.schemesIterator();
10826            if (schemesIterator != null) {
10827                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10828                        schemesIterator);
10829                if (intentListCopy.size() == 0) {
10830                    // no more intents to match; we're not equivalent
10831                    if (DEBUG_FILTERS) {
10832                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10833                                + " package: " + applicationInfo.packageName
10834                                + " activity: " + intent.activity.className
10835                                + " origPrio: " + intent.getPriority());
10836                    }
10837                    intent.setPriority(0);
10838                    return;
10839                }
10840            }
10841
10842            // find matching authorities subsets
10843            final Iterator<IntentFilter.AuthorityEntry>
10844                    authoritiesIterator = intent.authoritiesIterator();
10845            if (authoritiesIterator != null) {
10846                getIntentListSubset(intentListCopy,
10847                        new AuthoritiesIterGenerator(),
10848                        authoritiesIterator);
10849                if (intentListCopy.size() == 0) {
10850                    // no more intents to match; we're not equivalent
10851                    if (DEBUG_FILTERS) {
10852                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10853                                + " package: " + applicationInfo.packageName
10854                                + " activity: " + intent.activity.className
10855                                + " origPrio: " + intent.getPriority());
10856                    }
10857                    intent.setPriority(0);
10858                    return;
10859                }
10860            }
10861
10862            // we found matching filter(s); app gets the max priority of all intents
10863            int cappedPriority = 0;
10864            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10865                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10866            }
10867            if (intent.getPriority() > cappedPriority) {
10868                if (DEBUG_FILTERS) {
10869                    Slog.i(TAG, "Found matching filter(s);"
10870                            + " cap priority to " + cappedPriority + ";"
10871                            + " package: " + applicationInfo.packageName
10872                            + " activity: " + intent.activity.className
10873                            + " origPrio: " + intent.getPriority());
10874                }
10875                intent.setPriority(cappedPriority);
10876                return;
10877            }
10878            // all this for nothing; the requested priority was <= what was on the system
10879        }
10880
10881        public final void addActivity(PackageParser.Activity a, String type) {
10882            mActivities.put(a.getComponentName(), a);
10883            if (DEBUG_SHOW_INFO)
10884                Log.v(
10885                TAG, "  " + type + " " +
10886                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10887            if (DEBUG_SHOW_INFO)
10888                Log.v(TAG, "    Class=" + a.info.name);
10889            final int NI = a.intents.size();
10890            for (int j=0; j<NI; j++) {
10891                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10892                if ("activity".equals(type)) {
10893                    final PackageSetting ps =
10894                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10895                    final List<PackageParser.Activity> systemActivities =
10896                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10897                    adjustPriority(systemActivities, intent);
10898                }
10899                if (DEBUG_SHOW_INFO) {
10900                    Log.v(TAG, "    IntentFilter:");
10901                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10902                }
10903                if (!intent.debugCheck()) {
10904                    Log.w(TAG, "==> For Activity " + a.info.name);
10905                }
10906                addFilter(intent);
10907            }
10908        }
10909
10910        public final void removeActivity(PackageParser.Activity a, String type) {
10911            mActivities.remove(a.getComponentName());
10912            if (DEBUG_SHOW_INFO) {
10913                Log.v(TAG, "  " + type + " "
10914                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10915                                : a.info.name) + ":");
10916                Log.v(TAG, "    Class=" + a.info.name);
10917            }
10918            final int NI = a.intents.size();
10919            for (int j=0; j<NI; j++) {
10920                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10921                if (DEBUG_SHOW_INFO) {
10922                    Log.v(TAG, "    IntentFilter:");
10923                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10924                }
10925                removeFilter(intent);
10926            }
10927        }
10928
10929        @Override
10930        protected boolean allowFilterResult(
10931                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10932            ActivityInfo filterAi = filter.activity.info;
10933            for (int i=dest.size()-1; i>=0; i--) {
10934                ActivityInfo destAi = dest.get(i).activityInfo;
10935                if (destAi.name == filterAi.name
10936                        && destAi.packageName == filterAi.packageName) {
10937                    return false;
10938                }
10939            }
10940            return true;
10941        }
10942
10943        @Override
10944        protected ActivityIntentInfo[] newArray(int size) {
10945            return new ActivityIntentInfo[size];
10946        }
10947
10948        @Override
10949        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10950            if (!sUserManager.exists(userId)) return true;
10951            PackageParser.Package p = filter.activity.owner;
10952            if (p != null) {
10953                PackageSetting ps = (PackageSetting)p.mExtras;
10954                if (ps != null) {
10955                    // System apps are never considered stopped for purposes of
10956                    // filtering, because there may be no way for the user to
10957                    // actually re-launch them.
10958                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10959                            && ps.getStopped(userId);
10960                }
10961            }
10962            return false;
10963        }
10964
10965        @Override
10966        protected boolean isPackageForFilter(String packageName,
10967                PackageParser.ActivityIntentInfo info) {
10968            return packageName.equals(info.activity.owner.packageName);
10969        }
10970
10971        @Override
10972        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10973                int match, int userId) {
10974            if (!sUserManager.exists(userId)) return null;
10975            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10976                return null;
10977            }
10978            final PackageParser.Activity activity = info.activity;
10979            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10980            if (ps == null) {
10981                return null;
10982            }
10983            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10984                    ps.readUserState(userId), userId);
10985            if (ai == null) {
10986                return null;
10987            }
10988            final ResolveInfo res = new ResolveInfo();
10989            res.activityInfo = ai;
10990            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10991                res.filter = info;
10992            }
10993            if (info != null) {
10994                res.handleAllWebDataURI = info.handleAllWebDataURI();
10995            }
10996            res.priority = info.getPriority();
10997            res.preferredOrder = activity.owner.mPreferredOrder;
10998            //System.out.println("Result: " + res.activityInfo.className +
10999            //                   " = " + res.priority);
11000            res.match = match;
11001            res.isDefault = info.hasDefault;
11002            res.labelRes = info.labelRes;
11003            res.nonLocalizedLabel = info.nonLocalizedLabel;
11004            if (userNeedsBadging(userId)) {
11005                res.noResourceId = true;
11006            } else {
11007                res.icon = info.icon;
11008            }
11009            res.iconResourceId = info.icon;
11010            res.system = res.activityInfo.applicationInfo.isSystemApp();
11011            return res;
11012        }
11013
11014        @Override
11015        protected void sortResults(List<ResolveInfo> results) {
11016            Collections.sort(results, mResolvePrioritySorter);
11017        }
11018
11019        @Override
11020        protected void dumpFilter(PrintWriter out, String prefix,
11021                PackageParser.ActivityIntentInfo filter) {
11022            out.print(prefix); out.print(
11023                    Integer.toHexString(System.identityHashCode(filter.activity)));
11024                    out.print(' ');
11025                    filter.activity.printComponentShortName(out);
11026                    out.print(" filter ");
11027                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11028        }
11029
11030        @Override
11031        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11032            return filter.activity;
11033        }
11034
11035        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11036            PackageParser.Activity activity = (PackageParser.Activity)label;
11037            out.print(prefix); out.print(
11038                    Integer.toHexString(System.identityHashCode(activity)));
11039                    out.print(' ');
11040                    activity.printComponentShortName(out);
11041            if (count > 1) {
11042                out.print(" ("); out.print(count); out.print(" filters)");
11043            }
11044            out.println();
11045        }
11046
11047        // Keys are String (activity class name), values are Activity.
11048        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11049                = new ArrayMap<ComponentName, PackageParser.Activity>();
11050        private int mFlags;
11051    }
11052
11053    private final class ServiceIntentResolver
11054            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11055        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11056                boolean defaultOnly, int userId) {
11057            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11058            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11059        }
11060
11061        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11062                int userId) {
11063            if (!sUserManager.exists(userId)) return null;
11064            mFlags = flags;
11065            return super.queryIntent(intent, resolvedType,
11066                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11067        }
11068
11069        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11070                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11071            if (!sUserManager.exists(userId)) return null;
11072            if (packageServices == null) {
11073                return null;
11074            }
11075            mFlags = flags;
11076            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11077            final int N = packageServices.size();
11078            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11079                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11080
11081            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11082            for (int i = 0; i < N; ++i) {
11083                intentFilters = packageServices.get(i).intents;
11084                if (intentFilters != null && intentFilters.size() > 0) {
11085                    PackageParser.ServiceIntentInfo[] array =
11086                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11087                    intentFilters.toArray(array);
11088                    listCut.add(array);
11089                }
11090            }
11091            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11092        }
11093
11094        public final void addService(PackageParser.Service s) {
11095            mServices.put(s.getComponentName(), s);
11096            if (DEBUG_SHOW_INFO) {
11097                Log.v(TAG, "  "
11098                        + (s.info.nonLocalizedLabel != null
11099                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11100                Log.v(TAG, "    Class=" + s.info.name);
11101            }
11102            final int NI = s.intents.size();
11103            int j;
11104            for (j=0; j<NI; j++) {
11105                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11106                if (DEBUG_SHOW_INFO) {
11107                    Log.v(TAG, "    IntentFilter:");
11108                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11109                }
11110                if (!intent.debugCheck()) {
11111                    Log.w(TAG, "==> For Service " + s.info.name);
11112                }
11113                addFilter(intent);
11114            }
11115        }
11116
11117        public final void removeService(PackageParser.Service s) {
11118            mServices.remove(s.getComponentName());
11119            if (DEBUG_SHOW_INFO) {
11120                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11121                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11122                Log.v(TAG, "    Class=" + s.info.name);
11123            }
11124            final int NI = s.intents.size();
11125            int j;
11126            for (j=0; j<NI; j++) {
11127                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11128                if (DEBUG_SHOW_INFO) {
11129                    Log.v(TAG, "    IntentFilter:");
11130                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11131                }
11132                removeFilter(intent);
11133            }
11134        }
11135
11136        @Override
11137        protected boolean allowFilterResult(
11138                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11139            ServiceInfo filterSi = filter.service.info;
11140            for (int i=dest.size()-1; i>=0; i--) {
11141                ServiceInfo destAi = dest.get(i).serviceInfo;
11142                if (destAi.name == filterSi.name
11143                        && destAi.packageName == filterSi.packageName) {
11144                    return false;
11145                }
11146            }
11147            return true;
11148        }
11149
11150        @Override
11151        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11152            return new PackageParser.ServiceIntentInfo[size];
11153        }
11154
11155        @Override
11156        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11157            if (!sUserManager.exists(userId)) return true;
11158            PackageParser.Package p = filter.service.owner;
11159            if (p != null) {
11160                PackageSetting ps = (PackageSetting)p.mExtras;
11161                if (ps != null) {
11162                    // System apps are never considered stopped for purposes of
11163                    // filtering, because there may be no way for the user to
11164                    // actually re-launch them.
11165                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11166                            && ps.getStopped(userId);
11167                }
11168            }
11169            return false;
11170        }
11171
11172        @Override
11173        protected boolean isPackageForFilter(String packageName,
11174                PackageParser.ServiceIntentInfo info) {
11175            return packageName.equals(info.service.owner.packageName);
11176        }
11177
11178        @Override
11179        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11180                int match, int userId) {
11181            if (!sUserManager.exists(userId)) return null;
11182            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11183            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11184                return null;
11185            }
11186            final PackageParser.Service service = info.service;
11187            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11188            if (ps == null) {
11189                return null;
11190            }
11191            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11192                    ps.readUserState(userId), userId);
11193            if (si == null) {
11194                return null;
11195            }
11196            final ResolveInfo res = new ResolveInfo();
11197            res.serviceInfo = si;
11198            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11199                res.filter = filter;
11200            }
11201            res.priority = info.getPriority();
11202            res.preferredOrder = service.owner.mPreferredOrder;
11203            res.match = match;
11204            res.isDefault = info.hasDefault;
11205            res.labelRes = info.labelRes;
11206            res.nonLocalizedLabel = info.nonLocalizedLabel;
11207            res.icon = info.icon;
11208            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11209            return res;
11210        }
11211
11212        @Override
11213        protected void sortResults(List<ResolveInfo> results) {
11214            Collections.sort(results, mResolvePrioritySorter);
11215        }
11216
11217        @Override
11218        protected void dumpFilter(PrintWriter out, String prefix,
11219                PackageParser.ServiceIntentInfo filter) {
11220            out.print(prefix); out.print(
11221                    Integer.toHexString(System.identityHashCode(filter.service)));
11222                    out.print(' ');
11223                    filter.service.printComponentShortName(out);
11224                    out.print(" filter ");
11225                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11226        }
11227
11228        @Override
11229        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11230            return filter.service;
11231        }
11232
11233        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11234            PackageParser.Service service = (PackageParser.Service)label;
11235            out.print(prefix); out.print(
11236                    Integer.toHexString(System.identityHashCode(service)));
11237                    out.print(' ');
11238                    service.printComponentShortName(out);
11239            if (count > 1) {
11240                out.print(" ("); out.print(count); out.print(" filters)");
11241            }
11242            out.println();
11243        }
11244
11245//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11246//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11247//            final List<ResolveInfo> retList = Lists.newArrayList();
11248//            while (i.hasNext()) {
11249//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11250//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11251//                    retList.add(resolveInfo);
11252//                }
11253//            }
11254//            return retList;
11255//        }
11256
11257        // Keys are String (activity class name), values are Activity.
11258        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11259                = new ArrayMap<ComponentName, PackageParser.Service>();
11260        private int mFlags;
11261    };
11262
11263    private final class ProviderIntentResolver
11264            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11265        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11266                boolean defaultOnly, int userId) {
11267            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11268            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11269        }
11270
11271        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11272                int userId) {
11273            if (!sUserManager.exists(userId))
11274                return null;
11275            mFlags = flags;
11276            return super.queryIntent(intent, resolvedType,
11277                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11278        }
11279
11280        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11281                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11282            if (!sUserManager.exists(userId))
11283                return null;
11284            if (packageProviders == null) {
11285                return null;
11286            }
11287            mFlags = flags;
11288            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11289            final int N = packageProviders.size();
11290            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11291                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11292
11293            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11294            for (int i = 0; i < N; ++i) {
11295                intentFilters = packageProviders.get(i).intents;
11296                if (intentFilters != null && intentFilters.size() > 0) {
11297                    PackageParser.ProviderIntentInfo[] array =
11298                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11299                    intentFilters.toArray(array);
11300                    listCut.add(array);
11301                }
11302            }
11303            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11304        }
11305
11306        public final void addProvider(PackageParser.Provider p) {
11307            if (mProviders.containsKey(p.getComponentName())) {
11308                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11309                return;
11310            }
11311
11312            mProviders.put(p.getComponentName(), p);
11313            if (DEBUG_SHOW_INFO) {
11314                Log.v(TAG, "  "
11315                        + (p.info.nonLocalizedLabel != null
11316                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11317                Log.v(TAG, "    Class=" + p.info.name);
11318            }
11319            final int NI = p.intents.size();
11320            int j;
11321            for (j = 0; j < NI; j++) {
11322                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11323                if (DEBUG_SHOW_INFO) {
11324                    Log.v(TAG, "    IntentFilter:");
11325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11326                }
11327                if (!intent.debugCheck()) {
11328                    Log.w(TAG, "==> For Provider " + p.info.name);
11329                }
11330                addFilter(intent);
11331            }
11332        }
11333
11334        public final void removeProvider(PackageParser.Provider p) {
11335            mProviders.remove(p.getComponentName());
11336            if (DEBUG_SHOW_INFO) {
11337                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11338                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11339                Log.v(TAG, "    Class=" + p.info.name);
11340            }
11341            final int NI = p.intents.size();
11342            int j;
11343            for (j = 0; j < NI; j++) {
11344                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11345                if (DEBUG_SHOW_INFO) {
11346                    Log.v(TAG, "    IntentFilter:");
11347                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11348                }
11349                removeFilter(intent);
11350            }
11351        }
11352
11353        @Override
11354        protected boolean allowFilterResult(
11355                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11356            ProviderInfo filterPi = filter.provider.info;
11357            for (int i = dest.size() - 1; i >= 0; i--) {
11358                ProviderInfo destPi = dest.get(i).providerInfo;
11359                if (destPi.name == filterPi.name
11360                        && destPi.packageName == filterPi.packageName) {
11361                    return false;
11362                }
11363            }
11364            return true;
11365        }
11366
11367        @Override
11368        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11369            return new PackageParser.ProviderIntentInfo[size];
11370        }
11371
11372        @Override
11373        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11374            if (!sUserManager.exists(userId))
11375                return true;
11376            PackageParser.Package p = filter.provider.owner;
11377            if (p != null) {
11378                PackageSetting ps = (PackageSetting) p.mExtras;
11379                if (ps != null) {
11380                    // System apps are never considered stopped for purposes of
11381                    // filtering, because there may be no way for the user to
11382                    // actually re-launch them.
11383                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11384                            && ps.getStopped(userId);
11385                }
11386            }
11387            return false;
11388        }
11389
11390        @Override
11391        protected boolean isPackageForFilter(String packageName,
11392                PackageParser.ProviderIntentInfo info) {
11393            return packageName.equals(info.provider.owner.packageName);
11394        }
11395
11396        @Override
11397        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11398                int match, int userId) {
11399            if (!sUserManager.exists(userId))
11400                return null;
11401            final PackageParser.ProviderIntentInfo info = filter;
11402            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11403                return null;
11404            }
11405            final PackageParser.Provider provider = info.provider;
11406            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11407            if (ps == null) {
11408                return null;
11409            }
11410            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11411                    ps.readUserState(userId), userId);
11412            if (pi == null) {
11413                return null;
11414            }
11415            final ResolveInfo res = new ResolveInfo();
11416            res.providerInfo = pi;
11417            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11418                res.filter = filter;
11419            }
11420            res.priority = info.getPriority();
11421            res.preferredOrder = provider.owner.mPreferredOrder;
11422            res.match = match;
11423            res.isDefault = info.hasDefault;
11424            res.labelRes = info.labelRes;
11425            res.nonLocalizedLabel = info.nonLocalizedLabel;
11426            res.icon = info.icon;
11427            res.system = res.providerInfo.applicationInfo.isSystemApp();
11428            return res;
11429        }
11430
11431        @Override
11432        protected void sortResults(List<ResolveInfo> results) {
11433            Collections.sort(results, mResolvePrioritySorter);
11434        }
11435
11436        @Override
11437        protected void dumpFilter(PrintWriter out, String prefix,
11438                PackageParser.ProviderIntentInfo filter) {
11439            out.print(prefix);
11440            out.print(
11441                    Integer.toHexString(System.identityHashCode(filter.provider)));
11442            out.print(' ');
11443            filter.provider.printComponentShortName(out);
11444            out.print(" filter ");
11445            out.println(Integer.toHexString(System.identityHashCode(filter)));
11446        }
11447
11448        @Override
11449        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11450            return filter.provider;
11451        }
11452
11453        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11454            PackageParser.Provider provider = (PackageParser.Provider)label;
11455            out.print(prefix); out.print(
11456                    Integer.toHexString(System.identityHashCode(provider)));
11457                    out.print(' ');
11458                    provider.printComponentShortName(out);
11459            if (count > 1) {
11460                out.print(" ("); out.print(count); out.print(" filters)");
11461            }
11462            out.println();
11463        }
11464
11465        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11466                = new ArrayMap<ComponentName, PackageParser.Provider>();
11467        private int mFlags;
11468    }
11469
11470    private static final class EphemeralIntentResolver
11471            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveIntentInfo> {
11472        /**
11473         * The result that has the highest defined order. Ordering applies on a
11474         * per-package basis. Mapping is from package name to Pair of order and
11475         * EphemeralResolveInfo.
11476         * <p>
11477         * NOTE: This is implemented as a field variable for convenience and efficiency.
11478         * By having a field variable, we're able to track filter ordering as soon as
11479         * a non-zero order is defined. Otherwise, multiple loops across the result set
11480         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11481         * this needs to be contained entirely within {@link #filterResults()}.
11482         */
11483        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11484
11485        @Override
11486        protected EphemeralResolveIntentInfo[] newArray(int size) {
11487            return new EphemeralResolveIntentInfo[size];
11488        }
11489
11490        @Override
11491        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11492            return true;
11493        }
11494
11495        @Override
11496        protected EphemeralResolveIntentInfo newResult(EphemeralResolveIntentInfo info, int match,
11497                int userId) {
11498            if (!sUserManager.exists(userId)) {
11499                return null;
11500            }
11501            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11502            final Integer order = info.getOrder();
11503            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11504                    mOrderResult.get(packageName);
11505            // ordering is enabled and this item's order isn't high enough
11506            if (lastOrderResult != null && lastOrderResult.first >= order) {
11507                return null;
11508            }
11509            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11510            if (order > 0) {
11511                // non-zero order, enable ordering
11512                mOrderResult.put(packageName, new Pair<>(order, res));
11513            }
11514            return info;
11515        }
11516
11517        @Override
11518        protected void filterResults(List<EphemeralResolveIntentInfo> results) {
11519            // only do work if ordering is enabled [most of the time it won't be]
11520            if (mOrderResult.size() == 0) {
11521                return;
11522            }
11523            int resultSize = results.size();
11524            for (int i = 0; i < resultSize; i++) {
11525                final EphemeralResolveInfo info = results.get(i).getEphemeralResolveInfo();
11526                final String packageName = info.getPackageName();
11527                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11528                if (savedInfo == null) {
11529                    // package doesn't having ordering
11530                    continue;
11531                }
11532                if (savedInfo.second == info) {
11533                    // circled back to the highest ordered item; remove from order list
11534                    mOrderResult.remove(savedInfo);
11535                    if (mOrderResult.size() == 0) {
11536                        // no more ordered items
11537                        break;
11538                    }
11539                    continue;
11540                }
11541                // item has a worse order, remove it from the result list
11542                results.remove(i);
11543                resultSize--;
11544                i--;
11545            }
11546        }
11547    }
11548
11549    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11550            new Comparator<ResolveInfo>() {
11551        public int compare(ResolveInfo r1, ResolveInfo r2) {
11552            int v1 = r1.priority;
11553            int v2 = r2.priority;
11554            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11555            if (v1 != v2) {
11556                return (v1 > v2) ? -1 : 1;
11557            }
11558            v1 = r1.preferredOrder;
11559            v2 = r2.preferredOrder;
11560            if (v1 != v2) {
11561                return (v1 > v2) ? -1 : 1;
11562            }
11563            if (r1.isDefault != r2.isDefault) {
11564                return r1.isDefault ? -1 : 1;
11565            }
11566            v1 = r1.match;
11567            v2 = r2.match;
11568            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11569            if (v1 != v2) {
11570                return (v1 > v2) ? -1 : 1;
11571            }
11572            if (r1.system != r2.system) {
11573                return r1.system ? -1 : 1;
11574            }
11575            if (r1.activityInfo != null) {
11576                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11577            }
11578            if (r1.serviceInfo != null) {
11579                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11580            }
11581            if (r1.providerInfo != null) {
11582                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11583            }
11584            return 0;
11585        }
11586    };
11587
11588    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11589            new Comparator<ProviderInfo>() {
11590        public int compare(ProviderInfo p1, ProviderInfo p2) {
11591            final int v1 = p1.initOrder;
11592            final int v2 = p2.initOrder;
11593            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11594        }
11595    };
11596
11597    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11598            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11599            final int[] userIds) {
11600        mHandler.post(new Runnable() {
11601            @Override
11602            public void run() {
11603                try {
11604                    final IActivityManager am = ActivityManager.getService();
11605                    if (am == null) return;
11606                    final int[] resolvedUserIds;
11607                    if (userIds == null) {
11608                        resolvedUserIds = am.getRunningUserIds();
11609                    } else {
11610                        resolvedUserIds = userIds;
11611                    }
11612                    for (int id : resolvedUserIds) {
11613                        final Intent intent = new Intent(action,
11614                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11615                        if (extras != null) {
11616                            intent.putExtras(extras);
11617                        }
11618                        if (targetPkg != null) {
11619                            intent.setPackage(targetPkg);
11620                        }
11621                        // Modify the UID when posting to other users
11622                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11623                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11624                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11625                            intent.putExtra(Intent.EXTRA_UID, uid);
11626                        }
11627                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11628                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11629                        if (DEBUG_BROADCASTS) {
11630                            RuntimeException here = new RuntimeException("here");
11631                            here.fillInStackTrace();
11632                            Slog.d(TAG, "Sending to user " + id + ": "
11633                                    + intent.toShortString(false, true, false, false)
11634                                    + " " + intent.getExtras(), here);
11635                        }
11636                        am.broadcastIntent(null, intent, null, finishedReceiver,
11637                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11638                                null, finishedReceiver != null, false, id);
11639                    }
11640                } catch (RemoteException ex) {
11641                }
11642            }
11643        });
11644    }
11645
11646    /**
11647     * Check if the external storage media is available. This is true if there
11648     * is a mounted external storage medium or if the external storage is
11649     * emulated.
11650     */
11651    private boolean isExternalMediaAvailable() {
11652        return mMediaMounted || Environment.isExternalStorageEmulated();
11653    }
11654
11655    @Override
11656    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11657        // writer
11658        synchronized (mPackages) {
11659            if (!isExternalMediaAvailable()) {
11660                // If the external storage is no longer mounted at this point,
11661                // the caller may not have been able to delete all of this
11662                // packages files and can not delete any more.  Bail.
11663                return null;
11664            }
11665            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11666            if (lastPackage != null) {
11667                pkgs.remove(lastPackage);
11668            }
11669            if (pkgs.size() > 0) {
11670                return pkgs.get(0);
11671            }
11672        }
11673        return null;
11674    }
11675
11676    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11677        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11678                userId, andCode ? 1 : 0, packageName);
11679        if (mSystemReady) {
11680            msg.sendToTarget();
11681        } else {
11682            if (mPostSystemReadyMessages == null) {
11683                mPostSystemReadyMessages = new ArrayList<>();
11684            }
11685            mPostSystemReadyMessages.add(msg);
11686        }
11687    }
11688
11689    void startCleaningPackages() {
11690        // reader
11691        if (!isExternalMediaAvailable()) {
11692            return;
11693        }
11694        synchronized (mPackages) {
11695            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11696                return;
11697            }
11698        }
11699        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11700        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11701        IActivityManager am = ActivityManager.getService();
11702        if (am != null) {
11703            try {
11704                am.startService(null, intent, null, mContext.getOpPackageName(),
11705                        UserHandle.USER_SYSTEM);
11706            } catch (RemoteException e) {
11707            }
11708        }
11709    }
11710
11711    @Override
11712    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11713            int installFlags, String installerPackageName, int userId) {
11714        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11715
11716        final int callingUid = Binder.getCallingUid();
11717        enforceCrossUserPermission(callingUid, userId,
11718                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11719
11720        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11721            try {
11722                if (observer != null) {
11723                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11724                }
11725            } catch (RemoteException re) {
11726            }
11727            return;
11728        }
11729
11730        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11731            installFlags |= PackageManager.INSTALL_FROM_ADB;
11732
11733        } else {
11734            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11735            // about installerPackageName.
11736
11737            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11738            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11739        }
11740
11741        UserHandle user;
11742        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11743            user = UserHandle.ALL;
11744        } else {
11745            user = new UserHandle(userId);
11746        }
11747
11748        // Only system components can circumvent runtime permissions when installing.
11749        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11750                && mContext.checkCallingOrSelfPermission(Manifest.permission
11751                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11752            throw new SecurityException("You need the "
11753                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11754                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11755        }
11756
11757        final File originFile = new File(originPath);
11758        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11759
11760        final Message msg = mHandler.obtainMessage(INIT_COPY);
11761        final VerificationInfo verificationInfo = new VerificationInfo(
11762                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11763        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11764                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11765                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11766                null /*certificates*/);
11767        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11768        msg.obj = params;
11769
11770        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11771                System.identityHashCode(msg.obj));
11772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11773                System.identityHashCode(msg.obj));
11774
11775        mHandler.sendMessage(msg);
11776    }
11777
11778    void installStage(String packageName, File stagedDir, String stagedCid,
11779            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11780            String installerPackageName, int installerUid, UserHandle user,
11781            Certificate[][] certificates) {
11782        if (DEBUG_EPHEMERAL) {
11783            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11784                Slog.d(TAG, "Ephemeral install of " + packageName);
11785            }
11786        }
11787        final VerificationInfo verificationInfo = new VerificationInfo(
11788                sessionParams.originatingUri, sessionParams.referrerUri,
11789                sessionParams.originatingUid, installerUid);
11790
11791        final OriginInfo origin;
11792        if (stagedDir != null) {
11793            origin = OriginInfo.fromStagedFile(stagedDir);
11794        } else {
11795            origin = OriginInfo.fromStagedContainer(stagedCid);
11796        }
11797
11798        final Message msg = mHandler.obtainMessage(INIT_COPY);
11799        final InstallParams params = new InstallParams(origin, null, observer,
11800                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11801                verificationInfo, user, sessionParams.abiOverride,
11802                sessionParams.grantedRuntimePermissions, certificates);
11803        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11804        msg.obj = params;
11805
11806        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11807                System.identityHashCode(msg.obj));
11808        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11809                System.identityHashCode(msg.obj));
11810
11811        mHandler.sendMessage(msg);
11812    }
11813
11814    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11815            int userId) {
11816        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11817        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11818    }
11819
11820    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11821            int appId, int... userIds) {
11822        if (ArrayUtils.isEmpty(userIds)) {
11823            return;
11824        }
11825        Bundle extras = new Bundle(1);
11826        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11827        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11828
11829        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11830                packageName, extras, 0, null, null, userIds);
11831        if (isSystem) {
11832            mHandler.post(() -> {
11833                        for (int userId : userIds) {
11834                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
11835                        }
11836                    }
11837            );
11838        }
11839    }
11840
11841    /**
11842     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
11843     * automatically without needing an explicit launch.
11844     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
11845     */
11846    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
11847        // If user is not running, the app didn't miss any broadcast
11848        if (!mUserManagerInternal.isUserRunning(userId)) {
11849            return;
11850        }
11851        final IActivityManager am = ActivityManager.getService();
11852        try {
11853            // Deliver LOCKED_BOOT_COMPLETED first
11854            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
11855                    .setPackage(packageName);
11856            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
11857            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
11858                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11859
11860            // Deliver BOOT_COMPLETED only if user is unlocked
11861            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
11862                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
11863                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
11864                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11865            }
11866        } catch (RemoteException e) {
11867            throw e.rethrowFromSystemServer();
11868        }
11869    }
11870
11871    @Override
11872    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11873            int userId) {
11874        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11875        PackageSetting pkgSetting;
11876        final int uid = Binder.getCallingUid();
11877        enforceCrossUserPermission(uid, userId,
11878                true /* requireFullPermission */, true /* checkShell */,
11879                "setApplicationHiddenSetting for user " + userId);
11880
11881        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11882            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11883            return false;
11884        }
11885
11886        long callingId = Binder.clearCallingIdentity();
11887        try {
11888            boolean sendAdded = false;
11889            boolean sendRemoved = false;
11890            // writer
11891            synchronized (mPackages) {
11892                pkgSetting = mSettings.mPackages.get(packageName);
11893                if (pkgSetting == null) {
11894                    return false;
11895                }
11896                // Do not allow "android" is being disabled
11897                if ("android".equals(packageName)) {
11898                    Slog.w(TAG, "Cannot hide package: android");
11899                    return false;
11900                }
11901                // Only allow protected packages to hide themselves.
11902                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11903                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11904                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11905                    return false;
11906                }
11907
11908                if (pkgSetting.getHidden(userId) != hidden) {
11909                    pkgSetting.setHidden(hidden, userId);
11910                    mSettings.writePackageRestrictionsLPr(userId);
11911                    if (hidden) {
11912                        sendRemoved = true;
11913                    } else {
11914                        sendAdded = true;
11915                    }
11916                }
11917            }
11918            if (sendAdded) {
11919                sendPackageAddedForUser(packageName, pkgSetting, userId);
11920                return true;
11921            }
11922            if (sendRemoved) {
11923                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11924                        "hiding pkg");
11925                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11926                return true;
11927            }
11928        } finally {
11929            Binder.restoreCallingIdentity(callingId);
11930        }
11931        return false;
11932    }
11933
11934    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11935            int userId) {
11936        final PackageRemovedInfo info = new PackageRemovedInfo();
11937        info.removedPackage = packageName;
11938        info.removedUsers = new int[] {userId};
11939        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11940        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11941    }
11942
11943    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11944        if (pkgList.length > 0) {
11945            Bundle extras = new Bundle(1);
11946            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11947
11948            sendPackageBroadcast(
11949                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11950                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11951                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11952                    new int[] {userId});
11953        }
11954    }
11955
11956    /**
11957     * Returns true if application is not found or there was an error. Otherwise it returns
11958     * the hidden state of the package for the given user.
11959     */
11960    @Override
11961    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11962        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11963        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11964                true /* requireFullPermission */, false /* checkShell */,
11965                "getApplicationHidden for user " + userId);
11966        PackageSetting pkgSetting;
11967        long callingId = Binder.clearCallingIdentity();
11968        try {
11969            // writer
11970            synchronized (mPackages) {
11971                pkgSetting = mSettings.mPackages.get(packageName);
11972                if (pkgSetting == null) {
11973                    return true;
11974                }
11975                return pkgSetting.getHidden(userId);
11976            }
11977        } finally {
11978            Binder.restoreCallingIdentity(callingId);
11979        }
11980    }
11981
11982    /**
11983     * @hide
11984     */
11985    @Override
11986    public int installExistingPackageAsUser(String packageName, int userId) {
11987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11988                null);
11989        PackageSetting pkgSetting;
11990        final int uid = Binder.getCallingUid();
11991        enforceCrossUserPermission(uid, userId,
11992                true /* requireFullPermission */, true /* checkShell */,
11993                "installExistingPackage for user " + userId);
11994        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11995            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11996        }
11997
11998        long callingId = Binder.clearCallingIdentity();
11999        try {
12000            boolean installed = false;
12001
12002            // writer
12003            synchronized (mPackages) {
12004                pkgSetting = mSettings.mPackages.get(packageName);
12005                if (pkgSetting == null) {
12006                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12007                }
12008                if (!pkgSetting.getInstalled(userId)) {
12009                    pkgSetting.setInstalled(true, userId);
12010                    pkgSetting.setHidden(false, userId);
12011                    mSettings.writePackageRestrictionsLPr(userId);
12012                    installed = true;
12013                }
12014            }
12015
12016            if (installed) {
12017                if (pkgSetting.pkg != null) {
12018                    synchronized (mInstallLock) {
12019                        // We don't need to freeze for a brand new install
12020                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12021                    }
12022                }
12023                sendPackageAddedForUser(packageName, pkgSetting, userId);
12024            }
12025        } finally {
12026            Binder.restoreCallingIdentity(callingId);
12027        }
12028
12029        return PackageManager.INSTALL_SUCCEEDED;
12030    }
12031
12032    boolean isUserRestricted(int userId, String restrictionKey) {
12033        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12034        if (restrictions.getBoolean(restrictionKey, false)) {
12035            Log.w(TAG, "User is restricted: " + restrictionKey);
12036            return true;
12037        }
12038        return false;
12039    }
12040
12041    @Override
12042    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12043            int userId) {
12044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12046                true /* requireFullPermission */, true /* checkShell */,
12047                "setPackagesSuspended for user " + userId);
12048
12049        if (ArrayUtils.isEmpty(packageNames)) {
12050            return packageNames;
12051        }
12052
12053        // List of package names for whom the suspended state has changed.
12054        List<String> changedPackages = new ArrayList<>(packageNames.length);
12055        // List of package names for whom the suspended state is not set as requested in this
12056        // method.
12057        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12058        long callingId = Binder.clearCallingIdentity();
12059        try {
12060            for (int i = 0; i < packageNames.length; i++) {
12061                String packageName = packageNames[i];
12062                boolean changed = false;
12063                final int appId;
12064                synchronized (mPackages) {
12065                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12066                    if (pkgSetting == null) {
12067                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12068                                + "\". Skipping suspending/un-suspending.");
12069                        unactionedPackages.add(packageName);
12070                        continue;
12071                    }
12072                    appId = pkgSetting.appId;
12073                    if (pkgSetting.getSuspended(userId) != suspended) {
12074                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12075                            unactionedPackages.add(packageName);
12076                            continue;
12077                        }
12078                        pkgSetting.setSuspended(suspended, userId);
12079                        mSettings.writePackageRestrictionsLPr(userId);
12080                        changed = true;
12081                        changedPackages.add(packageName);
12082                    }
12083                }
12084
12085                if (changed && suspended) {
12086                    killApplication(packageName, UserHandle.getUid(userId, appId),
12087                            "suspending package");
12088                }
12089            }
12090        } finally {
12091            Binder.restoreCallingIdentity(callingId);
12092        }
12093
12094        if (!changedPackages.isEmpty()) {
12095            sendPackagesSuspendedForUser(changedPackages.toArray(
12096                    new String[changedPackages.size()]), userId, suspended);
12097        }
12098
12099        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12100    }
12101
12102    @Override
12103    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12104        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12105                true /* requireFullPermission */, false /* checkShell */,
12106                "isPackageSuspendedForUser for user " + userId);
12107        synchronized (mPackages) {
12108            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12109            if (pkgSetting == null) {
12110                throw new IllegalArgumentException("Unknown target package: " + packageName);
12111            }
12112            return pkgSetting.getSuspended(userId);
12113        }
12114    }
12115
12116    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12117        if (isPackageDeviceAdmin(packageName, userId)) {
12118            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12119                    + "\": has an active device admin");
12120            return false;
12121        }
12122
12123        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12124        if (packageName.equals(activeLauncherPackageName)) {
12125            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12126                    + "\": contains the active launcher");
12127            return false;
12128        }
12129
12130        if (packageName.equals(mRequiredInstallerPackage)) {
12131            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12132                    + "\": required for package installation");
12133            return false;
12134        }
12135
12136        if (packageName.equals(mRequiredUninstallerPackage)) {
12137            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12138                    + "\": required for package uninstallation");
12139            return false;
12140        }
12141
12142        if (packageName.equals(mRequiredVerifierPackage)) {
12143            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12144                    + "\": required for package verification");
12145            return false;
12146        }
12147
12148        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12149            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12150                    + "\": is the default dialer");
12151            return false;
12152        }
12153
12154        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12155            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12156                    + "\": protected package");
12157            return false;
12158        }
12159
12160        return true;
12161    }
12162
12163    private String getActiveLauncherPackageName(int userId) {
12164        Intent intent = new Intent(Intent.ACTION_MAIN);
12165        intent.addCategory(Intent.CATEGORY_HOME);
12166        ResolveInfo resolveInfo = resolveIntent(
12167                intent,
12168                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12169                PackageManager.MATCH_DEFAULT_ONLY,
12170                userId);
12171
12172        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12173    }
12174
12175    private String getDefaultDialerPackageName(int userId) {
12176        synchronized (mPackages) {
12177            return mSettings.getDefaultDialerPackageNameLPw(userId);
12178        }
12179    }
12180
12181    @Override
12182    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12183        mContext.enforceCallingOrSelfPermission(
12184                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12185                "Only package verification agents can verify applications");
12186
12187        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12188        final PackageVerificationResponse response = new PackageVerificationResponse(
12189                verificationCode, Binder.getCallingUid());
12190        msg.arg1 = id;
12191        msg.obj = response;
12192        mHandler.sendMessage(msg);
12193    }
12194
12195    @Override
12196    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12197            long millisecondsToDelay) {
12198        mContext.enforceCallingOrSelfPermission(
12199                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12200                "Only package verification agents can extend verification timeouts");
12201
12202        final PackageVerificationState state = mPendingVerification.get(id);
12203        final PackageVerificationResponse response = new PackageVerificationResponse(
12204                verificationCodeAtTimeout, Binder.getCallingUid());
12205
12206        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12207            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12208        }
12209        if (millisecondsToDelay < 0) {
12210            millisecondsToDelay = 0;
12211        }
12212        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12213                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12214            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12215        }
12216
12217        if ((state != null) && !state.timeoutExtended()) {
12218            state.extendTimeout();
12219
12220            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12221            msg.arg1 = id;
12222            msg.obj = response;
12223            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12224        }
12225    }
12226
12227    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12228            int verificationCode, UserHandle user) {
12229        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12230        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12231        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12232        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12233        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12234
12235        mContext.sendBroadcastAsUser(intent, user,
12236                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12237    }
12238
12239    private ComponentName matchComponentForVerifier(String packageName,
12240            List<ResolveInfo> receivers) {
12241        ActivityInfo targetReceiver = null;
12242
12243        final int NR = receivers.size();
12244        for (int i = 0; i < NR; i++) {
12245            final ResolveInfo info = receivers.get(i);
12246            if (info.activityInfo == null) {
12247                continue;
12248            }
12249
12250            if (packageName.equals(info.activityInfo.packageName)) {
12251                targetReceiver = info.activityInfo;
12252                break;
12253            }
12254        }
12255
12256        if (targetReceiver == null) {
12257            return null;
12258        }
12259
12260        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12261    }
12262
12263    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12264            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12265        if (pkgInfo.verifiers.length == 0) {
12266            return null;
12267        }
12268
12269        final int N = pkgInfo.verifiers.length;
12270        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12271        for (int i = 0; i < N; i++) {
12272            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12273
12274            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12275                    receivers);
12276            if (comp == null) {
12277                continue;
12278            }
12279
12280            final int verifierUid = getUidForVerifier(verifierInfo);
12281            if (verifierUid == -1) {
12282                continue;
12283            }
12284
12285            if (DEBUG_VERIFY) {
12286                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12287                        + " with the correct signature");
12288            }
12289            sufficientVerifiers.add(comp);
12290            verificationState.addSufficientVerifier(verifierUid);
12291        }
12292
12293        return sufficientVerifiers;
12294    }
12295
12296    private int getUidForVerifier(VerifierInfo verifierInfo) {
12297        synchronized (mPackages) {
12298            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12299            if (pkg == null) {
12300                return -1;
12301            } else if (pkg.mSignatures.length != 1) {
12302                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12303                        + " has more than one signature; ignoring");
12304                return -1;
12305            }
12306
12307            /*
12308             * If the public key of the package's signature does not match
12309             * our expected public key, then this is a different package and
12310             * we should skip.
12311             */
12312
12313            final byte[] expectedPublicKey;
12314            try {
12315                final Signature verifierSig = pkg.mSignatures[0];
12316                final PublicKey publicKey = verifierSig.getPublicKey();
12317                expectedPublicKey = publicKey.getEncoded();
12318            } catch (CertificateException e) {
12319                return -1;
12320            }
12321
12322            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12323
12324            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12325                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12326                        + " does not have the expected public key; ignoring");
12327                return -1;
12328            }
12329
12330            return pkg.applicationInfo.uid;
12331        }
12332    }
12333
12334    @Override
12335    public void finishPackageInstall(int token, boolean didLaunch) {
12336        enforceSystemOrRoot("Only the system is allowed to finish installs");
12337
12338        if (DEBUG_INSTALL) {
12339            Slog.v(TAG, "BM finishing package install for " + token);
12340        }
12341        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12342
12343        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12344        mHandler.sendMessage(msg);
12345    }
12346
12347    /**
12348     * Get the verification agent timeout.
12349     *
12350     * @return verification timeout in milliseconds
12351     */
12352    private long getVerificationTimeout() {
12353        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12354                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12355                DEFAULT_VERIFICATION_TIMEOUT);
12356    }
12357
12358    /**
12359     * Get the default verification agent response code.
12360     *
12361     * @return default verification response code
12362     */
12363    private int getDefaultVerificationResponse() {
12364        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12365                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12366                DEFAULT_VERIFICATION_RESPONSE);
12367    }
12368
12369    /**
12370     * Check whether or not package verification has been enabled.
12371     *
12372     * @return true if verification should be performed
12373     */
12374    private boolean isVerificationEnabled(int userId, int installFlags) {
12375        if (!DEFAULT_VERIFY_ENABLE) {
12376            return false;
12377        }
12378        // Ephemeral apps don't get the full verification treatment
12379        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12380            if (DEBUG_EPHEMERAL) {
12381                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12382            }
12383            return false;
12384        }
12385
12386        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12387
12388        // Check if installing from ADB
12389        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12390            // Do not run verification in a test harness environment
12391            if (ActivityManager.isRunningInTestHarness()) {
12392                return false;
12393            }
12394            if (ensureVerifyAppsEnabled) {
12395                return true;
12396            }
12397            // Check if the developer does not want package verification for ADB installs
12398            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12399                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12400                return false;
12401            }
12402        }
12403
12404        if (ensureVerifyAppsEnabled) {
12405            return true;
12406        }
12407
12408        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12409                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12410    }
12411
12412    @Override
12413    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12414            throws RemoteException {
12415        mContext.enforceCallingOrSelfPermission(
12416                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12417                "Only intentfilter verification agents can verify applications");
12418
12419        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12420        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12421                Binder.getCallingUid(), verificationCode, failedDomains);
12422        msg.arg1 = id;
12423        msg.obj = response;
12424        mHandler.sendMessage(msg);
12425    }
12426
12427    @Override
12428    public int getIntentVerificationStatus(String packageName, int userId) {
12429        synchronized (mPackages) {
12430            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12431        }
12432    }
12433
12434    @Override
12435    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12436        mContext.enforceCallingOrSelfPermission(
12437                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12438
12439        boolean result = false;
12440        synchronized (mPackages) {
12441            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12442        }
12443        if (result) {
12444            scheduleWritePackageRestrictionsLocked(userId);
12445        }
12446        return result;
12447    }
12448
12449    @Override
12450    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12451            String packageName) {
12452        synchronized (mPackages) {
12453            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12454        }
12455    }
12456
12457    @Override
12458    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12459        if (TextUtils.isEmpty(packageName)) {
12460            return ParceledListSlice.emptyList();
12461        }
12462        synchronized (mPackages) {
12463            PackageParser.Package pkg = mPackages.get(packageName);
12464            if (pkg == null || pkg.activities == null) {
12465                return ParceledListSlice.emptyList();
12466            }
12467            final int count = pkg.activities.size();
12468            ArrayList<IntentFilter> result = new ArrayList<>();
12469            for (int n=0; n<count; n++) {
12470                PackageParser.Activity activity = pkg.activities.get(n);
12471                if (activity.intents != null && activity.intents.size() > 0) {
12472                    result.addAll(activity.intents);
12473                }
12474            }
12475            return new ParceledListSlice<>(result);
12476        }
12477    }
12478
12479    @Override
12480    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12481        mContext.enforceCallingOrSelfPermission(
12482                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12483
12484        synchronized (mPackages) {
12485            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12486            if (packageName != null) {
12487                result |= updateIntentVerificationStatus(packageName,
12488                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12489                        userId);
12490                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12491                        packageName, userId);
12492            }
12493            return result;
12494        }
12495    }
12496
12497    @Override
12498    public String getDefaultBrowserPackageName(int userId) {
12499        synchronized (mPackages) {
12500            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12501        }
12502    }
12503
12504    /**
12505     * Get the "allow unknown sources" setting.
12506     *
12507     * @return the current "allow unknown sources" setting
12508     */
12509    private int getUnknownSourcesSettings() {
12510        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12511                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12512                -1);
12513    }
12514
12515    @Override
12516    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12517        final int uid = Binder.getCallingUid();
12518        // writer
12519        synchronized (mPackages) {
12520            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12521            if (targetPackageSetting == null) {
12522                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12523            }
12524
12525            PackageSetting installerPackageSetting;
12526            if (installerPackageName != null) {
12527                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12528                if (installerPackageSetting == null) {
12529                    throw new IllegalArgumentException("Unknown installer package: "
12530                            + installerPackageName);
12531                }
12532            } else {
12533                installerPackageSetting = null;
12534            }
12535
12536            Signature[] callerSignature;
12537            Object obj = mSettings.getUserIdLPr(uid);
12538            if (obj != null) {
12539                if (obj instanceof SharedUserSetting) {
12540                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12541                } else if (obj instanceof PackageSetting) {
12542                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12543                } else {
12544                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12545                }
12546            } else {
12547                throw new SecurityException("Unknown calling UID: " + uid);
12548            }
12549
12550            // Verify: can't set installerPackageName to a package that is
12551            // not signed with the same cert as the caller.
12552            if (installerPackageSetting != null) {
12553                if (compareSignatures(callerSignature,
12554                        installerPackageSetting.signatures.mSignatures)
12555                        != PackageManager.SIGNATURE_MATCH) {
12556                    throw new SecurityException(
12557                            "Caller does not have same cert as new installer package "
12558                            + installerPackageName);
12559                }
12560            }
12561
12562            // Verify: if target already has an installer package, it must
12563            // be signed with the same cert as the caller.
12564            if (targetPackageSetting.installerPackageName != null) {
12565                PackageSetting setting = mSettings.mPackages.get(
12566                        targetPackageSetting.installerPackageName);
12567                // If the currently set package isn't valid, then it's always
12568                // okay to change it.
12569                if (setting != null) {
12570                    if (compareSignatures(callerSignature,
12571                            setting.signatures.mSignatures)
12572                            != PackageManager.SIGNATURE_MATCH) {
12573                        throw new SecurityException(
12574                                "Caller does not have same cert as old installer package "
12575                                + targetPackageSetting.installerPackageName);
12576                    }
12577                }
12578            }
12579
12580            // Okay!
12581            targetPackageSetting.installerPackageName = installerPackageName;
12582            if (installerPackageName != null) {
12583                mSettings.mInstallerPackages.add(installerPackageName);
12584            }
12585            scheduleWriteSettingsLocked();
12586        }
12587    }
12588
12589    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12590        // Queue up an async operation since the package installation may take a little while.
12591        mHandler.post(new Runnable() {
12592            public void run() {
12593                mHandler.removeCallbacks(this);
12594                 // Result object to be returned
12595                PackageInstalledInfo res = new PackageInstalledInfo();
12596                res.setReturnCode(currentStatus);
12597                res.uid = -1;
12598                res.pkg = null;
12599                res.removedInfo = null;
12600                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12601                    args.doPreInstall(res.returnCode);
12602                    synchronized (mInstallLock) {
12603                        installPackageTracedLI(args, res);
12604                    }
12605                    args.doPostInstall(res.returnCode, res.uid);
12606                }
12607
12608                // A restore should be performed at this point if (a) the install
12609                // succeeded, (b) the operation is not an update, and (c) the new
12610                // package has not opted out of backup participation.
12611                final boolean update = res.removedInfo != null
12612                        && res.removedInfo.removedPackage != null;
12613                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12614                boolean doRestore = !update
12615                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12616
12617                // Set up the post-install work request bookkeeping.  This will be used
12618                // and cleaned up by the post-install event handling regardless of whether
12619                // there's a restore pass performed.  Token values are >= 1.
12620                int token;
12621                if (mNextInstallToken < 0) mNextInstallToken = 1;
12622                token = mNextInstallToken++;
12623
12624                PostInstallData data = new PostInstallData(args, res);
12625                mRunningInstalls.put(token, data);
12626                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12627
12628                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12629                    // Pass responsibility to the Backup Manager.  It will perform a
12630                    // restore if appropriate, then pass responsibility back to the
12631                    // Package Manager to run the post-install observer callbacks
12632                    // and broadcasts.
12633                    IBackupManager bm = IBackupManager.Stub.asInterface(
12634                            ServiceManager.getService(Context.BACKUP_SERVICE));
12635                    if (bm != null) {
12636                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12637                                + " to BM for possible restore");
12638                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12639                        try {
12640                            // TODO: http://b/22388012
12641                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12642                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12643                            } else {
12644                                doRestore = false;
12645                            }
12646                        } catch (RemoteException e) {
12647                            // can't happen; the backup manager is local
12648                        } catch (Exception e) {
12649                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12650                            doRestore = false;
12651                        }
12652                    } else {
12653                        Slog.e(TAG, "Backup Manager not found!");
12654                        doRestore = false;
12655                    }
12656                }
12657
12658                if (!doRestore) {
12659                    // No restore possible, or the Backup Manager was mysteriously not
12660                    // available -- just fire the post-install work request directly.
12661                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12662
12663                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12664
12665                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12666                    mHandler.sendMessage(msg);
12667                }
12668            }
12669        });
12670    }
12671
12672    /**
12673     * Callback from PackageSettings whenever an app is first transitioned out of the
12674     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12675     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12676     * here whether the app is the target of an ongoing install, and only send the
12677     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12678     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12679     * handling.
12680     */
12681    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12682        // Serialize this with the rest of the install-process message chain.  In the
12683        // restore-at-install case, this Runnable will necessarily run before the
12684        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12685        // are coherent.  In the non-restore case, the app has already completed install
12686        // and been launched through some other means, so it is not in a problematic
12687        // state for observers to see the FIRST_LAUNCH signal.
12688        mHandler.post(new Runnable() {
12689            @Override
12690            public void run() {
12691                for (int i = 0; i < mRunningInstalls.size(); i++) {
12692                    final PostInstallData data = mRunningInstalls.valueAt(i);
12693                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12694                        continue;
12695                    }
12696                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12697                        // right package; but is it for the right user?
12698                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12699                            if (userId == data.res.newUsers[uIndex]) {
12700                                if (DEBUG_BACKUP) {
12701                                    Slog.i(TAG, "Package " + pkgName
12702                                            + " being restored so deferring FIRST_LAUNCH");
12703                                }
12704                                return;
12705                            }
12706                        }
12707                    }
12708                }
12709                // didn't find it, so not being restored
12710                if (DEBUG_BACKUP) {
12711                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12712                }
12713                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12714            }
12715        });
12716    }
12717
12718    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12719        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12720                installerPkg, null, userIds);
12721    }
12722
12723    private abstract class HandlerParams {
12724        private static final int MAX_RETRIES = 4;
12725
12726        /**
12727         * Number of times startCopy() has been attempted and had a non-fatal
12728         * error.
12729         */
12730        private int mRetries = 0;
12731
12732        /** User handle for the user requesting the information or installation. */
12733        private final UserHandle mUser;
12734        String traceMethod;
12735        int traceCookie;
12736
12737        HandlerParams(UserHandle user) {
12738            mUser = user;
12739        }
12740
12741        UserHandle getUser() {
12742            return mUser;
12743        }
12744
12745        HandlerParams setTraceMethod(String traceMethod) {
12746            this.traceMethod = traceMethod;
12747            return this;
12748        }
12749
12750        HandlerParams setTraceCookie(int traceCookie) {
12751            this.traceCookie = traceCookie;
12752            return this;
12753        }
12754
12755        final boolean startCopy() {
12756            boolean res;
12757            try {
12758                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12759
12760                if (++mRetries > MAX_RETRIES) {
12761                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12762                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12763                    handleServiceError();
12764                    return false;
12765                } else {
12766                    handleStartCopy();
12767                    res = true;
12768                }
12769            } catch (RemoteException e) {
12770                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12771                mHandler.sendEmptyMessage(MCS_RECONNECT);
12772                res = false;
12773            }
12774            handleReturnCode();
12775            return res;
12776        }
12777
12778        final void serviceError() {
12779            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12780            handleServiceError();
12781            handleReturnCode();
12782        }
12783
12784        abstract void handleStartCopy() throws RemoteException;
12785        abstract void handleServiceError();
12786        abstract void handleReturnCode();
12787    }
12788
12789    class MeasureParams extends HandlerParams {
12790        private final PackageStats mStats;
12791        private boolean mSuccess;
12792
12793        private final IPackageStatsObserver mObserver;
12794
12795        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12796            super(new UserHandle(stats.userHandle));
12797            mObserver = observer;
12798            mStats = stats;
12799        }
12800
12801        @Override
12802        public String toString() {
12803            return "MeasureParams{"
12804                + Integer.toHexString(System.identityHashCode(this))
12805                + " " + mStats.packageName + "}";
12806        }
12807
12808        @Override
12809        void handleStartCopy() throws RemoteException {
12810            synchronized (mInstallLock) {
12811                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12812            }
12813
12814            if (mSuccess) {
12815                boolean mounted = false;
12816                try {
12817                    final String status = Environment.getExternalStorageState();
12818                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12819                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12820                } catch (Exception e) {
12821                }
12822
12823                if (mounted) {
12824                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12825
12826                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12827                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12828
12829                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12830                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12831
12832                    // Always subtract cache size, since it's a subdirectory
12833                    mStats.externalDataSize -= mStats.externalCacheSize;
12834
12835                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12836                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12837
12838                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12839                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12840                }
12841            }
12842        }
12843
12844        @Override
12845        void handleReturnCode() {
12846            if (mObserver != null) {
12847                try {
12848                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12849                } catch (RemoteException e) {
12850                    Slog.i(TAG, "Observer no longer exists.");
12851                }
12852            }
12853        }
12854
12855        @Override
12856        void handleServiceError() {
12857            Slog.e(TAG, "Could not measure application " + mStats.packageName
12858                            + " external storage");
12859        }
12860    }
12861
12862    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12863            throws RemoteException {
12864        long result = 0;
12865        for (File path : paths) {
12866            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12867        }
12868        return result;
12869    }
12870
12871    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12872        for (File path : paths) {
12873            try {
12874                mcs.clearDirectory(path.getAbsolutePath());
12875            } catch (RemoteException e) {
12876            }
12877        }
12878    }
12879
12880    static class OriginInfo {
12881        /**
12882         * Location where install is coming from, before it has been
12883         * copied/renamed into place. This could be a single monolithic APK
12884         * file, or a cluster directory. This location may be untrusted.
12885         */
12886        final File file;
12887        final String cid;
12888
12889        /**
12890         * Flag indicating that {@link #file} or {@link #cid} has already been
12891         * staged, meaning downstream users don't need to defensively copy the
12892         * contents.
12893         */
12894        final boolean staged;
12895
12896        /**
12897         * Flag indicating that {@link #file} or {@link #cid} is an already
12898         * installed app that is being moved.
12899         */
12900        final boolean existing;
12901
12902        final String resolvedPath;
12903        final File resolvedFile;
12904
12905        static OriginInfo fromNothing() {
12906            return new OriginInfo(null, null, false, false);
12907        }
12908
12909        static OriginInfo fromUntrustedFile(File file) {
12910            return new OriginInfo(file, null, false, false);
12911        }
12912
12913        static OriginInfo fromExistingFile(File file) {
12914            return new OriginInfo(file, null, false, true);
12915        }
12916
12917        static OriginInfo fromStagedFile(File file) {
12918            return new OriginInfo(file, null, true, false);
12919        }
12920
12921        static OriginInfo fromStagedContainer(String cid) {
12922            return new OriginInfo(null, cid, true, false);
12923        }
12924
12925        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12926            this.file = file;
12927            this.cid = cid;
12928            this.staged = staged;
12929            this.existing = existing;
12930
12931            if (cid != null) {
12932                resolvedPath = PackageHelper.getSdDir(cid);
12933                resolvedFile = new File(resolvedPath);
12934            } else if (file != null) {
12935                resolvedPath = file.getAbsolutePath();
12936                resolvedFile = file;
12937            } else {
12938                resolvedPath = null;
12939                resolvedFile = null;
12940            }
12941        }
12942    }
12943
12944    static class MoveInfo {
12945        final int moveId;
12946        final String fromUuid;
12947        final String toUuid;
12948        final String packageName;
12949        final String dataAppName;
12950        final int appId;
12951        final String seinfo;
12952        final int targetSdkVersion;
12953
12954        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12955                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12956            this.moveId = moveId;
12957            this.fromUuid = fromUuid;
12958            this.toUuid = toUuid;
12959            this.packageName = packageName;
12960            this.dataAppName = dataAppName;
12961            this.appId = appId;
12962            this.seinfo = seinfo;
12963            this.targetSdkVersion = targetSdkVersion;
12964        }
12965    }
12966
12967    static class VerificationInfo {
12968        /** A constant used to indicate that a uid value is not present. */
12969        public static final int NO_UID = -1;
12970
12971        /** URI referencing where the package was downloaded from. */
12972        final Uri originatingUri;
12973
12974        /** HTTP referrer URI associated with the originatingURI. */
12975        final Uri referrer;
12976
12977        /** UID of the application that the install request originated from. */
12978        final int originatingUid;
12979
12980        /** UID of application requesting the install */
12981        final int installerUid;
12982
12983        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12984            this.originatingUri = originatingUri;
12985            this.referrer = referrer;
12986            this.originatingUid = originatingUid;
12987            this.installerUid = installerUid;
12988        }
12989    }
12990
12991    class InstallParams extends HandlerParams {
12992        final OriginInfo origin;
12993        final MoveInfo move;
12994        final IPackageInstallObserver2 observer;
12995        int installFlags;
12996        final String installerPackageName;
12997        final String volumeUuid;
12998        private InstallArgs mArgs;
12999        private int mRet;
13000        final String packageAbiOverride;
13001        final String[] grantedRuntimePermissions;
13002        final VerificationInfo verificationInfo;
13003        final Certificate[][] certificates;
13004
13005        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13006                int installFlags, String installerPackageName, String volumeUuid,
13007                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13008                String[] grantedPermissions, Certificate[][] certificates) {
13009            super(user);
13010            this.origin = origin;
13011            this.move = move;
13012            this.observer = observer;
13013            this.installFlags = installFlags;
13014            this.installerPackageName = installerPackageName;
13015            this.volumeUuid = volumeUuid;
13016            this.verificationInfo = verificationInfo;
13017            this.packageAbiOverride = packageAbiOverride;
13018            this.grantedRuntimePermissions = grantedPermissions;
13019            this.certificates = certificates;
13020        }
13021
13022        @Override
13023        public String toString() {
13024            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13025                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13026        }
13027
13028        private int installLocationPolicy(PackageInfoLite pkgLite) {
13029            String packageName = pkgLite.packageName;
13030            int installLocation = pkgLite.installLocation;
13031            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13032            // reader
13033            synchronized (mPackages) {
13034                // Currently installed package which the new package is attempting to replace or
13035                // null if no such package is installed.
13036                PackageParser.Package installedPkg = mPackages.get(packageName);
13037                // Package which currently owns the data which the new package will own if installed.
13038                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13039                // will be null whereas dataOwnerPkg will contain information about the package
13040                // which was uninstalled while keeping its data.
13041                PackageParser.Package dataOwnerPkg = installedPkg;
13042                if (dataOwnerPkg  == null) {
13043                    PackageSetting ps = mSettings.mPackages.get(packageName);
13044                    if (ps != null) {
13045                        dataOwnerPkg = ps.pkg;
13046                    }
13047                }
13048
13049                if (dataOwnerPkg != null) {
13050                    // If installed, the package will get access to data left on the device by its
13051                    // predecessor. As a security measure, this is permited only if this is not a
13052                    // version downgrade or if the predecessor package is marked as debuggable and
13053                    // a downgrade is explicitly requested.
13054                    //
13055                    // On debuggable platform builds, downgrades are permitted even for
13056                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13057                    // not offer security guarantees and thus it's OK to disable some security
13058                    // mechanisms to make debugging/testing easier on those builds. However, even on
13059                    // debuggable builds downgrades of packages are permitted only if requested via
13060                    // installFlags. This is because we aim to keep the behavior of debuggable
13061                    // platform builds as close as possible to the behavior of non-debuggable
13062                    // platform builds.
13063                    final boolean downgradeRequested =
13064                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13065                    final boolean packageDebuggable =
13066                                (dataOwnerPkg.applicationInfo.flags
13067                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13068                    final boolean downgradePermitted =
13069                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13070                    if (!downgradePermitted) {
13071                        try {
13072                            checkDowngrade(dataOwnerPkg, pkgLite);
13073                        } catch (PackageManagerException e) {
13074                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13075                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13076                        }
13077                    }
13078                }
13079
13080                if (installedPkg != null) {
13081                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13082                        // Check for updated system application.
13083                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13084                            if (onSd) {
13085                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13086                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13087                            }
13088                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13089                        } else {
13090                            if (onSd) {
13091                                // Install flag overrides everything.
13092                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13093                            }
13094                            // If current upgrade specifies particular preference
13095                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13096                                // Application explicitly specified internal.
13097                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13098                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13099                                // App explictly prefers external. Let policy decide
13100                            } else {
13101                                // Prefer previous location
13102                                if (isExternal(installedPkg)) {
13103                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13104                                }
13105                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13106                            }
13107                        }
13108                    } else {
13109                        // Invalid install. Return error code
13110                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13111                    }
13112                }
13113            }
13114            // All the special cases have been taken care of.
13115            // Return result based on recommended install location.
13116            if (onSd) {
13117                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13118            }
13119            return pkgLite.recommendedInstallLocation;
13120        }
13121
13122        /*
13123         * Invoke remote method to get package information and install
13124         * location values. Override install location based on default
13125         * policy if needed and then create install arguments based
13126         * on the install location.
13127         */
13128        public void handleStartCopy() throws RemoteException {
13129            int ret = PackageManager.INSTALL_SUCCEEDED;
13130
13131            // If we're already staged, we've firmly committed to an install location
13132            if (origin.staged) {
13133                if (origin.file != null) {
13134                    installFlags |= PackageManager.INSTALL_INTERNAL;
13135                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13136                } else if (origin.cid != null) {
13137                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13138                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13139                } else {
13140                    throw new IllegalStateException("Invalid stage location");
13141                }
13142            }
13143
13144            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13145            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13146            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13147            PackageInfoLite pkgLite = null;
13148
13149            if (onInt && onSd) {
13150                // Check if both bits are set.
13151                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13152                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13153            } else if (onSd && ephemeral) {
13154                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13155                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13156            } else {
13157                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13158                        packageAbiOverride);
13159
13160                if (DEBUG_EPHEMERAL && ephemeral) {
13161                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13162                }
13163
13164                /*
13165                 * If we have too little free space, try to free cache
13166                 * before giving up.
13167                 */
13168                if (!origin.staged && pkgLite.recommendedInstallLocation
13169                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13170                    // TODO: focus freeing disk space on the target device
13171                    final StorageManager storage = StorageManager.from(mContext);
13172                    final long lowThreshold = storage.getStorageLowBytes(
13173                            Environment.getDataDirectory());
13174
13175                    final long sizeBytes = mContainerService.calculateInstalledSize(
13176                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13177
13178                    try {
13179                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13180                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13181                                installFlags, packageAbiOverride);
13182                    } catch (InstallerException e) {
13183                        Slog.w(TAG, "Failed to free cache", e);
13184                    }
13185
13186                    /*
13187                     * The cache free must have deleted the file we
13188                     * downloaded to install.
13189                     *
13190                     * TODO: fix the "freeCache" call to not delete
13191                     *       the file we care about.
13192                     */
13193                    if (pkgLite.recommendedInstallLocation
13194                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13195                        pkgLite.recommendedInstallLocation
13196                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13197                    }
13198                }
13199            }
13200
13201            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13202                int loc = pkgLite.recommendedInstallLocation;
13203                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13204                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13205                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13206                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13207                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13208                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13209                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13210                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13211                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13212                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13213                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13214                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13215                } else {
13216                    // Override with defaults if needed.
13217                    loc = installLocationPolicy(pkgLite);
13218                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13219                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13220                    } else if (!onSd && !onInt) {
13221                        // Override install location with flags
13222                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13223                            // Set the flag to install on external media.
13224                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13225                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13226                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13227                            if (DEBUG_EPHEMERAL) {
13228                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13229                            }
13230                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13231                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13232                                    |PackageManager.INSTALL_INTERNAL);
13233                        } else {
13234                            // Make sure the flag for installing on external
13235                            // media is unset
13236                            installFlags |= PackageManager.INSTALL_INTERNAL;
13237                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13238                        }
13239                    }
13240                }
13241            }
13242
13243            final InstallArgs args = createInstallArgs(this);
13244            mArgs = args;
13245
13246            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13247                // TODO: http://b/22976637
13248                // Apps installed for "all" users use the device owner to verify the app
13249                UserHandle verifierUser = getUser();
13250                if (verifierUser == UserHandle.ALL) {
13251                    verifierUser = UserHandle.SYSTEM;
13252                }
13253
13254                /*
13255                 * Determine if we have any installed package verifiers. If we
13256                 * do, then we'll defer to them to verify the packages.
13257                 */
13258                final int requiredUid = mRequiredVerifierPackage == null ? -1
13259                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13260                                verifierUser.getIdentifier());
13261                if (!origin.existing && requiredUid != -1
13262                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13263                    final Intent verification = new Intent(
13264                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13265                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13266                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13267                            PACKAGE_MIME_TYPE);
13268                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13269
13270                    // Query all live verifiers based on current user state
13271                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13272                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13273
13274                    if (DEBUG_VERIFY) {
13275                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13276                                + verification.toString() + " with " + pkgLite.verifiers.length
13277                                + " optional verifiers");
13278                    }
13279
13280                    final int verificationId = mPendingVerificationToken++;
13281
13282                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13283
13284                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13285                            installerPackageName);
13286
13287                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13288                            installFlags);
13289
13290                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13291                            pkgLite.packageName);
13292
13293                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13294                            pkgLite.versionCode);
13295
13296                    if (verificationInfo != null) {
13297                        if (verificationInfo.originatingUri != null) {
13298                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13299                                    verificationInfo.originatingUri);
13300                        }
13301                        if (verificationInfo.referrer != null) {
13302                            verification.putExtra(Intent.EXTRA_REFERRER,
13303                                    verificationInfo.referrer);
13304                        }
13305                        if (verificationInfo.originatingUid >= 0) {
13306                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13307                                    verificationInfo.originatingUid);
13308                        }
13309                        if (verificationInfo.installerUid >= 0) {
13310                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13311                                    verificationInfo.installerUid);
13312                        }
13313                    }
13314
13315                    final PackageVerificationState verificationState = new PackageVerificationState(
13316                            requiredUid, args);
13317
13318                    mPendingVerification.append(verificationId, verificationState);
13319
13320                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13321                            receivers, verificationState);
13322
13323                    /*
13324                     * If any sufficient verifiers were listed in the package
13325                     * manifest, attempt to ask them.
13326                     */
13327                    if (sufficientVerifiers != null) {
13328                        final int N = sufficientVerifiers.size();
13329                        if (N == 0) {
13330                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13331                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13332                        } else {
13333                            for (int i = 0; i < N; i++) {
13334                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13335
13336                                final Intent sufficientIntent = new Intent(verification);
13337                                sufficientIntent.setComponent(verifierComponent);
13338                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13339                            }
13340                        }
13341                    }
13342
13343                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13344                            mRequiredVerifierPackage, receivers);
13345                    if (ret == PackageManager.INSTALL_SUCCEEDED
13346                            && mRequiredVerifierPackage != null) {
13347                        Trace.asyncTraceBegin(
13348                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13349                        /*
13350                         * Send the intent to the required verification agent,
13351                         * but only start the verification timeout after the
13352                         * target BroadcastReceivers have run.
13353                         */
13354                        verification.setComponent(requiredVerifierComponent);
13355                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13356                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13357                                new BroadcastReceiver() {
13358                                    @Override
13359                                    public void onReceive(Context context, Intent intent) {
13360                                        final Message msg = mHandler
13361                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13362                                        msg.arg1 = verificationId;
13363                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13364                                    }
13365                                }, null, 0, null, null);
13366
13367                        /*
13368                         * We don't want the copy to proceed until verification
13369                         * succeeds, so null out this field.
13370                         */
13371                        mArgs = null;
13372                    }
13373                } else {
13374                    /*
13375                     * No package verification is enabled, so immediately start
13376                     * the remote call to initiate copy using temporary file.
13377                     */
13378                    ret = args.copyApk(mContainerService, true);
13379                }
13380            }
13381
13382            mRet = ret;
13383        }
13384
13385        @Override
13386        void handleReturnCode() {
13387            // If mArgs is null, then MCS couldn't be reached. When it
13388            // reconnects, it will try again to install. At that point, this
13389            // will succeed.
13390            if (mArgs != null) {
13391                processPendingInstall(mArgs, mRet);
13392            }
13393        }
13394
13395        @Override
13396        void handleServiceError() {
13397            mArgs = createInstallArgs(this);
13398            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13399        }
13400
13401        public boolean isForwardLocked() {
13402            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13403        }
13404    }
13405
13406    /**
13407     * Used during creation of InstallArgs
13408     *
13409     * @param installFlags package installation flags
13410     * @return true if should be installed on external storage
13411     */
13412    private static boolean installOnExternalAsec(int installFlags) {
13413        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13414            return false;
13415        }
13416        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13417            return true;
13418        }
13419        return false;
13420    }
13421
13422    /**
13423     * Used during creation of InstallArgs
13424     *
13425     * @param installFlags package installation flags
13426     * @return true if should be installed as forward locked
13427     */
13428    private static boolean installForwardLocked(int installFlags) {
13429        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13430    }
13431
13432    private InstallArgs createInstallArgs(InstallParams params) {
13433        if (params.move != null) {
13434            return new MoveInstallArgs(params);
13435        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13436            return new AsecInstallArgs(params);
13437        } else {
13438            return new FileInstallArgs(params);
13439        }
13440    }
13441
13442    /**
13443     * Create args that describe an existing installed package. Typically used
13444     * when cleaning up old installs, or used as a move source.
13445     */
13446    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13447            String resourcePath, String[] instructionSets) {
13448        final boolean isInAsec;
13449        if (installOnExternalAsec(installFlags)) {
13450            /* Apps on SD card are always in ASEC containers. */
13451            isInAsec = true;
13452        } else if (installForwardLocked(installFlags)
13453                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13454            /*
13455             * Forward-locked apps are only in ASEC containers if they're the
13456             * new style
13457             */
13458            isInAsec = true;
13459        } else {
13460            isInAsec = false;
13461        }
13462
13463        if (isInAsec) {
13464            return new AsecInstallArgs(codePath, instructionSets,
13465                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13466        } else {
13467            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13468        }
13469    }
13470
13471    static abstract class InstallArgs {
13472        /** @see InstallParams#origin */
13473        final OriginInfo origin;
13474        /** @see InstallParams#move */
13475        final MoveInfo move;
13476
13477        final IPackageInstallObserver2 observer;
13478        // Always refers to PackageManager flags only
13479        final int installFlags;
13480        final String installerPackageName;
13481        final String volumeUuid;
13482        final UserHandle user;
13483        final String abiOverride;
13484        final String[] installGrantPermissions;
13485        /** If non-null, drop an async trace when the install completes */
13486        final String traceMethod;
13487        final int traceCookie;
13488        final Certificate[][] certificates;
13489
13490        // The list of instruction sets supported by this app. This is currently
13491        // only used during the rmdex() phase to clean up resources. We can get rid of this
13492        // if we move dex files under the common app path.
13493        /* nullable */ String[] instructionSets;
13494
13495        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13496                int installFlags, String installerPackageName, String volumeUuid,
13497                UserHandle user, String[] instructionSets,
13498                String abiOverride, String[] installGrantPermissions,
13499                String traceMethod, int traceCookie, Certificate[][] certificates) {
13500            this.origin = origin;
13501            this.move = move;
13502            this.installFlags = installFlags;
13503            this.observer = observer;
13504            this.installerPackageName = installerPackageName;
13505            this.volumeUuid = volumeUuid;
13506            this.user = user;
13507            this.instructionSets = instructionSets;
13508            this.abiOverride = abiOverride;
13509            this.installGrantPermissions = installGrantPermissions;
13510            this.traceMethod = traceMethod;
13511            this.traceCookie = traceCookie;
13512            this.certificates = certificates;
13513        }
13514
13515        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13516        abstract int doPreInstall(int status);
13517
13518        /**
13519         * Rename package into final resting place. All paths on the given
13520         * scanned package should be updated to reflect the rename.
13521         */
13522        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13523        abstract int doPostInstall(int status, int uid);
13524
13525        /** @see PackageSettingBase#codePathString */
13526        abstract String getCodePath();
13527        /** @see PackageSettingBase#resourcePathString */
13528        abstract String getResourcePath();
13529
13530        // Need installer lock especially for dex file removal.
13531        abstract void cleanUpResourcesLI();
13532        abstract boolean doPostDeleteLI(boolean delete);
13533
13534        /**
13535         * Called before the source arguments are copied. This is used mostly
13536         * for MoveParams when it needs to read the source file to put it in the
13537         * destination.
13538         */
13539        int doPreCopy() {
13540            return PackageManager.INSTALL_SUCCEEDED;
13541        }
13542
13543        /**
13544         * Called after the source arguments are copied. This is used mostly for
13545         * MoveParams when it needs to read the source file to put it in the
13546         * destination.
13547         */
13548        int doPostCopy(int uid) {
13549            return PackageManager.INSTALL_SUCCEEDED;
13550        }
13551
13552        protected boolean isFwdLocked() {
13553            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13554        }
13555
13556        protected boolean isExternalAsec() {
13557            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13558        }
13559
13560        protected boolean isEphemeral() {
13561            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13562        }
13563
13564        UserHandle getUser() {
13565            return user;
13566        }
13567    }
13568
13569    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13570        if (!allCodePaths.isEmpty()) {
13571            if (instructionSets == null) {
13572                throw new IllegalStateException("instructionSet == null");
13573            }
13574            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13575            for (String codePath : allCodePaths) {
13576                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13577                    try {
13578                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13579                    } catch (InstallerException ignored) {
13580                    }
13581                }
13582            }
13583        }
13584    }
13585
13586    /**
13587     * Logic to handle installation of non-ASEC applications, including copying
13588     * and renaming logic.
13589     */
13590    class FileInstallArgs extends InstallArgs {
13591        private File codeFile;
13592        private File resourceFile;
13593
13594        // Example topology:
13595        // /data/app/com.example/base.apk
13596        // /data/app/com.example/split_foo.apk
13597        // /data/app/com.example/lib/arm/libfoo.so
13598        // /data/app/com.example/lib/arm64/libfoo.so
13599        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13600
13601        /** New install */
13602        FileInstallArgs(InstallParams params) {
13603            super(params.origin, params.move, params.observer, params.installFlags,
13604                    params.installerPackageName, params.volumeUuid,
13605                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13606                    params.grantedRuntimePermissions,
13607                    params.traceMethod, params.traceCookie, params.certificates);
13608            if (isFwdLocked()) {
13609                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13610            }
13611        }
13612
13613        /** Existing install */
13614        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13615            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13616                    null, null, null, 0, null /*certificates*/);
13617            this.codeFile = (codePath != null) ? new File(codePath) : null;
13618            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13619        }
13620
13621        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13622            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13623            try {
13624                return doCopyApk(imcs, temp);
13625            } finally {
13626                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13627            }
13628        }
13629
13630        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13631            if (origin.staged) {
13632                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13633                codeFile = origin.file;
13634                resourceFile = origin.file;
13635                return PackageManager.INSTALL_SUCCEEDED;
13636            }
13637
13638            try {
13639                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13640                final File tempDir =
13641                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13642                codeFile = tempDir;
13643                resourceFile = tempDir;
13644            } catch (IOException e) {
13645                Slog.w(TAG, "Failed to create copy file: " + e);
13646                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13647            }
13648
13649            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13650                @Override
13651                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13652                    if (!FileUtils.isValidExtFilename(name)) {
13653                        throw new IllegalArgumentException("Invalid filename: " + name);
13654                    }
13655                    try {
13656                        final File file = new File(codeFile, name);
13657                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13658                                O_RDWR | O_CREAT, 0644);
13659                        Os.chmod(file.getAbsolutePath(), 0644);
13660                        return new ParcelFileDescriptor(fd);
13661                    } catch (ErrnoException e) {
13662                        throw new RemoteException("Failed to open: " + e.getMessage());
13663                    }
13664                }
13665            };
13666
13667            int ret = PackageManager.INSTALL_SUCCEEDED;
13668            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13669            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13670                Slog.e(TAG, "Failed to copy package");
13671                return ret;
13672            }
13673
13674            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13675            NativeLibraryHelper.Handle handle = null;
13676            try {
13677                handle = NativeLibraryHelper.Handle.create(codeFile);
13678                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13679                        abiOverride);
13680            } catch (IOException e) {
13681                Slog.e(TAG, "Copying native libraries failed", e);
13682                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13683            } finally {
13684                IoUtils.closeQuietly(handle);
13685            }
13686
13687            return ret;
13688        }
13689
13690        int doPreInstall(int status) {
13691            if (status != PackageManager.INSTALL_SUCCEEDED) {
13692                cleanUp();
13693            }
13694            return status;
13695        }
13696
13697        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13698            if (status != PackageManager.INSTALL_SUCCEEDED) {
13699                cleanUp();
13700                return false;
13701            }
13702
13703            final File targetDir = codeFile.getParentFile();
13704            final File beforeCodeFile = codeFile;
13705            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13706
13707            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13708            try {
13709                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13710            } catch (ErrnoException e) {
13711                Slog.w(TAG, "Failed to rename", e);
13712                return false;
13713            }
13714
13715            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13716                Slog.w(TAG, "Failed to restorecon");
13717                return false;
13718            }
13719
13720            // Reflect the rename internally
13721            codeFile = afterCodeFile;
13722            resourceFile = afterCodeFile;
13723
13724            // Reflect the rename in scanned details
13725            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13726            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13727                    afterCodeFile, pkg.baseCodePath));
13728            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13729                    afterCodeFile, pkg.splitCodePaths));
13730
13731            // Reflect the rename in app info
13732            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13733            pkg.setApplicationInfoCodePath(pkg.codePath);
13734            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13735            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13736            pkg.setApplicationInfoResourcePath(pkg.codePath);
13737            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13738            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13739
13740            return true;
13741        }
13742
13743        int doPostInstall(int status, int uid) {
13744            if (status != PackageManager.INSTALL_SUCCEEDED) {
13745                cleanUp();
13746            }
13747            return status;
13748        }
13749
13750        @Override
13751        String getCodePath() {
13752            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13753        }
13754
13755        @Override
13756        String getResourcePath() {
13757            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13758        }
13759
13760        private boolean cleanUp() {
13761            if (codeFile == null || !codeFile.exists()) {
13762                return false;
13763            }
13764
13765            removeCodePathLI(codeFile);
13766
13767            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13768                resourceFile.delete();
13769            }
13770
13771            return true;
13772        }
13773
13774        void cleanUpResourcesLI() {
13775            // Try enumerating all code paths before deleting
13776            List<String> allCodePaths = Collections.EMPTY_LIST;
13777            if (codeFile != null && codeFile.exists()) {
13778                try {
13779                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13780                    allCodePaths = pkg.getAllCodePaths();
13781                } catch (PackageParserException e) {
13782                    // Ignored; we tried our best
13783                }
13784            }
13785
13786            cleanUp();
13787            removeDexFiles(allCodePaths, instructionSets);
13788        }
13789
13790        boolean doPostDeleteLI(boolean delete) {
13791            // XXX err, shouldn't we respect the delete flag?
13792            cleanUpResourcesLI();
13793            return true;
13794        }
13795    }
13796
13797    private boolean isAsecExternal(String cid) {
13798        final String asecPath = PackageHelper.getSdFilesystem(cid);
13799        return !asecPath.startsWith(mAsecInternalPath);
13800    }
13801
13802    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13803            PackageManagerException {
13804        if (copyRet < 0) {
13805            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13806                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13807                throw new PackageManagerException(copyRet, message);
13808            }
13809        }
13810    }
13811
13812    /**
13813     * Extract the MountService "container ID" from the full code path of an
13814     * .apk.
13815     */
13816    static String cidFromCodePath(String fullCodePath) {
13817        int eidx = fullCodePath.lastIndexOf("/");
13818        String subStr1 = fullCodePath.substring(0, eidx);
13819        int sidx = subStr1.lastIndexOf("/");
13820        return subStr1.substring(sidx+1, eidx);
13821    }
13822
13823    /**
13824     * Logic to handle installation of ASEC applications, including copying and
13825     * renaming logic.
13826     */
13827    class AsecInstallArgs extends InstallArgs {
13828        static final String RES_FILE_NAME = "pkg.apk";
13829        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13830
13831        String cid;
13832        String packagePath;
13833        String resourcePath;
13834
13835        /** New install */
13836        AsecInstallArgs(InstallParams params) {
13837            super(params.origin, params.move, params.observer, params.installFlags,
13838                    params.installerPackageName, params.volumeUuid,
13839                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13840                    params.grantedRuntimePermissions,
13841                    params.traceMethod, params.traceCookie, params.certificates);
13842        }
13843
13844        /** Existing install */
13845        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13846                        boolean isExternal, boolean isForwardLocked) {
13847            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13848              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13849                    instructionSets, null, null, null, 0, null /*certificates*/);
13850            // Hackily pretend we're still looking at a full code path
13851            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13852                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13853            }
13854
13855            // Extract cid from fullCodePath
13856            int eidx = fullCodePath.lastIndexOf("/");
13857            String subStr1 = fullCodePath.substring(0, eidx);
13858            int sidx = subStr1.lastIndexOf("/");
13859            cid = subStr1.substring(sidx+1, eidx);
13860            setMountPath(subStr1);
13861        }
13862
13863        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13864            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13865              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13866                    instructionSets, null, null, null, 0, null /*certificates*/);
13867            this.cid = cid;
13868            setMountPath(PackageHelper.getSdDir(cid));
13869        }
13870
13871        void createCopyFile() {
13872            cid = mInstallerService.allocateExternalStageCidLegacy();
13873        }
13874
13875        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13876            if (origin.staged && origin.cid != null) {
13877                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13878                cid = origin.cid;
13879                setMountPath(PackageHelper.getSdDir(cid));
13880                return PackageManager.INSTALL_SUCCEEDED;
13881            }
13882
13883            if (temp) {
13884                createCopyFile();
13885            } else {
13886                /*
13887                 * Pre-emptively destroy the container since it's destroyed if
13888                 * copying fails due to it existing anyway.
13889                 */
13890                PackageHelper.destroySdDir(cid);
13891            }
13892
13893            final String newMountPath = imcs.copyPackageToContainer(
13894                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13895                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13896
13897            if (newMountPath != null) {
13898                setMountPath(newMountPath);
13899                return PackageManager.INSTALL_SUCCEEDED;
13900            } else {
13901                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13902            }
13903        }
13904
13905        @Override
13906        String getCodePath() {
13907            return packagePath;
13908        }
13909
13910        @Override
13911        String getResourcePath() {
13912            return resourcePath;
13913        }
13914
13915        int doPreInstall(int status) {
13916            if (status != PackageManager.INSTALL_SUCCEEDED) {
13917                // Destroy container
13918                PackageHelper.destroySdDir(cid);
13919            } else {
13920                boolean mounted = PackageHelper.isContainerMounted(cid);
13921                if (!mounted) {
13922                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13923                            Process.SYSTEM_UID);
13924                    if (newMountPath != null) {
13925                        setMountPath(newMountPath);
13926                    } else {
13927                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13928                    }
13929                }
13930            }
13931            return status;
13932        }
13933
13934        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13935            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13936            String newMountPath = null;
13937            if (PackageHelper.isContainerMounted(cid)) {
13938                // Unmount the container
13939                if (!PackageHelper.unMountSdDir(cid)) {
13940                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13941                    return false;
13942                }
13943            }
13944            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13945                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13946                        " which might be stale. Will try to clean up.");
13947                // Clean up the stale container and proceed to recreate.
13948                if (!PackageHelper.destroySdDir(newCacheId)) {
13949                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13950                    return false;
13951                }
13952                // Successfully cleaned up stale container. Try to rename again.
13953                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13954                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13955                            + " inspite of cleaning it up.");
13956                    return false;
13957                }
13958            }
13959            if (!PackageHelper.isContainerMounted(newCacheId)) {
13960                Slog.w(TAG, "Mounting container " + newCacheId);
13961                newMountPath = PackageHelper.mountSdDir(newCacheId,
13962                        getEncryptKey(), Process.SYSTEM_UID);
13963            } else {
13964                newMountPath = PackageHelper.getSdDir(newCacheId);
13965            }
13966            if (newMountPath == null) {
13967                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13968                return false;
13969            }
13970            Log.i(TAG, "Succesfully renamed " + cid +
13971                    " to " + newCacheId +
13972                    " at new path: " + newMountPath);
13973            cid = newCacheId;
13974
13975            final File beforeCodeFile = new File(packagePath);
13976            setMountPath(newMountPath);
13977            final File afterCodeFile = new File(packagePath);
13978
13979            // Reflect the rename in scanned details
13980            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13981            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13982                    afterCodeFile, pkg.baseCodePath));
13983            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13984                    afterCodeFile, pkg.splitCodePaths));
13985
13986            // Reflect the rename in app info
13987            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13988            pkg.setApplicationInfoCodePath(pkg.codePath);
13989            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13990            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13991            pkg.setApplicationInfoResourcePath(pkg.codePath);
13992            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13993            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13994
13995            return true;
13996        }
13997
13998        private void setMountPath(String mountPath) {
13999            final File mountFile = new File(mountPath);
14000
14001            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14002            if (monolithicFile.exists()) {
14003                packagePath = monolithicFile.getAbsolutePath();
14004                if (isFwdLocked()) {
14005                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14006                } else {
14007                    resourcePath = packagePath;
14008                }
14009            } else {
14010                packagePath = mountFile.getAbsolutePath();
14011                resourcePath = packagePath;
14012            }
14013        }
14014
14015        int doPostInstall(int status, int uid) {
14016            if (status != PackageManager.INSTALL_SUCCEEDED) {
14017                cleanUp();
14018            } else {
14019                final int groupOwner;
14020                final String protectedFile;
14021                if (isFwdLocked()) {
14022                    groupOwner = UserHandle.getSharedAppGid(uid);
14023                    protectedFile = RES_FILE_NAME;
14024                } else {
14025                    groupOwner = -1;
14026                    protectedFile = null;
14027                }
14028
14029                if (uid < Process.FIRST_APPLICATION_UID
14030                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14031                    Slog.e(TAG, "Failed to finalize " + cid);
14032                    PackageHelper.destroySdDir(cid);
14033                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14034                }
14035
14036                boolean mounted = PackageHelper.isContainerMounted(cid);
14037                if (!mounted) {
14038                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14039                }
14040            }
14041            return status;
14042        }
14043
14044        private void cleanUp() {
14045            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14046
14047            // Destroy secure container
14048            PackageHelper.destroySdDir(cid);
14049        }
14050
14051        private List<String> getAllCodePaths() {
14052            final File codeFile = new File(getCodePath());
14053            if (codeFile != null && codeFile.exists()) {
14054                try {
14055                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14056                    return pkg.getAllCodePaths();
14057                } catch (PackageParserException e) {
14058                    // Ignored; we tried our best
14059                }
14060            }
14061            return Collections.EMPTY_LIST;
14062        }
14063
14064        void cleanUpResourcesLI() {
14065            // Enumerate all code paths before deleting
14066            cleanUpResourcesLI(getAllCodePaths());
14067        }
14068
14069        private void cleanUpResourcesLI(List<String> allCodePaths) {
14070            cleanUp();
14071            removeDexFiles(allCodePaths, instructionSets);
14072        }
14073
14074        String getPackageName() {
14075            return getAsecPackageName(cid);
14076        }
14077
14078        boolean doPostDeleteLI(boolean delete) {
14079            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14080            final List<String> allCodePaths = getAllCodePaths();
14081            boolean mounted = PackageHelper.isContainerMounted(cid);
14082            if (mounted) {
14083                // Unmount first
14084                if (PackageHelper.unMountSdDir(cid)) {
14085                    mounted = false;
14086                }
14087            }
14088            if (!mounted && delete) {
14089                cleanUpResourcesLI(allCodePaths);
14090            }
14091            return !mounted;
14092        }
14093
14094        @Override
14095        int doPreCopy() {
14096            if (isFwdLocked()) {
14097                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14098                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14099                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14100                }
14101            }
14102
14103            return PackageManager.INSTALL_SUCCEEDED;
14104        }
14105
14106        @Override
14107        int doPostCopy(int uid) {
14108            if (isFwdLocked()) {
14109                if (uid < Process.FIRST_APPLICATION_UID
14110                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14111                                RES_FILE_NAME)) {
14112                    Slog.e(TAG, "Failed to finalize " + cid);
14113                    PackageHelper.destroySdDir(cid);
14114                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14115                }
14116            }
14117
14118            return PackageManager.INSTALL_SUCCEEDED;
14119        }
14120    }
14121
14122    /**
14123     * Logic to handle movement of existing installed applications.
14124     */
14125    class MoveInstallArgs extends InstallArgs {
14126        private File codeFile;
14127        private File resourceFile;
14128
14129        /** New install */
14130        MoveInstallArgs(InstallParams params) {
14131            super(params.origin, params.move, params.observer, params.installFlags,
14132                    params.installerPackageName, params.volumeUuid,
14133                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14134                    params.grantedRuntimePermissions,
14135                    params.traceMethod, params.traceCookie, params.certificates);
14136        }
14137
14138        int copyApk(IMediaContainerService imcs, boolean temp) {
14139            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14140                    + move.fromUuid + " to " + move.toUuid);
14141            synchronized (mInstaller) {
14142                try {
14143                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14144                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14145                } catch (InstallerException e) {
14146                    Slog.w(TAG, "Failed to move app", e);
14147                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14148                }
14149            }
14150
14151            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14152            resourceFile = codeFile;
14153            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14154
14155            return PackageManager.INSTALL_SUCCEEDED;
14156        }
14157
14158        int doPreInstall(int status) {
14159            if (status != PackageManager.INSTALL_SUCCEEDED) {
14160                cleanUp(move.toUuid);
14161            }
14162            return status;
14163        }
14164
14165        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14166            if (status != PackageManager.INSTALL_SUCCEEDED) {
14167                cleanUp(move.toUuid);
14168                return false;
14169            }
14170
14171            // Reflect the move in app info
14172            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14173            pkg.setApplicationInfoCodePath(pkg.codePath);
14174            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14175            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14176            pkg.setApplicationInfoResourcePath(pkg.codePath);
14177            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14178            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14179
14180            return true;
14181        }
14182
14183        int doPostInstall(int status, int uid) {
14184            if (status == PackageManager.INSTALL_SUCCEEDED) {
14185                cleanUp(move.fromUuid);
14186            } else {
14187                cleanUp(move.toUuid);
14188            }
14189            return status;
14190        }
14191
14192        @Override
14193        String getCodePath() {
14194            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14195        }
14196
14197        @Override
14198        String getResourcePath() {
14199            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14200        }
14201
14202        private boolean cleanUp(String volumeUuid) {
14203            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14204                    move.dataAppName);
14205            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14206            final int[] userIds = sUserManager.getUserIds();
14207            synchronized (mInstallLock) {
14208                // Clean up both app data and code
14209                // All package moves are frozen until finished
14210                for (int userId : userIds) {
14211                    try {
14212                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14213                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14214                    } catch (InstallerException e) {
14215                        Slog.w(TAG, String.valueOf(e));
14216                    }
14217                }
14218                removeCodePathLI(codeFile);
14219            }
14220            return true;
14221        }
14222
14223        void cleanUpResourcesLI() {
14224            throw new UnsupportedOperationException();
14225        }
14226
14227        boolean doPostDeleteLI(boolean delete) {
14228            throw new UnsupportedOperationException();
14229        }
14230    }
14231
14232    static String getAsecPackageName(String packageCid) {
14233        int idx = packageCid.lastIndexOf("-");
14234        if (idx == -1) {
14235            return packageCid;
14236        }
14237        return packageCid.substring(0, idx);
14238    }
14239
14240    // Utility method used to create code paths based on package name and available index.
14241    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14242        String idxStr = "";
14243        int idx = 1;
14244        // Fall back to default value of idx=1 if prefix is not
14245        // part of oldCodePath
14246        if (oldCodePath != null) {
14247            String subStr = oldCodePath;
14248            // Drop the suffix right away
14249            if (suffix != null && subStr.endsWith(suffix)) {
14250                subStr = subStr.substring(0, subStr.length() - suffix.length());
14251            }
14252            // If oldCodePath already contains prefix find out the
14253            // ending index to either increment or decrement.
14254            int sidx = subStr.lastIndexOf(prefix);
14255            if (sidx != -1) {
14256                subStr = subStr.substring(sidx + prefix.length());
14257                if (subStr != null) {
14258                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14259                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14260                    }
14261                    try {
14262                        idx = Integer.parseInt(subStr);
14263                        if (idx <= 1) {
14264                            idx++;
14265                        } else {
14266                            idx--;
14267                        }
14268                    } catch(NumberFormatException e) {
14269                    }
14270                }
14271            }
14272        }
14273        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14274        return prefix + idxStr;
14275    }
14276
14277    private File getNextCodePath(File targetDir, String packageName) {
14278        int suffix = 1;
14279        File result;
14280        do {
14281            result = new File(targetDir, packageName + "-" + suffix);
14282            suffix++;
14283        } while (result.exists());
14284        return result;
14285    }
14286
14287    // Utility method that returns the relative package path with respect
14288    // to the installation directory. Like say for /data/data/com.test-1.apk
14289    // string com.test-1 is returned.
14290    static String deriveCodePathName(String codePath) {
14291        if (codePath == null) {
14292            return null;
14293        }
14294        final File codeFile = new File(codePath);
14295        final String name = codeFile.getName();
14296        if (codeFile.isDirectory()) {
14297            return name;
14298        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14299            final int lastDot = name.lastIndexOf('.');
14300            return name.substring(0, lastDot);
14301        } else {
14302            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14303            return null;
14304        }
14305    }
14306
14307    static class PackageInstalledInfo {
14308        String name;
14309        int uid;
14310        // The set of users that originally had this package installed.
14311        int[] origUsers;
14312        // The set of users that now have this package installed.
14313        int[] newUsers;
14314        PackageParser.Package pkg;
14315        int returnCode;
14316        String returnMsg;
14317        PackageRemovedInfo removedInfo;
14318        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14319
14320        public void setError(int code, String msg) {
14321            setReturnCode(code);
14322            setReturnMessage(msg);
14323            Slog.w(TAG, msg);
14324        }
14325
14326        public void setError(String msg, PackageParserException e) {
14327            setReturnCode(e.error);
14328            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14329            Slog.w(TAG, msg, e);
14330        }
14331
14332        public void setError(String msg, PackageManagerException e) {
14333            returnCode = e.error;
14334            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14335            Slog.w(TAG, msg, e);
14336        }
14337
14338        public void setReturnCode(int returnCode) {
14339            this.returnCode = returnCode;
14340            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14341            for (int i = 0; i < childCount; i++) {
14342                addedChildPackages.valueAt(i).returnCode = returnCode;
14343            }
14344        }
14345
14346        private void setReturnMessage(String returnMsg) {
14347            this.returnMsg = returnMsg;
14348            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14349            for (int i = 0; i < childCount; i++) {
14350                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14351            }
14352        }
14353
14354        // In some error cases we want to convey more info back to the observer
14355        String origPackage;
14356        String origPermission;
14357    }
14358
14359    /*
14360     * Install a non-existing package.
14361     */
14362    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14363            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14364            PackageInstalledInfo res) {
14365        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14366
14367        // Remember this for later, in case we need to rollback this install
14368        String pkgName = pkg.packageName;
14369
14370        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14371
14372        synchronized(mPackages) {
14373            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14374            if (renamedPackage != null) {
14375                // A package with the same name is already installed, though
14376                // it has been renamed to an older name.  The package we
14377                // are trying to install should be installed as an update to
14378                // the existing one, but that has not been requested, so bail.
14379                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14380                        + " without first uninstalling package running as "
14381                        + renamedPackage);
14382                return;
14383            }
14384            if (mPackages.containsKey(pkgName)) {
14385                // Don't allow installation over an existing package with the same name.
14386                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14387                        + " without first uninstalling.");
14388                return;
14389            }
14390        }
14391
14392        try {
14393            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14394                    System.currentTimeMillis(), user);
14395
14396            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14397
14398            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14399                prepareAppDataAfterInstallLIF(newPackage);
14400
14401            } else {
14402                // Remove package from internal structures, but keep around any
14403                // data that might have already existed
14404                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14405                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14406            }
14407        } catch (PackageManagerException e) {
14408            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14409        }
14410
14411        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14412    }
14413
14414    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14415        // Can't rotate keys during boot or if sharedUser.
14416        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14417                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14418            return false;
14419        }
14420        // app is using upgradeKeySets; make sure all are valid
14421        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14422        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14423        for (int i = 0; i < upgradeKeySets.length; i++) {
14424            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14425                Slog.wtf(TAG, "Package "
14426                         + (oldPs.name != null ? oldPs.name : "<null>")
14427                         + " contains upgrade-key-set reference to unknown key-set: "
14428                         + upgradeKeySets[i]
14429                         + " reverting to signatures check.");
14430                return false;
14431            }
14432        }
14433        return true;
14434    }
14435
14436    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14437        // Upgrade keysets are being used.  Determine if new package has a superset of the
14438        // required keys.
14439        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14440        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14441        for (int i = 0; i < upgradeKeySets.length; i++) {
14442            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14443            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14444                return true;
14445            }
14446        }
14447        return false;
14448    }
14449
14450    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14451        try (DigestInputStream digestStream =
14452                new DigestInputStream(new FileInputStream(file), digest)) {
14453            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14454        }
14455    }
14456
14457    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14458            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14459        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14460
14461        final PackageParser.Package oldPackage;
14462        final String pkgName = pkg.packageName;
14463        final int[] allUsers;
14464        final int[] installedUsers;
14465
14466        synchronized(mPackages) {
14467            oldPackage = mPackages.get(pkgName);
14468            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14469
14470            // don't allow upgrade to target a release SDK from a pre-release SDK
14471            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14472                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14473            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14474                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14475            if (oldTargetsPreRelease
14476                    && !newTargetsPreRelease
14477                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14478                Slog.w(TAG, "Can't install package targeting released sdk");
14479                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14480                return;
14481            }
14482
14483            // don't allow an upgrade from full to ephemeral
14484            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14485            if (isEphemeral && !oldIsEphemeral) {
14486                // can't downgrade from full to ephemeral
14487                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14488                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14489                return;
14490            }
14491
14492            // verify signatures are valid
14493            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14494            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14495                if (!checkUpgradeKeySetLP(ps, pkg)) {
14496                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14497                            "New package not signed by keys specified by upgrade-keysets: "
14498                                    + pkgName);
14499                    return;
14500                }
14501            } else {
14502                // default to original signature matching
14503                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14504                        != PackageManager.SIGNATURE_MATCH) {
14505                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14506                            "New package has a different signature: " + pkgName);
14507                    return;
14508                }
14509            }
14510
14511            // don't allow a system upgrade unless the upgrade hash matches
14512            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14513                byte[] digestBytes = null;
14514                try {
14515                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14516                    updateDigest(digest, new File(pkg.baseCodePath));
14517                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14518                        for (String path : pkg.splitCodePaths) {
14519                            updateDigest(digest, new File(path));
14520                        }
14521                    }
14522                    digestBytes = digest.digest();
14523                } catch (NoSuchAlgorithmException | IOException e) {
14524                    res.setError(INSTALL_FAILED_INVALID_APK,
14525                            "Could not compute hash: " + pkgName);
14526                    return;
14527                }
14528                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14529                    res.setError(INSTALL_FAILED_INVALID_APK,
14530                            "New package fails restrict-update check: " + pkgName);
14531                    return;
14532                }
14533                // retain upgrade restriction
14534                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14535            }
14536
14537            // Check for shared user id changes
14538            String invalidPackageName =
14539                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14540            if (invalidPackageName != null) {
14541                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14542                        "Package " + invalidPackageName + " tried to change user "
14543                                + oldPackage.mSharedUserId);
14544                return;
14545            }
14546
14547            // In case of rollback, remember per-user/profile install state
14548            allUsers = sUserManager.getUserIds();
14549            installedUsers = ps.queryInstalledUsers(allUsers, true);
14550        }
14551
14552        // Update what is removed
14553        res.removedInfo = new PackageRemovedInfo();
14554        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14555        res.removedInfo.removedPackage = oldPackage.packageName;
14556        res.removedInfo.isUpdate = true;
14557        res.removedInfo.origUsers = installedUsers;
14558        final int childCount = (oldPackage.childPackages != null)
14559                ? oldPackage.childPackages.size() : 0;
14560        for (int i = 0; i < childCount; i++) {
14561            boolean childPackageUpdated = false;
14562            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14563            if (res.addedChildPackages != null) {
14564                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14565                if (childRes != null) {
14566                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14567                    childRes.removedInfo.removedPackage = childPkg.packageName;
14568                    childRes.removedInfo.isUpdate = true;
14569                    childPackageUpdated = true;
14570                }
14571            }
14572            if (!childPackageUpdated) {
14573                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14574                childRemovedRes.removedPackage = childPkg.packageName;
14575                childRemovedRes.isUpdate = false;
14576                childRemovedRes.dataRemoved = true;
14577                synchronized (mPackages) {
14578                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14579                    if (childPs != null) {
14580                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14581                    }
14582                }
14583                if (res.removedInfo.removedChildPackages == null) {
14584                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14585                }
14586                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14587            }
14588        }
14589
14590        boolean sysPkg = (isSystemApp(oldPackage));
14591        if (sysPkg) {
14592            // Set the system/privileged flags as needed
14593            final boolean privileged =
14594                    (oldPackage.applicationInfo.privateFlags
14595                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14596            final int systemPolicyFlags = policyFlags
14597                    | PackageParser.PARSE_IS_SYSTEM
14598                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14599
14600            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14601                    user, allUsers, installerPackageName, res);
14602        } else {
14603            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14604                    user, allUsers, installerPackageName, res);
14605        }
14606    }
14607
14608    public List<String> getPreviousCodePaths(String packageName) {
14609        final PackageSetting ps = mSettings.mPackages.get(packageName);
14610        final List<String> result = new ArrayList<String>();
14611        if (ps != null && ps.oldCodePaths != null) {
14612            result.addAll(ps.oldCodePaths);
14613        }
14614        return result;
14615    }
14616
14617    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14618            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14619            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14620        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14621                + deletedPackage);
14622
14623        String pkgName = deletedPackage.packageName;
14624        boolean deletedPkg = true;
14625        boolean addedPkg = false;
14626        boolean updatedSettings = false;
14627        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14628        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14629                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14630
14631        final long origUpdateTime = (pkg.mExtras != null)
14632                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14633
14634        // First delete the existing package while retaining the data directory
14635        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14636                res.removedInfo, true, pkg)) {
14637            // If the existing package wasn't successfully deleted
14638            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14639            deletedPkg = false;
14640        } else {
14641            // Successfully deleted the old package; proceed with replace.
14642
14643            // If deleted package lived in a container, give users a chance to
14644            // relinquish resources before killing.
14645            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14646                if (DEBUG_INSTALL) {
14647                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14648                }
14649                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14650                final ArrayList<String> pkgList = new ArrayList<String>(1);
14651                pkgList.add(deletedPackage.applicationInfo.packageName);
14652                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14653            }
14654
14655            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14656                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14657            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14658
14659            try {
14660                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14661                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14662                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14663
14664                // Update the in-memory copy of the previous code paths.
14665                PackageSetting ps = mSettings.mPackages.get(pkgName);
14666                if (!killApp) {
14667                    if (ps.oldCodePaths == null) {
14668                        ps.oldCodePaths = new ArraySet<>();
14669                    }
14670                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14671                    if (deletedPackage.splitCodePaths != null) {
14672                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14673                    }
14674                } else {
14675                    ps.oldCodePaths = null;
14676                }
14677                if (ps.childPackageNames != null) {
14678                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14679                        final String childPkgName = ps.childPackageNames.get(i);
14680                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14681                        childPs.oldCodePaths = ps.oldCodePaths;
14682                    }
14683                }
14684                prepareAppDataAfterInstallLIF(newPackage);
14685                addedPkg = true;
14686            } catch (PackageManagerException e) {
14687                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14688            }
14689        }
14690
14691        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14692            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14693
14694            // Revert all internal state mutations and added folders for the failed install
14695            if (addedPkg) {
14696                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14697                        res.removedInfo, true, null);
14698            }
14699
14700            // Restore the old package
14701            if (deletedPkg) {
14702                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14703                File restoreFile = new File(deletedPackage.codePath);
14704                // Parse old package
14705                boolean oldExternal = isExternal(deletedPackage);
14706                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14707                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14708                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14709                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14710                try {
14711                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14712                            null);
14713                } catch (PackageManagerException e) {
14714                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14715                            + e.getMessage());
14716                    return;
14717                }
14718
14719                synchronized (mPackages) {
14720                    // Ensure the installer package name up to date
14721                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14722
14723                    // Update permissions for restored package
14724                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14725
14726                    mSettings.writeLPr();
14727                }
14728
14729                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14730            }
14731        } else {
14732            synchronized (mPackages) {
14733                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14734                if (ps != null) {
14735                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14736                    if (res.removedInfo.removedChildPackages != null) {
14737                        final int childCount = res.removedInfo.removedChildPackages.size();
14738                        // Iterate in reverse as we may modify the collection
14739                        for (int i = childCount - 1; i >= 0; i--) {
14740                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14741                            if (res.addedChildPackages.containsKey(childPackageName)) {
14742                                res.removedInfo.removedChildPackages.removeAt(i);
14743                            } else {
14744                                PackageRemovedInfo childInfo = res.removedInfo
14745                                        .removedChildPackages.valueAt(i);
14746                                childInfo.removedForAllUsers = mPackages.get(
14747                                        childInfo.removedPackage) == null;
14748                            }
14749                        }
14750                    }
14751                }
14752            }
14753        }
14754    }
14755
14756    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14757            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14758            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14759        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14760                + ", old=" + deletedPackage);
14761
14762        final boolean disabledSystem;
14763
14764        // Remove existing system package
14765        removePackageLI(deletedPackage, true);
14766
14767        synchronized (mPackages) {
14768            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14769        }
14770        if (!disabledSystem) {
14771            // We didn't need to disable the .apk as a current system package,
14772            // which means we are replacing another update that is already
14773            // installed.  We need to make sure to delete the older one's .apk.
14774            res.removedInfo.args = createInstallArgsForExisting(0,
14775                    deletedPackage.applicationInfo.getCodePath(),
14776                    deletedPackage.applicationInfo.getResourcePath(),
14777                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14778        } else {
14779            res.removedInfo.args = null;
14780        }
14781
14782        // Successfully disabled the old package. Now proceed with re-installation
14783        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14784                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14785        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14786
14787        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14788        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14789                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14790
14791        PackageParser.Package newPackage = null;
14792        try {
14793            // Add the package to the internal data structures
14794            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14795
14796            // Set the update and install times
14797            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14798            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14799                    System.currentTimeMillis());
14800
14801            // Update the package dynamic state if succeeded
14802            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14803                // Now that the install succeeded make sure we remove data
14804                // directories for any child package the update removed.
14805                final int deletedChildCount = (deletedPackage.childPackages != null)
14806                        ? deletedPackage.childPackages.size() : 0;
14807                final int newChildCount = (newPackage.childPackages != null)
14808                        ? newPackage.childPackages.size() : 0;
14809                for (int i = 0; i < deletedChildCount; i++) {
14810                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14811                    boolean childPackageDeleted = true;
14812                    for (int j = 0; j < newChildCount; j++) {
14813                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14814                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14815                            childPackageDeleted = false;
14816                            break;
14817                        }
14818                    }
14819                    if (childPackageDeleted) {
14820                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14821                                deletedChildPkg.packageName);
14822                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14823                            PackageRemovedInfo removedChildRes = res.removedInfo
14824                                    .removedChildPackages.get(deletedChildPkg.packageName);
14825                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14826                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14827                        }
14828                    }
14829                }
14830
14831                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14832                prepareAppDataAfterInstallLIF(newPackage);
14833            }
14834        } catch (PackageManagerException e) {
14835            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14836            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14837        }
14838
14839        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14840            // Re installation failed. Restore old information
14841            // Remove new pkg information
14842            if (newPackage != null) {
14843                removeInstalledPackageLI(newPackage, true);
14844            }
14845            // Add back the old system package
14846            try {
14847                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14848            } catch (PackageManagerException e) {
14849                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14850            }
14851
14852            synchronized (mPackages) {
14853                if (disabledSystem) {
14854                    enableSystemPackageLPw(deletedPackage);
14855                }
14856
14857                // Ensure the installer package name up to date
14858                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14859
14860                // Update permissions for restored package
14861                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14862
14863                mSettings.writeLPr();
14864            }
14865
14866            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14867                    + " after failed upgrade");
14868        }
14869    }
14870
14871    /**
14872     * Checks whether the parent or any of the child packages have a change shared
14873     * user. For a package to be a valid update the shred users of the parent and
14874     * the children should match. We may later support changing child shared users.
14875     * @param oldPkg The updated package.
14876     * @param newPkg The update package.
14877     * @return The shared user that change between the versions.
14878     */
14879    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14880            PackageParser.Package newPkg) {
14881        // Check parent shared user
14882        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14883            return newPkg.packageName;
14884        }
14885        // Check child shared users
14886        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14887        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14888        for (int i = 0; i < newChildCount; i++) {
14889            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14890            // If this child was present, did it have the same shared user?
14891            for (int j = 0; j < oldChildCount; j++) {
14892                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14893                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14894                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14895                    return newChildPkg.packageName;
14896                }
14897            }
14898        }
14899        return null;
14900    }
14901
14902    private void removeNativeBinariesLI(PackageSetting ps) {
14903        // Remove the lib path for the parent package
14904        if (ps != null) {
14905            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14906            // Remove the lib path for the child packages
14907            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14908            for (int i = 0; i < childCount; i++) {
14909                PackageSetting childPs = null;
14910                synchronized (mPackages) {
14911                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14912                }
14913                if (childPs != null) {
14914                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14915                            .legacyNativeLibraryPathString);
14916                }
14917            }
14918        }
14919    }
14920
14921    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14922        // Enable the parent package
14923        mSettings.enableSystemPackageLPw(pkg.packageName);
14924        // Enable the child packages
14925        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14926        for (int i = 0; i < childCount; i++) {
14927            PackageParser.Package childPkg = pkg.childPackages.get(i);
14928            mSettings.enableSystemPackageLPw(childPkg.packageName);
14929        }
14930    }
14931
14932    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14933            PackageParser.Package newPkg) {
14934        // Disable the parent package (parent always replaced)
14935        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14936        // Disable the child packages
14937        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14938        for (int i = 0; i < childCount; i++) {
14939            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14940            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14941            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14942        }
14943        return disabled;
14944    }
14945
14946    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14947            String installerPackageName) {
14948        // Enable the parent package
14949        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14950        // Enable the child packages
14951        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14952        for (int i = 0; i < childCount; i++) {
14953            PackageParser.Package childPkg = pkg.childPackages.get(i);
14954            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14955        }
14956    }
14957
14958    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14959        // Collect all used permissions in the UID
14960        ArraySet<String> usedPermissions = new ArraySet<>();
14961        final int packageCount = su.packages.size();
14962        for (int i = 0; i < packageCount; i++) {
14963            PackageSetting ps = su.packages.valueAt(i);
14964            if (ps.pkg == null) {
14965                continue;
14966            }
14967            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14968            for (int j = 0; j < requestedPermCount; j++) {
14969                String permission = ps.pkg.requestedPermissions.get(j);
14970                BasePermission bp = mSettings.mPermissions.get(permission);
14971                if (bp != null) {
14972                    usedPermissions.add(permission);
14973                }
14974            }
14975        }
14976
14977        PermissionsState permissionsState = su.getPermissionsState();
14978        // Prune install permissions
14979        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14980        final int installPermCount = installPermStates.size();
14981        for (int i = installPermCount - 1; i >= 0;  i--) {
14982            PermissionState permissionState = installPermStates.get(i);
14983            if (!usedPermissions.contains(permissionState.getName())) {
14984                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14985                if (bp != null) {
14986                    permissionsState.revokeInstallPermission(bp);
14987                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14988                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14989                }
14990            }
14991        }
14992
14993        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14994
14995        // Prune runtime permissions
14996        for (int userId : allUserIds) {
14997            List<PermissionState> runtimePermStates = permissionsState
14998                    .getRuntimePermissionStates(userId);
14999            final int runtimePermCount = runtimePermStates.size();
15000            for (int i = runtimePermCount - 1; i >= 0; i--) {
15001                PermissionState permissionState = runtimePermStates.get(i);
15002                if (!usedPermissions.contains(permissionState.getName())) {
15003                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15004                    if (bp != null) {
15005                        permissionsState.revokeRuntimePermission(bp, userId);
15006                        permissionsState.updatePermissionFlags(bp, userId,
15007                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15008                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15009                                runtimePermissionChangedUserIds, userId);
15010                    }
15011                }
15012            }
15013        }
15014
15015        return runtimePermissionChangedUserIds;
15016    }
15017
15018    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15019            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15020        // Update the parent package setting
15021        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15022                res, user);
15023        // Update the child packages setting
15024        final int childCount = (newPackage.childPackages != null)
15025                ? newPackage.childPackages.size() : 0;
15026        for (int i = 0; i < childCount; i++) {
15027            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15028            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15029            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15030                    childRes.origUsers, childRes, user);
15031        }
15032    }
15033
15034    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15035            String installerPackageName, int[] allUsers, int[] installedForUsers,
15036            PackageInstalledInfo res, UserHandle user) {
15037        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15038
15039        String pkgName = newPackage.packageName;
15040        synchronized (mPackages) {
15041            //write settings. the installStatus will be incomplete at this stage.
15042            //note that the new package setting would have already been
15043            //added to mPackages. It hasn't been persisted yet.
15044            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15046            mSettings.writeLPr();
15047            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15048        }
15049
15050        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15051        synchronized (mPackages) {
15052            updatePermissionsLPw(newPackage.packageName, newPackage,
15053                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15054                            ? UPDATE_PERMISSIONS_ALL : 0));
15055            // For system-bundled packages, we assume that installing an upgraded version
15056            // of the package implies that the user actually wants to run that new code,
15057            // so we enable the package.
15058            PackageSetting ps = mSettings.mPackages.get(pkgName);
15059            final int userId = user.getIdentifier();
15060            if (ps != null) {
15061                if (isSystemApp(newPackage)) {
15062                    if (DEBUG_INSTALL) {
15063                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15064                    }
15065                    // Enable system package for requested users
15066                    if (res.origUsers != null) {
15067                        for (int origUserId : res.origUsers) {
15068                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15069                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15070                                        origUserId, installerPackageName);
15071                            }
15072                        }
15073                    }
15074                    // Also convey the prior install/uninstall state
15075                    if (allUsers != null && installedForUsers != null) {
15076                        for (int currentUserId : allUsers) {
15077                            final boolean installed = ArrayUtils.contains(
15078                                    installedForUsers, currentUserId);
15079                            if (DEBUG_INSTALL) {
15080                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15081                            }
15082                            ps.setInstalled(installed, currentUserId);
15083                        }
15084                        // these install state changes will be persisted in the
15085                        // upcoming call to mSettings.writeLPr().
15086                    }
15087                }
15088                // It's implied that when a user requests installation, they want the app to be
15089                // installed and enabled.
15090                if (userId != UserHandle.USER_ALL) {
15091                    ps.setInstalled(true, userId);
15092                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15093                }
15094            }
15095            res.name = pkgName;
15096            res.uid = newPackage.applicationInfo.uid;
15097            res.pkg = newPackage;
15098            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15099            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15100            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15101            //to update install status
15102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15103            mSettings.writeLPr();
15104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15105        }
15106
15107        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15108    }
15109
15110    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15111        try {
15112            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15113            installPackageLI(args, res);
15114        } finally {
15115            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15116        }
15117    }
15118
15119    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15120        final int installFlags = args.installFlags;
15121        final String installerPackageName = args.installerPackageName;
15122        final String volumeUuid = args.volumeUuid;
15123        final File tmpPackageFile = new File(args.getCodePath());
15124        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15125        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15126                || (args.volumeUuid != null));
15127        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15128        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15129        boolean replace = false;
15130        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15131        if (args.move != null) {
15132            // moving a complete application; perform an initial scan on the new install location
15133            scanFlags |= SCAN_INITIAL;
15134        }
15135        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15136            scanFlags |= SCAN_DONT_KILL_APP;
15137        }
15138
15139        // Result object to be returned
15140        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15141
15142        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15143
15144        // Sanity check
15145        if (ephemeral && (forwardLocked || onExternal)) {
15146            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15147                    + " external=" + onExternal);
15148            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15149            return;
15150        }
15151
15152        // Retrieve PackageSettings and parse package
15153        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15154                | PackageParser.PARSE_ENFORCE_CODE
15155                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15156                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15157                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15158                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15159        PackageParser pp = new PackageParser();
15160        pp.setSeparateProcesses(mSeparateProcesses);
15161        pp.setDisplayMetrics(mMetrics);
15162
15163        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15164        final PackageParser.Package pkg;
15165        try {
15166            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15167        } catch (PackageParserException e) {
15168            res.setError("Failed parse during installPackageLI", e);
15169            return;
15170        } finally {
15171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15172        }
15173
15174        // If we are installing a clustered package add results for the children
15175        if (pkg.childPackages != null) {
15176            synchronized (mPackages) {
15177                final int childCount = pkg.childPackages.size();
15178                for (int i = 0; i < childCount; i++) {
15179                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15180                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15181                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15182                    childRes.pkg = childPkg;
15183                    childRes.name = childPkg.packageName;
15184                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15185                    if (childPs != null) {
15186                        childRes.origUsers = childPs.queryInstalledUsers(
15187                                sUserManager.getUserIds(), true);
15188                    }
15189                    if ((mPackages.containsKey(childPkg.packageName))) {
15190                        childRes.removedInfo = new PackageRemovedInfo();
15191                        childRes.removedInfo.removedPackage = childPkg.packageName;
15192                    }
15193                    if (res.addedChildPackages == null) {
15194                        res.addedChildPackages = new ArrayMap<>();
15195                    }
15196                    res.addedChildPackages.put(childPkg.packageName, childRes);
15197                }
15198            }
15199        }
15200
15201        // If package doesn't declare API override, mark that we have an install
15202        // time CPU ABI override.
15203        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15204            pkg.cpuAbiOverride = args.abiOverride;
15205        }
15206
15207        String pkgName = res.name = pkg.packageName;
15208        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15209            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15210                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15211                return;
15212            }
15213        }
15214
15215        try {
15216            // either use what we've been given or parse directly from the APK
15217            if (args.certificates != null) {
15218                try {
15219                    PackageParser.populateCertificates(pkg, args.certificates);
15220                } catch (PackageParserException e) {
15221                    // there was something wrong with the certificates we were given;
15222                    // try to pull them from the APK
15223                    PackageParser.collectCertificates(pkg, parseFlags);
15224                }
15225            } else {
15226                PackageParser.collectCertificates(pkg, parseFlags);
15227            }
15228        } catch (PackageParserException e) {
15229            res.setError("Failed collect during installPackageLI", e);
15230            return;
15231        }
15232
15233        // Get rid of all references to package scan path via parser.
15234        pp = null;
15235        String oldCodePath = null;
15236        boolean systemApp = false;
15237        synchronized (mPackages) {
15238            // Check if installing already existing package
15239            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15240                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15241                if (pkg.mOriginalPackages != null
15242                        && pkg.mOriginalPackages.contains(oldName)
15243                        && mPackages.containsKey(oldName)) {
15244                    // This package is derived from an original package,
15245                    // and this device has been updating from that original
15246                    // name.  We must continue using the original name, so
15247                    // rename the new package here.
15248                    pkg.setPackageName(oldName);
15249                    pkgName = pkg.packageName;
15250                    replace = true;
15251                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15252                            + oldName + " pkgName=" + pkgName);
15253                } else if (mPackages.containsKey(pkgName)) {
15254                    // This package, under its official name, already exists
15255                    // on the device; we should replace it.
15256                    replace = true;
15257                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15258                }
15259
15260                // Child packages are installed through the parent package
15261                if (pkg.parentPackage != null) {
15262                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15263                            "Package " + pkg.packageName + " is child of package "
15264                                    + pkg.parentPackage.parentPackage + ". Child packages "
15265                                    + "can be updated only through the parent package.");
15266                    return;
15267                }
15268
15269                if (replace) {
15270                    // Prevent apps opting out from runtime permissions
15271                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15272                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15273                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15274                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15275                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15276                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15277                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15278                                        + " doesn't support runtime permissions but the old"
15279                                        + " target SDK " + oldTargetSdk + " does.");
15280                        return;
15281                    }
15282
15283                    // Prevent installing of child packages
15284                    if (oldPackage.parentPackage != null) {
15285                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15286                                "Package " + pkg.packageName + " is child of package "
15287                                        + oldPackage.parentPackage + ". Child packages "
15288                                        + "can be updated only through the parent package.");
15289                        return;
15290                    }
15291                }
15292            }
15293
15294            PackageSetting ps = mSettings.mPackages.get(pkgName);
15295            if (ps != null) {
15296                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15297
15298                // Quick sanity check that we're signed correctly if updating;
15299                // we'll check this again later when scanning, but we want to
15300                // bail early here before tripping over redefined permissions.
15301                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15302                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15303                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15304                                + pkg.packageName + " upgrade keys do not match the "
15305                                + "previously installed version");
15306                        return;
15307                    }
15308                } else {
15309                    try {
15310                        verifySignaturesLP(ps, pkg);
15311                    } catch (PackageManagerException e) {
15312                        res.setError(e.error, e.getMessage());
15313                        return;
15314                    }
15315                }
15316
15317                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15318                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15319                    systemApp = (ps.pkg.applicationInfo.flags &
15320                            ApplicationInfo.FLAG_SYSTEM) != 0;
15321                }
15322                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15323            }
15324
15325            // Check whether the newly-scanned package wants to define an already-defined perm
15326            int N = pkg.permissions.size();
15327            for (int i = N-1; i >= 0; i--) {
15328                PackageParser.Permission perm = pkg.permissions.get(i);
15329                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15330                if (bp != null) {
15331                    // If the defining package is signed with our cert, it's okay.  This
15332                    // also includes the "updating the same package" case, of course.
15333                    // "updating same package" could also involve key-rotation.
15334                    final boolean sigsOk;
15335                    if (bp.sourcePackage.equals(pkg.packageName)
15336                            && (bp.packageSetting instanceof PackageSetting)
15337                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15338                                    scanFlags))) {
15339                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15340                    } else {
15341                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15342                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15343                    }
15344                    if (!sigsOk) {
15345                        // If the owning package is the system itself, we log but allow
15346                        // install to proceed; we fail the install on all other permission
15347                        // redefinitions.
15348                        if (!bp.sourcePackage.equals("android")) {
15349                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15350                                    + pkg.packageName + " attempting to redeclare permission "
15351                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15352                            res.origPermission = perm.info.name;
15353                            res.origPackage = bp.sourcePackage;
15354                            return;
15355                        } else {
15356                            Slog.w(TAG, "Package " + pkg.packageName
15357                                    + " attempting to redeclare system permission "
15358                                    + perm.info.name + "; ignoring new declaration");
15359                            pkg.permissions.remove(i);
15360                        }
15361                    }
15362                }
15363            }
15364        }
15365
15366        if (systemApp) {
15367            if (onExternal) {
15368                // Abort update; system app can't be replaced with app on sdcard
15369                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15370                        "Cannot install updates to system apps on sdcard");
15371                return;
15372            } else if (ephemeral) {
15373                // Abort update; system app can't be replaced with an ephemeral app
15374                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15375                        "Cannot update a system app with an ephemeral app");
15376                return;
15377            }
15378        }
15379
15380        if (args.move != null) {
15381            // We did an in-place move, so dex is ready to roll
15382            scanFlags |= SCAN_NO_DEX;
15383            scanFlags |= SCAN_MOVE;
15384
15385            synchronized (mPackages) {
15386                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15387                if (ps == null) {
15388                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15389                            "Missing settings for moved package " + pkgName);
15390                }
15391
15392                // We moved the entire application as-is, so bring over the
15393                // previously derived ABI information.
15394                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15395                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15396            }
15397
15398        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15399            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15400            scanFlags |= SCAN_NO_DEX;
15401
15402            try {
15403                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15404                    args.abiOverride : pkg.cpuAbiOverride);
15405                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15406                        true /*extractLibs*/, mAppLib32InstallDir);
15407            } catch (PackageManagerException pme) {
15408                Slog.e(TAG, "Error deriving application ABI", pme);
15409                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15410                return;
15411            }
15412
15413            // Shared libraries for the package need to be updated.
15414            synchronized (mPackages) {
15415                try {
15416                    updateSharedLibrariesLPr(pkg, null);
15417                } catch (PackageManagerException e) {
15418                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15419                }
15420            }
15421            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15422            // Do not run PackageDexOptimizer through the local performDexOpt
15423            // method because `pkg` may not be in `mPackages` yet.
15424            //
15425            // Also, don't fail application installs if the dexopt step fails.
15426            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15427                    null /* instructionSets */, false /* checkProfiles */,
15428                    getCompilerFilterForReason(REASON_INSTALL),
15429                    getOrCreateCompilerPackageStats(pkg));
15430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15431
15432            // Notify BackgroundDexOptService that the package has been changed.
15433            // If this is an update of a package which used to fail to compile,
15434            // BDOS will remove it from its blacklist.
15435            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15436        }
15437
15438        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15439            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15440            return;
15441        }
15442
15443        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15444
15445        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15446                "installPackageLI")) {
15447            if (replace) {
15448                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15449                        installerPackageName, res);
15450            } else {
15451                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15452                        args.user, installerPackageName, volumeUuid, res);
15453            }
15454        }
15455        synchronized (mPackages) {
15456            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15457            if (ps != null) {
15458                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15459            }
15460
15461            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15462            for (int i = 0; i < childCount; i++) {
15463                PackageParser.Package childPkg = pkg.childPackages.get(i);
15464                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15465                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15466                if (childPs != null) {
15467                    childRes.newUsers = childPs.queryInstalledUsers(
15468                            sUserManager.getUserIds(), true);
15469                }
15470            }
15471        }
15472    }
15473
15474    private void startIntentFilterVerifications(int userId, boolean replacing,
15475            PackageParser.Package pkg) {
15476        if (mIntentFilterVerifierComponent == null) {
15477            Slog.w(TAG, "No IntentFilter verification will not be done as "
15478                    + "there is no IntentFilterVerifier available!");
15479            return;
15480        }
15481
15482        final int verifierUid = getPackageUid(
15483                mIntentFilterVerifierComponent.getPackageName(),
15484                MATCH_DEBUG_TRIAGED_MISSING,
15485                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15486
15487        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15488        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15489        mHandler.sendMessage(msg);
15490
15491        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15492        for (int i = 0; i < childCount; i++) {
15493            PackageParser.Package childPkg = pkg.childPackages.get(i);
15494            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15495            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15496            mHandler.sendMessage(msg);
15497        }
15498    }
15499
15500    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15501            PackageParser.Package pkg) {
15502        int size = pkg.activities.size();
15503        if (size == 0) {
15504            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15505                    "No activity, so no need to verify any IntentFilter!");
15506            return;
15507        }
15508
15509        final boolean hasDomainURLs = hasDomainURLs(pkg);
15510        if (!hasDomainURLs) {
15511            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15512                    "No domain URLs, so no need to verify any IntentFilter!");
15513            return;
15514        }
15515
15516        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15517                + " if any IntentFilter from the " + size
15518                + " Activities needs verification ...");
15519
15520        int count = 0;
15521        final String packageName = pkg.packageName;
15522
15523        synchronized (mPackages) {
15524            // If this is a new install and we see that we've already run verification for this
15525            // package, we have nothing to do: it means the state was restored from backup.
15526            if (!replacing) {
15527                IntentFilterVerificationInfo ivi =
15528                        mSettings.getIntentFilterVerificationLPr(packageName);
15529                if (ivi != null) {
15530                    if (DEBUG_DOMAIN_VERIFICATION) {
15531                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15532                                + ivi.getStatusString());
15533                    }
15534                    return;
15535                }
15536            }
15537
15538            // If any filters need to be verified, then all need to be.
15539            boolean needToVerify = false;
15540            for (PackageParser.Activity a : pkg.activities) {
15541                for (ActivityIntentInfo filter : a.intents) {
15542                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15543                        if (DEBUG_DOMAIN_VERIFICATION) {
15544                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15545                        }
15546                        needToVerify = true;
15547                        break;
15548                    }
15549                }
15550            }
15551
15552            if (needToVerify) {
15553                final int verificationId = mIntentFilterVerificationToken++;
15554                for (PackageParser.Activity a : pkg.activities) {
15555                    for (ActivityIntentInfo filter : a.intents) {
15556                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15557                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15558                                    "Verification needed for IntentFilter:" + filter.toString());
15559                            mIntentFilterVerifier.addOneIntentFilterVerification(
15560                                    verifierUid, userId, verificationId, filter, packageName);
15561                            count++;
15562                        }
15563                    }
15564                }
15565            }
15566        }
15567
15568        if (count > 0) {
15569            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15570                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15571                    +  " for userId:" + userId);
15572            mIntentFilterVerifier.startVerifications(userId);
15573        } else {
15574            if (DEBUG_DOMAIN_VERIFICATION) {
15575                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15576            }
15577        }
15578    }
15579
15580    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15581        final ComponentName cn  = filter.activity.getComponentName();
15582        final String packageName = cn.getPackageName();
15583
15584        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15585                packageName);
15586        if (ivi == null) {
15587            return true;
15588        }
15589        int status = ivi.getStatus();
15590        switch (status) {
15591            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15592            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15593                return true;
15594
15595            default:
15596                // Nothing to do
15597                return false;
15598        }
15599    }
15600
15601    private static boolean isMultiArch(ApplicationInfo info) {
15602        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15603    }
15604
15605    private static boolean isExternal(PackageParser.Package pkg) {
15606        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15607    }
15608
15609    private static boolean isExternal(PackageSetting ps) {
15610        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15611    }
15612
15613    private static boolean isEphemeral(PackageParser.Package pkg) {
15614        return pkg.applicationInfo.isEphemeralApp();
15615    }
15616
15617    private static boolean isEphemeral(PackageSetting ps) {
15618        return ps.pkg != null && isEphemeral(ps.pkg);
15619    }
15620
15621    private static boolean isSystemApp(PackageParser.Package pkg) {
15622        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15623    }
15624
15625    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15626        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15627    }
15628
15629    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15630        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15631    }
15632
15633    private static boolean isSystemApp(PackageSetting ps) {
15634        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15635    }
15636
15637    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15638        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15639    }
15640
15641    private int packageFlagsToInstallFlags(PackageSetting ps) {
15642        int installFlags = 0;
15643        if (isEphemeral(ps)) {
15644            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15645        }
15646        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15647            // This existing package was an external ASEC install when we have
15648            // the external flag without a UUID
15649            installFlags |= PackageManager.INSTALL_EXTERNAL;
15650        }
15651        if (ps.isForwardLocked()) {
15652            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15653        }
15654        return installFlags;
15655    }
15656
15657    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15658        if (isExternal(pkg)) {
15659            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15660                return StorageManager.UUID_PRIMARY_PHYSICAL;
15661            } else {
15662                return pkg.volumeUuid;
15663            }
15664        } else {
15665            return StorageManager.UUID_PRIVATE_INTERNAL;
15666        }
15667    }
15668
15669    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15670        if (isExternal(pkg)) {
15671            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15672                return mSettings.getExternalVersion();
15673            } else {
15674                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15675            }
15676        } else {
15677            return mSettings.getInternalVersion();
15678        }
15679    }
15680
15681    private void deleteTempPackageFiles() {
15682        final FilenameFilter filter = new FilenameFilter() {
15683            public boolean accept(File dir, String name) {
15684                return name.startsWith("vmdl") && name.endsWith(".tmp");
15685            }
15686        };
15687        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15688            file.delete();
15689        }
15690    }
15691
15692    @Override
15693    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15694            int flags) {
15695        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15696                flags);
15697    }
15698
15699    @Override
15700    public void deletePackage(final String packageName,
15701            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15702        mContext.enforceCallingOrSelfPermission(
15703                android.Manifest.permission.DELETE_PACKAGES, null);
15704        Preconditions.checkNotNull(packageName);
15705        Preconditions.checkNotNull(observer);
15706        final int uid = Binder.getCallingUid();
15707        if (!isOrphaned(packageName)
15708                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15709            try {
15710                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15711                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15712                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15713                observer.onUserActionRequired(intent);
15714            } catch (RemoteException re) {
15715            }
15716            return;
15717        }
15718        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15719        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15720        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15721            mContext.enforceCallingOrSelfPermission(
15722                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15723                    "deletePackage for user " + userId);
15724        }
15725
15726        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15727            try {
15728                observer.onPackageDeleted(packageName,
15729                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15730            } catch (RemoteException re) {
15731            }
15732            return;
15733        }
15734
15735        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15736            try {
15737                observer.onPackageDeleted(packageName,
15738                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15739            } catch (RemoteException re) {
15740            }
15741            return;
15742        }
15743
15744        if (DEBUG_REMOVE) {
15745            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15746                    + " deleteAllUsers: " + deleteAllUsers );
15747        }
15748        // Queue up an async operation since the package deletion may take a little while.
15749        mHandler.post(new Runnable() {
15750            public void run() {
15751                mHandler.removeCallbacks(this);
15752                int returnCode;
15753                if (!deleteAllUsers) {
15754                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15755                } else {
15756                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15757                    // If nobody is blocking uninstall, proceed with delete for all users
15758                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15759                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15760                    } else {
15761                        // Otherwise uninstall individually for users with blockUninstalls=false
15762                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15763                        for (int userId : users) {
15764                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15765                                returnCode = deletePackageX(packageName, userId, userFlags);
15766                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15767                                    Slog.w(TAG, "Package delete failed for user " + userId
15768                                            + ", returnCode " + returnCode);
15769                                }
15770                            }
15771                        }
15772                        // The app has only been marked uninstalled for certain users.
15773                        // We still need to report that delete was blocked
15774                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15775                    }
15776                }
15777                try {
15778                    observer.onPackageDeleted(packageName, returnCode, null);
15779                } catch (RemoteException e) {
15780                    Log.i(TAG, "Observer no longer exists.");
15781                } //end catch
15782            } //end run
15783        });
15784    }
15785
15786    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15787        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15788              || callingUid == Process.SYSTEM_UID) {
15789            return true;
15790        }
15791        final int callingUserId = UserHandle.getUserId(callingUid);
15792        // If the caller installed the pkgName, then allow it to silently uninstall.
15793        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15794            return true;
15795        }
15796
15797        // Allow package verifier to silently uninstall.
15798        if (mRequiredVerifierPackage != null &&
15799                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15800            return true;
15801        }
15802
15803        // Allow package uninstaller to silently uninstall.
15804        if (mRequiredUninstallerPackage != null &&
15805                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15806            return true;
15807        }
15808
15809        // Allow storage manager to silently uninstall.
15810        if (mStorageManagerPackage != null &&
15811                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15812            return true;
15813        }
15814        return false;
15815    }
15816
15817    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15818        int[] result = EMPTY_INT_ARRAY;
15819        for (int userId : userIds) {
15820            if (getBlockUninstallForUser(packageName, userId)) {
15821                result = ArrayUtils.appendInt(result, userId);
15822            }
15823        }
15824        return result;
15825    }
15826
15827    @Override
15828    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15829        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15830    }
15831
15832    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15833        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15834                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15835        try {
15836            if (dpm != null) {
15837                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15838                        /* callingUserOnly =*/ false);
15839                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15840                        : deviceOwnerComponentName.getPackageName();
15841                // Does the package contains the device owner?
15842                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15843                // this check is probably not needed, since DO should be registered as a device
15844                // admin on some user too. (Original bug for this: b/17657954)
15845                if (packageName.equals(deviceOwnerPackageName)) {
15846                    return true;
15847                }
15848                // Does it contain a device admin for any user?
15849                int[] users;
15850                if (userId == UserHandle.USER_ALL) {
15851                    users = sUserManager.getUserIds();
15852                } else {
15853                    users = new int[]{userId};
15854                }
15855                for (int i = 0; i < users.length; ++i) {
15856                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15857                        return true;
15858                    }
15859                }
15860            }
15861        } catch (RemoteException e) {
15862        }
15863        return false;
15864    }
15865
15866    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15867        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15868    }
15869
15870    /**
15871     *  This method is an internal method that could be get invoked either
15872     *  to delete an installed package or to clean up a failed installation.
15873     *  After deleting an installed package, a broadcast is sent to notify any
15874     *  listeners that the package has been removed. For cleaning up a failed
15875     *  installation, the broadcast is not necessary since the package's
15876     *  installation wouldn't have sent the initial broadcast either
15877     *  The key steps in deleting a package are
15878     *  deleting the package information in internal structures like mPackages,
15879     *  deleting the packages base directories through installd
15880     *  updating mSettings to reflect current status
15881     *  persisting settings for later use
15882     *  sending a broadcast if necessary
15883     */
15884    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15885        final PackageRemovedInfo info = new PackageRemovedInfo();
15886        final boolean res;
15887
15888        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15889                ? UserHandle.USER_ALL : userId;
15890
15891        if (isPackageDeviceAdmin(packageName, removeUser)) {
15892            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15893            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15894        }
15895
15896        PackageSetting uninstalledPs = null;
15897
15898        // for the uninstall-updates case and restricted profiles, remember the per-
15899        // user handle installed state
15900        int[] allUsers;
15901        synchronized (mPackages) {
15902            uninstalledPs = mSettings.mPackages.get(packageName);
15903            if (uninstalledPs == null) {
15904                Slog.w(TAG, "Not removing non-existent package " + packageName);
15905                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15906            }
15907            allUsers = sUserManager.getUserIds();
15908            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15909        }
15910
15911        final int freezeUser;
15912        if (isUpdatedSystemApp(uninstalledPs)
15913                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15914            // We're downgrading a system app, which will apply to all users, so
15915            // freeze them all during the downgrade
15916            freezeUser = UserHandle.USER_ALL;
15917        } else {
15918            freezeUser = removeUser;
15919        }
15920
15921        synchronized (mInstallLock) {
15922            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15923            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15924                    deleteFlags, "deletePackageX")) {
15925                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15926                        deleteFlags | REMOVE_CHATTY, info, true, null);
15927            }
15928            synchronized (mPackages) {
15929                if (res) {
15930                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15931                }
15932            }
15933        }
15934
15935        if (res) {
15936            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15937            info.sendPackageRemovedBroadcasts(killApp);
15938            info.sendSystemPackageUpdatedBroadcasts();
15939            info.sendSystemPackageAppearedBroadcasts();
15940        }
15941        // Force a gc here.
15942        Runtime.getRuntime().gc();
15943        // Delete the resources here after sending the broadcast to let
15944        // other processes clean up before deleting resources.
15945        if (info.args != null) {
15946            synchronized (mInstallLock) {
15947                info.args.doPostDeleteLI(true);
15948            }
15949        }
15950
15951        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15952    }
15953
15954    class PackageRemovedInfo {
15955        String removedPackage;
15956        int uid = -1;
15957        int removedAppId = -1;
15958        int[] origUsers;
15959        int[] removedUsers = null;
15960        boolean isRemovedPackageSystemUpdate = false;
15961        boolean isUpdate;
15962        boolean dataRemoved;
15963        boolean removedForAllUsers;
15964        // Clean up resources deleted packages.
15965        InstallArgs args = null;
15966        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15967        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15968
15969        void sendPackageRemovedBroadcasts(boolean killApp) {
15970            sendPackageRemovedBroadcastInternal(killApp);
15971            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15972            for (int i = 0; i < childCount; i++) {
15973                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15974                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15975            }
15976        }
15977
15978        void sendSystemPackageUpdatedBroadcasts() {
15979            if (isRemovedPackageSystemUpdate) {
15980                sendSystemPackageUpdatedBroadcastsInternal();
15981                final int childCount = (removedChildPackages != null)
15982                        ? removedChildPackages.size() : 0;
15983                for (int i = 0; i < childCount; i++) {
15984                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15985                    if (childInfo.isRemovedPackageSystemUpdate) {
15986                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15987                    }
15988                }
15989            }
15990        }
15991
15992        void sendSystemPackageAppearedBroadcasts() {
15993            final int packageCount = (appearedChildPackages != null)
15994                    ? appearedChildPackages.size() : 0;
15995            for (int i = 0; i < packageCount; i++) {
15996                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15997                sendPackageAddedForNewUsers(installedInfo.name, true,
15998                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
15999            }
16000        }
16001
16002        private void sendSystemPackageUpdatedBroadcastsInternal() {
16003            Bundle extras = new Bundle(2);
16004            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16005            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16006            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16007                    extras, 0, null, null, null);
16008            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16009                    extras, 0, null, null, null);
16010            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16011                    null, 0, removedPackage, null, null);
16012        }
16013
16014        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16015            Bundle extras = new Bundle(2);
16016            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16017            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16018            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16019            if (isUpdate || isRemovedPackageSystemUpdate) {
16020                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16021            }
16022            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16023            if (removedPackage != null) {
16024                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16025                        extras, 0, null, null, removedUsers);
16026                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16027                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16028                            removedPackage, extras, 0, null, null, removedUsers);
16029                }
16030            }
16031            if (removedAppId >= 0) {
16032                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16033                        removedUsers);
16034            }
16035        }
16036    }
16037
16038    /*
16039     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16040     * flag is not set, the data directory is removed as well.
16041     * make sure this flag is set for partially installed apps. If not its meaningless to
16042     * delete a partially installed application.
16043     */
16044    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16045            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16046        String packageName = ps.name;
16047        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16048        // Retrieve object to delete permissions for shared user later on
16049        final PackageParser.Package deletedPkg;
16050        final PackageSetting deletedPs;
16051        // reader
16052        synchronized (mPackages) {
16053            deletedPkg = mPackages.get(packageName);
16054            deletedPs = mSettings.mPackages.get(packageName);
16055            if (outInfo != null) {
16056                outInfo.removedPackage = packageName;
16057                outInfo.removedUsers = deletedPs != null
16058                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16059                        : null;
16060            }
16061        }
16062
16063        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16064
16065        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16066            final PackageParser.Package resolvedPkg;
16067            if (deletedPkg != null) {
16068                resolvedPkg = deletedPkg;
16069            } else {
16070                // We don't have a parsed package when it lives on an ejected
16071                // adopted storage device, so fake something together
16072                resolvedPkg = new PackageParser.Package(ps.name);
16073                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16074            }
16075            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16076                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16077            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16078            if (outInfo != null) {
16079                outInfo.dataRemoved = true;
16080            }
16081            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16082        }
16083
16084        // writer
16085        synchronized (mPackages) {
16086            if (deletedPs != null) {
16087                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16088                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16089                    clearDefaultBrowserIfNeeded(packageName);
16090                    if (outInfo != null) {
16091                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16092                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16093                    }
16094                    updatePermissionsLPw(deletedPs.name, null, 0);
16095                    if (deletedPs.sharedUser != null) {
16096                        // Remove permissions associated with package. Since runtime
16097                        // permissions are per user we have to kill the removed package
16098                        // or packages running under the shared user of the removed
16099                        // package if revoking the permissions requested only by the removed
16100                        // package is successful and this causes a change in gids.
16101                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16102                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16103                                    userId);
16104                            if (userIdToKill == UserHandle.USER_ALL
16105                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16106                                // If gids changed for this user, kill all affected packages.
16107                                mHandler.post(new Runnable() {
16108                                    @Override
16109                                    public void run() {
16110                                        // This has to happen with no lock held.
16111                                        killApplication(deletedPs.name, deletedPs.appId,
16112                                                KILL_APP_REASON_GIDS_CHANGED);
16113                                    }
16114                                });
16115                                break;
16116                            }
16117                        }
16118                    }
16119                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16120                }
16121                // make sure to preserve per-user disabled state if this removal was just
16122                // a downgrade of a system app to the factory package
16123                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16124                    if (DEBUG_REMOVE) {
16125                        Slog.d(TAG, "Propagating install state across downgrade");
16126                    }
16127                    for (int userId : allUserHandles) {
16128                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16129                        if (DEBUG_REMOVE) {
16130                            Slog.d(TAG, "    user " + userId + " => " + installed);
16131                        }
16132                        ps.setInstalled(installed, userId);
16133                    }
16134                }
16135            }
16136            // can downgrade to reader
16137            if (writeSettings) {
16138                // Save settings now
16139                mSettings.writeLPr();
16140            }
16141        }
16142        if (outInfo != null) {
16143            // A user ID was deleted here. Go through all users and remove it
16144            // from KeyStore.
16145            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16146        }
16147    }
16148
16149    static boolean locationIsPrivileged(File path) {
16150        try {
16151            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16152                    .getCanonicalPath();
16153            return path.getCanonicalPath().startsWith(privilegedAppDir);
16154        } catch (IOException e) {
16155            Slog.e(TAG, "Unable to access code path " + path);
16156        }
16157        return false;
16158    }
16159
16160    /*
16161     * Tries to delete system package.
16162     */
16163    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16164            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16165            boolean writeSettings) {
16166        if (deletedPs.parentPackageName != null) {
16167            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16168            return false;
16169        }
16170
16171        final boolean applyUserRestrictions
16172                = (allUserHandles != null) && (outInfo.origUsers != null);
16173        final PackageSetting disabledPs;
16174        // Confirm if the system package has been updated
16175        // An updated system app can be deleted. This will also have to restore
16176        // the system pkg from system partition
16177        // reader
16178        synchronized (mPackages) {
16179            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16180        }
16181
16182        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16183                + " disabledPs=" + disabledPs);
16184
16185        if (disabledPs == null) {
16186            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16187            return false;
16188        } else if (DEBUG_REMOVE) {
16189            Slog.d(TAG, "Deleting system pkg from data partition");
16190        }
16191
16192        if (DEBUG_REMOVE) {
16193            if (applyUserRestrictions) {
16194                Slog.d(TAG, "Remembering install states:");
16195                for (int userId : allUserHandles) {
16196                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16197                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16198                }
16199            }
16200        }
16201
16202        // Delete the updated package
16203        outInfo.isRemovedPackageSystemUpdate = true;
16204        if (outInfo.removedChildPackages != null) {
16205            final int childCount = (deletedPs.childPackageNames != null)
16206                    ? deletedPs.childPackageNames.size() : 0;
16207            for (int i = 0; i < childCount; i++) {
16208                String childPackageName = deletedPs.childPackageNames.get(i);
16209                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16210                        .contains(childPackageName)) {
16211                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16212                            childPackageName);
16213                    if (childInfo != null) {
16214                        childInfo.isRemovedPackageSystemUpdate = true;
16215                    }
16216                }
16217            }
16218        }
16219
16220        if (disabledPs.versionCode < deletedPs.versionCode) {
16221            // Delete data for downgrades
16222            flags &= ~PackageManager.DELETE_KEEP_DATA;
16223        } else {
16224            // Preserve data by setting flag
16225            flags |= PackageManager.DELETE_KEEP_DATA;
16226        }
16227
16228        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16229                outInfo, writeSettings, disabledPs.pkg);
16230        if (!ret) {
16231            return false;
16232        }
16233
16234        // writer
16235        synchronized (mPackages) {
16236            // Reinstate the old system package
16237            enableSystemPackageLPw(disabledPs.pkg);
16238            // Remove any native libraries from the upgraded package.
16239            removeNativeBinariesLI(deletedPs);
16240        }
16241
16242        // Install the system package
16243        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16244        int parseFlags = mDefParseFlags
16245                | PackageParser.PARSE_MUST_BE_APK
16246                | PackageParser.PARSE_IS_SYSTEM
16247                | PackageParser.PARSE_IS_SYSTEM_DIR;
16248        if (locationIsPrivileged(disabledPs.codePath)) {
16249            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16250        }
16251
16252        final PackageParser.Package newPkg;
16253        try {
16254            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16255        } catch (PackageManagerException e) {
16256            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16257                    + e.getMessage());
16258            return false;
16259        }
16260        try {
16261            // update shared libraries for the newly re-installed system package
16262            updateSharedLibrariesLPr(newPkg, null);
16263        } catch (PackageManagerException e) {
16264            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16265        }
16266
16267        prepareAppDataAfterInstallLIF(newPkg);
16268
16269        // writer
16270        synchronized (mPackages) {
16271            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16272
16273            // Propagate the permissions state as we do not want to drop on the floor
16274            // runtime permissions. The update permissions method below will take
16275            // care of removing obsolete permissions and grant install permissions.
16276            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16277            updatePermissionsLPw(newPkg.packageName, newPkg,
16278                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16279
16280            if (applyUserRestrictions) {
16281                if (DEBUG_REMOVE) {
16282                    Slog.d(TAG, "Propagating install state across reinstall");
16283                }
16284                for (int userId : allUserHandles) {
16285                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16286                    if (DEBUG_REMOVE) {
16287                        Slog.d(TAG, "    user " + userId + " => " + installed);
16288                    }
16289                    ps.setInstalled(installed, userId);
16290
16291                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16292                }
16293                // Regardless of writeSettings we need to ensure that this restriction
16294                // state propagation is persisted
16295                mSettings.writeAllUsersPackageRestrictionsLPr();
16296            }
16297            // can downgrade to reader here
16298            if (writeSettings) {
16299                mSettings.writeLPr();
16300            }
16301        }
16302        return true;
16303    }
16304
16305    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16306            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16307            PackageRemovedInfo outInfo, boolean writeSettings,
16308            PackageParser.Package replacingPackage) {
16309        synchronized (mPackages) {
16310            if (outInfo != null) {
16311                outInfo.uid = ps.appId;
16312            }
16313
16314            if (outInfo != null && outInfo.removedChildPackages != null) {
16315                final int childCount = (ps.childPackageNames != null)
16316                        ? ps.childPackageNames.size() : 0;
16317                for (int i = 0; i < childCount; i++) {
16318                    String childPackageName = ps.childPackageNames.get(i);
16319                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16320                    if (childPs == null) {
16321                        return false;
16322                    }
16323                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16324                            childPackageName);
16325                    if (childInfo != null) {
16326                        childInfo.uid = childPs.appId;
16327                    }
16328                }
16329            }
16330        }
16331
16332        // Delete package data from internal structures and also remove data if flag is set
16333        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16334
16335        // Delete the child packages data
16336        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16337        for (int i = 0; i < childCount; i++) {
16338            PackageSetting childPs;
16339            synchronized (mPackages) {
16340                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16341            }
16342            if (childPs != null) {
16343                PackageRemovedInfo childOutInfo = (outInfo != null
16344                        && outInfo.removedChildPackages != null)
16345                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16346                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16347                        && (replacingPackage != null
16348                        && !replacingPackage.hasChildPackage(childPs.name))
16349                        ? flags & ~DELETE_KEEP_DATA : flags;
16350                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16351                        deleteFlags, writeSettings);
16352            }
16353        }
16354
16355        // Delete application code and resources only for parent packages
16356        if (ps.parentPackageName == null) {
16357            if (deleteCodeAndResources && (outInfo != null)) {
16358                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16359                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16360                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16361            }
16362        }
16363
16364        return true;
16365    }
16366
16367    @Override
16368    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16369            int userId) {
16370        mContext.enforceCallingOrSelfPermission(
16371                android.Manifest.permission.DELETE_PACKAGES, null);
16372        synchronized (mPackages) {
16373            PackageSetting ps = mSettings.mPackages.get(packageName);
16374            if (ps == null) {
16375                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16376                return false;
16377            }
16378            if (!ps.getInstalled(userId)) {
16379                // Can't block uninstall for an app that is not installed or enabled.
16380                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16381                return false;
16382            }
16383            ps.setBlockUninstall(blockUninstall, userId);
16384            mSettings.writePackageRestrictionsLPr(userId);
16385        }
16386        return true;
16387    }
16388
16389    @Override
16390    public boolean getBlockUninstallForUser(String packageName, int userId) {
16391        synchronized (mPackages) {
16392            PackageSetting ps = mSettings.mPackages.get(packageName);
16393            if (ps == null) {
16394                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16395                return false;
16396            }
16397            return ps.getBlockUninstall(userId);
16398        }
16399    }
16400
16401    @Override
16402    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16403        int callingUid = Binder.getCallingUid();
16404        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16405            throw new SecurityException(
16406                    "setRequiredForSystemUser can only be run by the system or root");
16407        }
16408        synchronized (mPackages) {
16409            PackageSetting ps = mSettings.mPackages.get(packageName);
16410            if (ps == null) {
16411                Log.w(TAG, "Package doesn't exist: " + packageName);
16412                return false;
16413            }
16414            if (systemUserApp) {
16415                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16416            } else {
16417                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16418            }
16419            mSettings.writeLPr();
16420        }
16421        return true;
16422    }
16423
16424    /*
16425     * This method handles package deletion in general
16426     */
16427    private boolean deletePackageLIF(String packageName, UserHandle user,
16428            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16429            PackageRemovedInfo outInfo, boolean writeSettings,
16430            PackageParser.Package replacingPackage) {
16431        if (packageName == null) {
16432            Slog.w(TAG, "Attempt to delete null packageName.");
16433            return false;
16434        }
16435
16436        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16437
16438        PackageSetting ps;
16439
16440        synchronized (mPackages) {
16441            ps = mSettings.mPackages.get(packageName);
16442            if (ps == null) {
16443                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16444                return false;
16445            }
16446
16447            if (ps.parentPackageName != null && (!isSystemApp(ps)
16448                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16449                if (DEBUG_REMOVE) {
16450                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16451                            + ((user == null) ? UserHandle.USER_ALL : user));
16452                }
16453                final int removedUserId = (user != null) ? user.getIdentifier()
16454                        : UserHandle.USER_ALL;
16455                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16456                    return false;
16457                }
16458                markPackageUninstalledForUserLPw(ps, user);
16459                scheduleWritePackageRestrictionsLocked(user);
16460                return true;
16461            }
16462        }
16463
16464        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16465                && user.getIdentifier() != UserHandle.USER_ALL)) {
16466            // The caller is asking that the package only be deleted for a single
16467            // user.  To do this, we just mark its uninstalled state and delete
16468            // its data. If this is a system app, we only allow this to happen if
16469            // they have set the special DELETE_SYSTEM_APP which requests different
16470            // semantics than normal for uninstalling system apps.
16471            markPackageUninstalledForUserLPw(ps, user);
16472
16473            if (!isSystemApp(ps)) {
16474                // Do not uninstall the APK if an app should be cached
16475                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16476                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16477                    // Other user still have this package installed, so all
16478                    // we need to do is clear this user's data and save that
16479                    // it is uninstalled.
16480                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16481                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16482                        return false;
16483                    }
16484                    scheduleWritePackageRestrictionsLocked(user);
16485                    return true;
16486                } else {
16487                    // We need to set it back to 'installed' so the uninstall
16488                    // broadcasts will be sent correctly.
16489                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16490                    ps.setInstalled(true, user.getIdentifier());
16491                }
16492            } else {
16493                // This is a system app, so we assume that the
16494                // other users still have this package installed, so all
16495                // we need to do is clear this user's data and save that
16496                // it is uninstalled.
16497                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16498                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16499                    return false;
16500                }
16501                scheduleWritePackageRestrictionsLocked(user);
16502                return true;
16503            }
16504        }
16505
16506        // If we are deleting a composite package for all users, keep track
16507        // of result for each child.
16508        if (ps.childPackageNames != null && outInfo != null) {
16509            synchronized (mPackages) {
16510                final int childCount = ps.childPackageNames.size();
16511                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16512                for (int i = 0; i < childCount; i++) {
16513                    String childPackageName = ps.childPackageNames.get(i);
16514                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16515                    childInfo.removedPackage = childPackageName;
16516                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16517                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16518                    if (childPs != null) {
16519                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16520                    }
16521                }
16522            }
16523        }
16524
16525        boolean ret = false;
16526        if (isSystemApp(ps)) {
16527            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16528            // When an updated system application is deleted we delete the existing resources
16529            // as well and fall back to existing code in system partition
16530            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16531        } else {
16532            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16533            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16534                    outInfo, writeSettings, replacingPackage);
16535        }
16536
16537        // Take a note whether we deleted the package for all users
16538        if (outInfo != null) {
16539            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16540            if (outInfo.removedChildPackages != null) {
16541                synchronized (mPackages) {
16542                    final int childCount = outInfo.removedChildPackages.size();
16543                    for (int i = 0; i < childCount; i++) {
16544                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16545                        if (childInfo != null) {
16546                            childInfo.removedForAllUsers = mPackages.get(
16547                                    childInfo.removedPackage) == null;
16548                        }
16549                    }
16550                }
16551            }
16552            // If we uninstalled an update to a system app there may be some
16553            // child packages that appeared as they are declared in the system
16554            // app but were not declared in the update.
16555            if (isSystemApp(ps)) {
16556                synchronized (mPackages) {
16557                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16558                    final int childCount = (updatedPs.childPackageNames != null)
16559                            ? updatedPs.childPackageNames.size() : 0;
16560                    for (int i = 0; i < childCount; i++) {
16561                        String childPackageName = updatedPs.childPackageNames.get(i);
16562                        if (outInfo.removedChildPackages == null
16563                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16564                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16565                            if (childPs == null) {
16566                                continue;
16567                            }
16568                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16569                            installRes.name = childPackageName;
16570                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16571                            installRes.pkg = mPackages.get(childPackageName);
16572                            installRes.uid = childPs.pkg.applicationInfo.uid;
16573                            if (outInfo.appearedChildPackages == null) {
16574                                outInfo.appearedChildPackages = new ArrayMap<>();
16575                            }
16576                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16577                        }
16578                    }
16579                }
16580            }
16581        }
16582
16583        return ret;
16584    }
16585
16586    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16587        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16588                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16589        for (int nextUserId : userIds) {
16590            if (DEBUG_REMOVE) {
16591                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16592            }
16593            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16594                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16595                    false /*hidden*/, false /*suspended*/, null, null, null,
16596                    false /*blockUninstall*/,
16597                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16598        }
16599    }
16600
16601    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16602            PackageRemovedInfo outInfo) {
16603        final PackageParser.Package pkg;
16604        synchronized (mPackages) {
16605            pkg = mPackages.get(ps.name);
16606        }
16607
16608        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16609                : new int[] {userId};
16610        for (int nextUserId : userIds) {
16611            if (DEBUG_REMOVE) {
16612                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16613                        + nextUserId);
16614            }
16615
16616            destroyAppDataLIF(pkg, userId,
16617                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16618            destroyAppProfilesLIF(pkg, userId);
16619            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16620            schedulePackageCleaning(ps.name, nextUserId, false);
16621            synchronized (mPackages) {
16622                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16623                    scheduleWritePackageRestrictionsLocked(nextUserId);
16624                }
16625                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16626            }
16627        }
16628
16629        if (outInfo != null) {
16630            outInfo.removedPackage = ps.name;
16631            outInfo.removedAppId = ps.appId;
16632            outInfo.removedUsers = userIds;
16633        }
16634
16635        return true;
16636    }
16637
16638    private final class ClearStorageConnection implements ServiceConnection {
16639        IMediaContainerService mContainerService;
16640
16641        @Override
16642        public void onServiceConnected(ComponentName name, IBinder service) {
16643            synchronized (this) {
16644                mContainerService = IMediaContainerService.Stub
16645                        .asInterface(Binder.allowBlocking(service));
16646                notifyAll();
16647            }
16648        }
16649
16650        @Override
16651        public void onServiceDisconnected(ComponentName name) {
16652        }
16653    }
16654
16655    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16656        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16657
16658        final boolean mounted;
16659        if (Environment.isExternalStorageEmulated()) {
16660            mounted = true;
16661        } else {
16662            final String status = Environment.getExternalStorageState();
16663
16664            mounted = status.equals(Environment.MEDIA_MOUNTED)
16665                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16666        }
16667
16668        if (!mounted) {
16669            return;
16670        }
16671
16672        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16673        int[] users;
16674        if (userId == UserHandle.USER_ALL) {
16675            users = sUserManager.getUserIds();
16676        } else {
16677            users = new int[] { userId };
16678        }
16679        final ClearStorageConnection conn = new ClearStorageConnection();
16680        if (mContext.bindServiceAsUser(
16681                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16682            try {
16683                for (int curUser : users) {
16684                    long timeout = SystemClock.uptimeMillis() + 5000;
16685                    synchronized (conn) {
16686                        long now;
16687                        while (conn.mContainerService == null &&
16688                                (now = SystemClock.uptimeMillis()) < timeout) {
16689                            try {
16690                                conn.wait(timeout - now);
16691                            } catch (InterruptedException e) {
16692                            }
16693                        }
16694                    }
16695                    if (conn.mContainerService == null) {
16696                        return;
16697                    }
16698
16699                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16700                    clearDirectory(conn.mContainerService,
16701                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16702                    if (allData) {
16703                        clearDirectory(conn.mContainerService,
16704                                userEnv.buildExternalStorageAppDataDirs(packageName));
16705                        clearDirectory(conn.mContainerService,
16706                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16707                    }
16708                }
16709            } finally {
16710                mContext.unbindService(conn);
16711            }
16712        }
16713    }
16714
16715    @Override
16716    public void clearApplicationProfileData(String packageName) {
16717        enforceSystemOrRoot("Only the system can clear all profile data");
16718
16719        final PackageParser.Package pkg;
16720        synchronized (mPackages) {
16721            pkg = mPackages.get(packageName);
16722        }
16723
16724        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16725            synchronized (mInstallLock) {
16726                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16727                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16728                        true /* removeBaseMarker */);
16729            }
16730        }
16731    }
16732
16733    @Override
16734    public void clearApplicationUserData(final String packageName,
16735            final IPackageDataObserver observer, final int userId) {
16736        mContext.enforceCallingOrSelfPermission(
16737                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16738
16739        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16740                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16741
16742        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16743            throw new SecurityException("Cannot clear data for a protected package: "
16744                    + packageName);
16745        }
16746        // Queue up an async operation since the package deletion may take a little while.
16747        mHandler.post(new Runnable() {
16748            public void run() {
16749                mHandler.removeCallbacks(this);
16750                final boolean succeeded;
16751                try (PackageFreezer freezer = freezePackage(packageName,
16752                        "clearApplicationUserData")) {
16753                    synchronized (mInstallLock) {
16754                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16755                    }
16756                    clearExternalStorageDataSync(packageName, userId, true);
16757                }
16758                if (succeeded) {
16759                    // invoke DeviceStorageMonitor's update method to clear any notifications
16760                    DeviceStorageMonitorInternal dsm = LocalServices
16761                            .getService(DeviceStorageMonitorInternal.class);
16762                    if (dsm != null) {
16763                        dsm.checkMemory();
16764                    }
16765                }
16766                if(observer != null) {
16767                    try {
16768                        observer.onRemoveCompleted(packageName, succeeded);
16769                    } catch (RemoteException e) {
16770                        Log.i(TAG, "Observer no longer exists.");
16771                    }
16772                } //end if observer
16773            } //end run
16774        });
16775    }
16776
16777    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16778        if (packageName == null) {
16779            Slog.w(TAG, "Attempt to delete null packageName.");
16780            return false;
16781        }
16782
16783        // Try finding details about the requested package
16784        PackageParser.Package pkg;
16785        synchronized (mPackages) {
16786            pkg = mPackages.get(packageName);
16787            if (pkg == null) {
16788                final PackageSetting ps = mSettings.mPackages.get(packageName);
16789                if (ps != null) {
16790                    pkg = ps.pkg;
16791                }
16792            }
16793
16794            if (pkg == null) {
16795                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16796                return false;
16797            }
16798
16799            PackageSetting ps = (PackageSetting) pkg.mExtras;
16800            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16801        }
16802
16803        clearAppDataLIF(pkg, userId,
16804                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16805
16806        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16807        removeKeystoreDataIfNeeded(userId, appId);
16808
16809        UserManagerInternal umInternal = getUserManagerInternal();
16810        final int flags;
16811        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16812            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16813        } else if (umInternal.isUserRunning(userId)) {
16814            flags = StorageManager.FLAG_STORAGE_DE;
16815        } else {
16816            flags = 0;
16817        }
16818        prepareAppDataContentsLIF(pkg, userId, flags);
16819
16820        return true;
16821    }
16822
16823    /**
16824     * Reverts user permission state changes (permissions and flags) in
16825     * all packages for a given user.
16826     *
16827     * @param userId The device user for which to do a reset.
16828     */
16829    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16830        final int packageCount = mPackages.size();
16831        for (int i = 0; i < packageCount; i++) {
16832            PackageParser.Package pkg = mPackages.valueAt(i);
16833            PackageSetting ps = (PackageSetting) pkg.mExtras;
16834            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16835        }
16836    }
16837
16838    private void resetNetworkPolicies(int userId) {
16839        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16840    }
16841
16842    /**
16843     * Reverts user permission state changes (permissions and flags).
16844     *
16845     * @param ps The package for which to reset.
16846     * @param userId The device user for which to do a reset.
16847     */
16848    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16849            final PackageSetting ps, final int userId) {
16850        if (ps.pkg == null) {
16851            return;
16852        }
16853
16854        // These are flags that can change base on user actions.
16855        final int userSettableMask = FLAG_PERMISSION_USER_SET
16856                | FLAG_PERMISSION_USER_FIXED
16857                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16858                | FLAG_PERMISSION_REVIEW_REQUIRED;
16859
16860        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16861                | FLAG_PERMISSION_POLICY_FIXED;
16862
16863        boolean writeInstallPermissions = false;
16864        boolean writeRuntimePermissions = false;
16865
16866        final int permissionCount = ps.pkg.requestedPermissions.size();
16867        for (int i = 0; i < permissionCount; i++) {
16868            String permission = ps.pkg.requestedPermissions.get(i);
16869
16870            BasePermission bp = mSettings.mPermissions.get(permission);
16871            if (bp == null) {
16872                continue;
16873            }
16874
16875            // If shared user we just reset the state to which only this app contributed.
16876            if (ps.sharedUser != null) {
16877                boolean used = false;
16878                final int packageCount = ps.sharedUser.packages.size();
16879                for (int j = 0; j < packageCount; j++) {
16880                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16881                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16882                            && pkg.pkg.requestedPermissions.contains(permission)) {
16883                        used = true;
16884                        break;
16885                    }
16886                }
16887                if (used) {
16888                    continue;
16889                }
16890            }
16891
16892            PermissionsState permissionsState = ps.getPermissionsState();
16893
16894            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16895
16896            // Always clear the user settable flags.
16897            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16898                    bp.name) != null;
16899            // If permission review is enabled and this is a legacy app, mark the
16900            // permission as requiring a review as this is the initial state.
16901            int flags = 0;
16902            if (mPermissionReviewRequired
16903                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16904                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16905            }
16906            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16907                if (hasInstallState) {
16908                    writeInstallPermissions = true;
16909                } else {
16910                    writeRuntimePermissions = true;
16911                }
16912            }
16913
16914            // Below is only runtime permission handling.
16915            if (!bp.isRuntime()) {
16916                continue;
16917            }
16918
16919            // Never clobber system or policy.
16920            if ((oldFlags & policyOrSystemFlags) != 0) {
16921                continue;
16922            }
16923
16924            // If this permission was granted by default, make sure it is.
16925            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16926                if (permissionsState.grantRuntimePermission(bp, userId)
16927                        != PERMISSION_OPERATION_FAILURE) {
16928                    writeRuntimePermissions = true;
16929                }
16930            // If permission review is enabled the permissions for a legacy apps
16931            // are represented as constantly granted runtime ones, so don't revoke.
16932            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16933                // Otherwise, reset the permission.
16934                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16935                switch (revokeResult) {
16936                    case PERMISSION_OPERATION_SUCCESS:
16937                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16938                        writeRuntimePermissions = true;
16939                        final int appId = ps.appId;
16940                        mHandler.post(new Runnable() {
16941                            @Override
16942                            public void run() {
16943                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16944                            }
16945                        });
16946                    } break;
16947                }
16948            }
16949        }
16950
16951        // Synchronously write as we are taking permissions away.
16952        if (writeRuntimePermissions) {
16953            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16954        }
16955
16956        // Synchronously write as we are taking permissions away.
16957        if (writeInstallPermissions) {
16958            mSettings.writeLPr();
16959        }
16960    }
16961
16962    /**
16963     * Remove entries from the keystore daemon. Will only remove it if the
16964     * {@code appId} is valid.
16965     */
16966    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16967        if (appId < 0) {
16968            return;
16969        }
16970
16971        final KeyStore keyStore = KeyStore.getInstance();
16972        if (keyStore != null) {
16973            if (userId == UserHandle.USER_ALL) {
16974                for (final int individual : sUserManager.getUserIds()) {
16975                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16976                }
16977            } else {
16978                keyStore.clearUid(UserHandle.getUid(userId, appId));
16979            }
16980        } else {
16981            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16982        }
16983    }
16984
16985    @Override
16986    public void deleteApplicationCacheFiles(final String packageName,
16987            final IPackageDataObserver observer) {
16988        final int userId = UserHandle.getCallingUserId();
16989        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16990    }
16991
16992    @Override
16993    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16994            final IPackageDataObserver observer) {
16995        mContext.enforceCallingOrSelfPermission(
16996                android.Manifest.permission.DELETE_CACHE_FILES, null);
16997        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16998                /* requireFullPermission= */ true, /* checkShell= */ false,
16999                "delete application cache files");
17000
17001        final PackageParser.Package pkg;
17002        synchronized (mPackages) {
17003            pkg = mPackages.get(packageName);
17004        }
17005
17006        // Queue up an async operation since the package deletion may take a little while.
17007        mHandler.post(new Runnable() {
17008            public void run() {
17009                synchronized (mInstallLock) {
17010                    final int flags = StorageManager.FLAG_STORAGE_DE
17011                            | StorageManager.FLAG_STORAGE_CE;
17012                    // We're only clearing cache files, so we don't care if the
17013                    // app is unfrozen and still able to run
17014                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17015                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17016                }
17017                clearExternalStorageDataSync(packageName, userId, false);
17018                if (observer != null) {
17019                    try {
17020                        observer.onRemoveCompleted(packageName, true);
17021                    } catch (RemoteException e) {
17022                        Log.i(TAG, "Observer no longer exists.");
17023                    }
17024                }
17025            }
17026        });
17027    }
17028
17029    @Override
17030    public void getPackageSizeInfo(final String packageName, int userHandle,
17031            final IPackageStatsObserver observer) {
17032        mContext.enforceCallingOrSelfPermission(
17033                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17034        if (packageName == null) {
17035            throw new IllegalArgumentException("Attempt to get size of null packageName");
17036        }
17037
17038        PackageStats stats = new PackageStats(packageName, userHandle);
17039
17040        /*
17041         * Queue up an async operation since the package measurement may take a
17042         * little while.
17043         */
17044        Message msg = mHandler.obtainMessage(INIT_COPY);
17045        msg.obj = new MeasureParams(stats, observer);
17046        mHandler.sendMessage(msg);
17047    }
17048
17049    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17050        final PackageSetting ps;
17051        synchronized (mPackages) {
17052            ps = mSettings.mPackages.get(packageName);
17053            if (ps == null) {
17054                Slog.w(TAG, "Failed to find settings for " + packageName);
17055                return false;
17056            }
17057        }
17058        try {
17059            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17060                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17061                    ps.getCeDataInode(userId), ps.codePathString, stats);
17062        } catch (InstallerException e) {
17063            Slog.w(TAG, String.valueOf(e));
17064            return false;
17065        }
17066
17067        // For now, ignore code size of packages on system partition
17068        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17069            stats.codeSize = 0;
17070        }
17071
17072        return true;
17073    }
17074
17075    private int getUidTargetSdkVersionLockedLPr(int uid) {
17076        Object obj = mSettings.getUserIdLPr(uid);
17077        if (obj instanceof SharedUserSetting) {
17078            final SharedUserSetting sus = (SharedUserSetting) obj;
17079            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17080            final Iterator<PackageSetting> it = sus.packages.iterator();
17081            while (it.hasNext()) {
17082                final PackageSetting ps = it.next();
17083                if (ps.pkg != null) {
17084                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17085                    if (v < vers) vers = v;
17086                }
17087            }
17088            return vers;
17089        } else if (obj instanceof PackageSetting) {
17090            final PackageSetting ps = (PackageSetting) obj;
17091            if (ps.pkg != null) {
17092                return ps.pkg.applicationInfo.targetSdkVersion;
17093            }
17094        }
17095        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17096    }
17097
17098    @Override
17099    public void addPreferredActivity(IntentFilter filter, int match,
17100            ComponentName[] set, ComponentName activity, int userId) {
17101        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17102                "Adding preferred");
17103    }
17104
17105    private void addPreferredActivityInternal(IntentFilter filter, int match,
17106            ComponentName[] set, ComponentName activity, boolean always, int userId,
17107            String opname) {
17108        // writer
17109        int callingUid = Binder.getCallingUid();
17110        enforceCrossUserPermission(callingUid, userId,
17111                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17112        if (filter.countActions() == 0) {
17113            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17114            return;
17115        }
17116        synchronized (mPackages) {
17117            if (mContext.checkCallingOrSelfPermission(
17118                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17119                    != PackageManager.PERMISSION_GRANTED) {
17120                if (getUidTargetSdkVersionLockedLPr(callingUid)
17121                        < Build.VERSION_CODES.FROYO) {
17122                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17123                            + callingUid);
17124                    return;
17125                }
17126                mContext.enforceCallingOrSelfPermission(
17127                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17128            }
17129
17130            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17131            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17132                    + userId + ":");
17133            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17134            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17135            scheduleWritePackageRestrictionsLocked(userId);
17136            postPreferredActivityChangedBroadcast(userId);
17137        }
17138    }
17139
17140    private void postPreferredActivityChangedBroadcast(int userId) {
17141        mHandler.post(() -> {
17142            final IActivityManager am = ActivityManager.getService();
17143            if (am == null) {
17144                return;
17145            }
17146
17147            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17148            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17149            try {
17150                am.broadcastIntent(null, intent, null, null,
17151                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17152                        null, false, false, userId);
17153            } catch (RemoteException e) {
17154            }
17155        });
17156    }
17157
17158    @Override
17159    public void replacePreferredActivity(IntentFilter filter, int match,
17160            ComponentName[] set, ComponentName activity, int userId) {
17161        if (filter.countActions() != 1) {
17162            throw new IllegalArgumentException(
17163                    "replacePreferredActivity expects filter to have only 1 action.");
17164        }
17165        if (filter.countDataAuthorities() != 0
17166                || filter.countDataPaths() != 0
17167                || filter.countDataSchemes() > 1
17168                || filter.countDataTypes() != 0) {
17169            throw new IllegalArgumentException(
17170                    "replacePreferredActivity expects filter to have no data authorities, " +
17171                    "paths, or types; and at most one scheme.");
17172        }
17173
17174        final int callingUid = Binder.getCallingUid();
17175        enforceCrossUserPermission(callingUid, userId,
17176                true /* requireFullPermission */, false /* checkShell */,
17177                "replace preferred activity");
17178        synchronized (mPackages) {
17179            if (mContext.checkCallingOrSelfPermission(
17180                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17181                    != PackageManager.PERMISSION_GRANTED) {
17182                if (getUidTargetSdkVersionLockedLPr(callingUid)
17183                        < Build.VERSION_CODES.FROYO) {
17184                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17185                            + Binder.getCallingUid());
17186                    return;
17187                }
17188                mContext.enforceCallingOrSelfPermission(
17189                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17190            }
17191
17192            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17193            if (pir != null) {
17194                // Get all of the existing entries that exactly match this filter.
17195                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17196                if (existing != null && existing.size() == 1) {
17197                    PreferredActivity cur = existing.get(0);
17198                    if (DEBUG_PREFERRED) {
17199                        Slog.i(TAG, "Checking replace of preferred:");
17200                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17201                        if (!cur.mPref.mAlways) {
17202                            Slog.i(TAG, "  -- CUR; not mAlways!");
17203                        } else {
17204                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17205                            Slog.i(TAG, "  -- CUR: mSet="
17206                                    + Arrays.toString(cur.mPref.mSetComponents));
17207                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17208                            Slog.i(TAG, "  -- NEW: mMatch="
17209                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17210                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17211                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17212                        }
17213                    }
17214                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17215                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17216                            && cur.mPref.sameSet(set)) {
17217                        // Setting the preferred activity to what it happens to be already
17218                        if (DEBUG_PREFERRED) {
17219                            Slog.i(TAG, "Replacing with same preferred activity "
17220                                    + cur.mPref.mShortComponent + " for user "
17221                                    + userId + ":");
17222                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17223                        }
17224                        return;
17225                    }
17226                }
17227
17228                if (existing != null) {
17229                    if (DEBUG_PREFERRED) {
17230                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17231                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17232                    }
17233                    for (int i = 0; i < existing.size(); i++) {
17234                        PreferredActivity pa = existing.get(i);
17235                        if (DEBUG_PREFERRED) {
17236                            Slog.i(TAG, "Removing existing preferred activity "
17237                                    + pa.mPref.mComponent + ":");
17238                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17239                        }
17240                        pir.removeFilter(pa);
17241                    }
17242                }
17243            }
17244            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17245                    "Replacing preferred");
17246        }
17247    }
17248
17249    @Override
17250    public void clearPackagePreferredActivities(String packageName) {
17251        final int uid = Binder.getCallingUid();
17252        // writer
17253        synchronized (mPackages) {
17254            PackageParser.Package pkg = mPackages.get(packageName);
17255            if (pkg == null || pkg.applicationInfo.uid != uid) {
17256                if (mContext.checkCallingOrSelfPermission(
17257                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17258                        != PackageManager.PERMISSION_GRANTED) {
17259                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17260                            < Build.VERSION_CODES.FROYO) {
17261                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17262                                + Binder.getCallingUid());
17263                        return;
17264                    }
17265                    mContext.enforceCallingOrSelfPermission(
17266                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17267                }
17268            }
17269
17270            int user = UserHandle.getCallingUserId();
17271            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17272                scheduleWritePackageRestrictionsLocked(user);
17273            }
17274        }
17275    }
17276
17277    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17278    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17279        ArrayList<PreferredActivity> removed = null;
17280        boolean changed = false;
17281        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17282            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17283            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17284            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17285                continue;
17286            }
17287            Iterator<PreferredActivity> it = pir.filterIterator();
17288            while (it.hasNext()) {
17289                PreferredActivity pa = it.next();
17290                // Mark entry for removal only if it matches the package name
17291                // and the entry is of type "always".
17292                if (packageName == null ||
17293                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17294                                && pa.mPref.mAlways)) {
17295                    if (removed == null) {
17296                        removed = new ArrayList<PreferredActivity>();
17297                    }
17298                    removed.add(pa);
17299                }
17300            }
17301            if (removed != null) {
17302                for (int j=0; j<removed.size(); j++) {
17303                    PreferredActivity pa = removed.get(j);
17304                    pir.removeFilter(pa);
17305                }
17306                changed = true;
17307            }
17308        }
17309        if (changed) {
17310            postPreferredActivityChangedBroadcast(userId);
17311        }
17312        return changed;
17313    }
17314
17315    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17316    private void clearIntentFilterVerificationsLPw(int userId) {
17317        final int packageCount = mPackages.size();
17318        for (int i = 0; i < packageCount; i++) {
17319            PackageParser.Package pkg = mPackages.valueAt(i);
17320            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17321        }
17322    }
17323
17324    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17325    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17326        if (userId == UserHandle.USER_ALL) {
17327            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17328                    sUserManager.getUserIds())) {
17329                for (int oneUserId : sUserManager.getUserIds()) {
17330                    scheduleWritePackageRestrictionsLocked(oneUserId);
17331                }
17332            }
17333        } else {
17334            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17335                scheduleWritePackageRestrictionsLocked(userId);
17336            }
17337        }
17338    }
17339
17340    void clearDefaultBrowserIfNeeded(String packageName) {
17341        for (int oneUserId : sUserManager.getUserIds()) {
17342            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17343            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17344            if (packageName.equals(defaultBrowserPackageName)) {
17345                setDefaultBrowserPackageName(null, oneUserId);
17346            }
17347        }
17348    }
17349
17350    @Override
17351    public void resetApplicationPreferences(int userId) {
17352        mContext.enforceCallingOrSelfPermission(
17353                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17354        final long identity = Binder.clearCallingIdentity();
17355        // writer
17356        try {
17357            synchronized (mPackages) {
17358                clearPackagePreferredActivitiesLPw(null, userId);
17359                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17360                // TODO: We have to reset the default SMS and Phone. This requires
17361                // significant refactoring to keep all default apps in the package
17362                // manager (cleaner but more work) or have the services provide
17363                // callbacks to the package manager to request a default app reset.
17364                applyFactoryDefaultBrowserLPw(userId);
17365                clearIntentFilterVerificationsLPw(userId);
17366                primeDomainVerificationsLPw(userId);
17367                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17368                scheduleWritePackageRestrictionsLocked(userId);
17369            }
17370            resetNetworkPolicies(userId);
17371        } finally {
17372            Binder.restoreCallingIdentity(identity);
17373        }
17374    }
17375
17376    @Override
17377    public int getPreferredActivities(List<IntentFilter> outFilters,
17378            List<ComponentName> outActivities, String packageName) {
17379
17380        int num = 0;
17381        final int userId = UserHandle.getCallingUserId();
17382        // reader
17383        synchronized (mPackages) {
17384            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17385            if (pir != null) {
17386                final Iterator<PreferredActivity> it = pir.filterIterator();
17387                while (it.hasNext()) {
17388                    final PreferredActivity pa = it.next();
17389                    if (packageName == null
17390                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17391                                    && pa.mPref.mAlways)) {
17392                        if (outFilters != null) {
17393                            outFilters.add(new IntentFilter(pa));
17394                        }
17395                        if (outActivities != null) {
17396                            outActivities.add(pa.mPref.mComponent);
17397                        }
17398                    }
17399                }
17400            }
17401        }
17402
17403        return num;
17404    }
17405
17406    @Override
17407    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17408            int userId) {
17409        int callingUid = Binder.getCallingUid();
17410        if (callingUid != Process.SYSTEM_UID) {
17411            throw new SecurityException(
17412                    "addPersistentPreferredActivity can only be run by the system");
17413        }
17414        if (filter.countActions() == 0) {
17415            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17416            return;
17417        }
17418        synchronized (mPackages) {
17419            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17420                    ":");
17421            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17422            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17423                    new PersistentPreferredActivity(filter, activity));
17424            scheduleWritePackageRestrictionsLocked(userId);
17425            postPreferredActivityChangedBroadcast(userId);
17426        }
17427    }
17428
17429    @Override
17430    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17431        int callingUid = Binder.getCallingUid();
17432        if (callingUid != Process.SYSTEM_UID) {
17433            throw new SecurityException(
17434                    "clearPackagePersistentPreferredActivities can only be run by the system");
17435        }
17436        ArrayList<PersistentPreferredActivity> removed = null;
17437        boolean changed = false;
17438        synchronized (mPackages) {
17439            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17440                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17441                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17442                        .valueAt(i);
17443                if (userId != thisUserId) {
17444                    continue;
17445                }
17446                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17447                while (it.hasNext()) {
17448                    PersistentPreferredActivity ppa = it.next();
17449                    // Mark entry for removal only if it matches the package name.
17450                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17451                        if (removed == null) {
17452                            removed = new ArrayList<PersistentPreferredActivity>();
17453                        }
17454                        removed.add(ppa);
17455                    }
17456                }
17457                if (removed != null) {
17458                    for (int j=0; j<removed.size(); j++) {
17459                        PersistentPreferredActivity ppa = removed.get(j);
17460                        ppir.removeFilter(ppa);
17461                    }
17462                    changed = true;
17463                }
17464            }
17465
17466            if (changed) {
17467                scheduleWritePackageRestrictionsLocked(userId);
17468                postPreferredActivityChangedBroadcast(userId);
17469            }
17470        }
17471    }
17472
17473    /**
17474     * Common machinery for picking apart a restored XML blob and passing
17475     * it to a caller-supplied functor to be applied to the running system.
17476     */
17477    private void restoreFromXml(XmlPullParser parser, int userId,
17478            String expectedStartTag, BlobXmlRestorer functor)
17479            throws IOException, XmlPullParserException {
17480        int type;
17481        while ((type = parser.next()) != XmlPullParser.START_TAG
17482                && type != XmlPullParser.END_DOCUMENT) {
17483        }
17484        if (type != XmlPullParser.START_TAG) {
17485            // oops didn't find a start tag?!
17486            if (DEBUG_BACKUP) {
17487                Slog.e(TAG, "Didn't find start tag during restore");
17488            }
17489            return;
17490        }
17491Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17492        // this is supposed to be TAG_PREFERRED_BACKUP
17493        if (!expectedStartTag.equals(parser.getName())) {
17494            if (DEBUG_BACKUP) {
17495                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17496            }
17497            return;
17498        }
17499
17500        // skip interfering stuff, then we're aligned with the backing implementation
17501        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17502Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17503        functor.apply(parser, userId);
17504    }
17505
17506    private interface BlobXmlRestorer {
17507        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17508    }
17509
17510    /**
17511     * Non-Binder method, support for the backup/restore mechanism: write the
17512     * full set of preferred activities in its canonical XML format.  Returns the
17513     * XML output as a byte array, or null if there is none.
17514     */
17515    @Override
17516    public byte[] getPreferredActivityBackup(int userId) {
17517        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17518            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17519        }
17520
17521        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17522        try {
17523            final XmlSerializer serializer = new FastXmlSerializer();
17524            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17525            serializer.startDocument(null, true);
17526            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17527
17528            synchronized (mPackages) {
17529                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17530            }
17531
17532            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17533            serializer.endDocument();
17534            serializer.flush();
17535        } catch (Exception e) {
17536            if (DEBUG_BACKUP) {
17537                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17538            }
17539            return null;
17540        }
17541
17542        return dataStream.toByteArray();
17543    }
17544
17545    @Override
17546    public void restorePreferredActivities(byte[] backup, int userId) {
17547        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17548            throw new SecurityException("Only the system may call restorePreferredActivities()");
17549        }
17550
17551        try {
17552            final XmlPullParser parser = Xml.newPullParser();
17553            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17554            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17555                    new BlobXmlRestorer() {
17556                        @Override
17557                        public void apply(XmlPullParser parser, int userId)
17558                                throws XmlPullParserException, IOException {
17559                            synchronized (mPackages) {
17560                                mSettings.readPreferredActivitiesLPw(parser, userId);
17561                            }
17562                        }
17563                    } );
17564        } catch (Exception e) {
17565            if (DEBUG_BACKUP) {
17566                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17567            }
17568        }
17569    }
17570
17571    /**
17572     * Non-Binder method, support for the backup/restore mechanism: write the
17573     * default browser (etc) settings in its canonical XML format.  Returns the default
17574     * browser XML representation as a byte array, or null if there is none.
17575     */
17576    @Override
17577    public byte[] getDefaultAppsBackup(int userId) {
17578        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17579            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17580        }
17581
17582        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17583        try {
17584            final XmlSerializer serializer = new FastXmlSerializer();
17585            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17586            serializer.startDocument(null, true);
17587            serializer.startTag(null, TAG_DEFAULT_APPS);
17588
17589            synchronized (mPackages) {
17590                mSettings.writeDefaultAppsLPr(serializer, userId);
17591            }
17592
17593            serializer.endTag(null, TAG_DEFAULT_APPS);
17594            serializer.endDocument();
17595            serializer.flush();
17596        } catch (Exception e) {
17597            if (DEBUG_BACKUP) {
17598                Slog.e(TAG, "Unable to write default apps for backup", e);
17599            }
17600            return null;
17601        }
17602
17603        return dataStream.toByteArray();
17604    }
17605
17606    @Override
17607    public void restoreDefaultApps(byte[] backup, int userId) {
17608        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17609            throw new SecurityException("Only the system may call restoreDefaultApps()");
17610        }
17611
17612        try {
17613            final XmlPullParser parser = Xml.newPullParser();
17614            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17615            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17616                    new BlobXmlRestorer() {
17617                        @Override
17618                        public void apply(XmlPullParser parser, int userId)
17619                                throws XmlPullParserException, IOException {
17620                            synchronized (mPackages) {
17621                                mSettings.readDefaultAppsLPw(parser, userId);
17622                            }
17623                        }
17624                    } );
17625        } catch (Exception e) {
17626            if (DEBUG_BACKUP) {
17627                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17628            }
17629        }
17630    }
17631
17632    @Override
17633    public byte[] getIntentFilterVerificationBackup(int userId) {
17634        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17635            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17636        }
17637
17638        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17639        try {
17640            final XmlSerializer serializer = new FastXmlSerializer();
17641            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17642            serializer.startDocument(null, true);
17643            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17644
17645            synchronized (mPackages) {
17646                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17647            }
17648
17649            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17650            serializer.endDocument();
17651            serializer.flush();
17652        } catch (Exception e) {
17653            if (DEBUG_BACKUP) {
17654                Slog.e(TAG, "Unable to write default apps for backup", e);
17655            }
17656            return null;
17657        }
17658
17659        return dataStream.toByteArray();
17660    }
17661
17662    @Override
17663    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17664        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17665            throw new SecurityException("Only the system may call restorePreferredActivities()");
17666        }
17667
17668        try {
17669            final XmlPullParser parser = Xml.newPullParser();
17670            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17671            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17672                    new BlobXmlRestorer() {
17673                        @Override
17674                        public void apply(XmlPullParser parser, int userId)
17675                                throws XmlPullParserException, IOException {
17676                            synchronized (mPackages) {
17677                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17678                                mSettings.writeLPr();
17679                            }
17680                        }
17681                    } );
17682        } catch (Exception e) {
17683            if (DEBUG_BACKUP) {
17684                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17685            }
17686        }
17687    }
17688
17689    @Override
17690    public byte[] getPermissionGrantBackup(int userId) {
17691        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17692            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17693        }
17694
17695        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17696        try {
17697            final XmlSerializer serializer = new FastXmlSerializer();
17698            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17699            serializer.startDocument(null, true);
17700            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17701
17702            synchronized (mPackages) {
17703                serializeRuntimePermissionGrantsLPr(serializer, userId);
17704            }
17705
17706            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17707            serializer.endDocument();
17708            serializer.flush();
17709        } catch (Exception e) {
17710            if (DEBUG_BACKUP) {
17711                Slog.e(TAG, "Unable to write default apps for backup", e);
17712            }
17713            return null;
17714        }
17715
17716        return dataStream.toByteArray();
17717    }
17718
17719    @Override
17720    public void restorePermissionGrants(byte[] backup, int userId) {
17721        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17722            throw new SecurityException("Only the system may call restorePermissionGrants()");
17723        }
17724
17725        try {
17726            final XmlPullParser parser = Xml.newPullParser();
17727            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17728            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17729                    new BlobXmlRestorer() {
17730                        @Override
17731                        public void apply(XmlPullParser parser, int userId)
17732                                throws XmlPullParserException, IOException {
17733                            synchronized (mPackages) {
17734                                processRestoredPermissionGrantsLPr(parser, userId);
17735                            }
17736                        }
17737                    } );
17738        } catch (Exception e) {
17739            if (DEBUG_BACKUP) {
17740                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17741            }
17742        }
17743    }
17744
17745    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17746            throws IOException {
17747        serializer.startTag(null, TAG_ALL_GRANTS);
17748
17749        final int N = mSettings.mPackages.size();
17750        for (int i = 0; i < N; i++) {
17751            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17752            boolean pkgGrantsKnown = false;
17753
17754            PermissionsState packagePerms = ps.getPermissionsState();
17755
17756            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17757                final int grantFlags = state.getFlags();
17758                // only look at grants that are not system/policy fixed
17759                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17760                    final boolean isGranted = state.isGranted();
17761                    // And only back up the user-twiddled state bits
17762                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17763                        final String packageName = mSettings.mPackages.keyAt(i);
17764                        if (!pkgGrantsKnown) {
17765                            serializer.startTag(null, TAG_GRANT);
17766                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17767                            pkgGrantsKnown = true;
17768                        }
17769
17770                        final boolean userSet =
17771                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17772                        final boolean userFixed =
17773                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17774                        final boolean revoke =
17775                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17776
17777                        serializer.startTag(null, TAG_PERMISSION);
17778                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17779                        if (isGranted) {
17780                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17781                        }
17782                        if (userSet) {
17783                            serializer.attribute(null, ATTR_USER_SET, "true");
17784                        }
17785                        if (userFixed) {
17786                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17787                        }
17788                        if (revoke) {
17789                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17790                        }
17791                        serializer.endTag(null, TAG_PERMISSION);
17792                    }
17793                }
17794            }
17795
17796            if (pkgGrantsKnown) {
17797                serializer.endTag(null, TAG_GRANT);
17798            }
17799        }
17800
17801        serializer.endTag(null, TAG_ALL_GRANTS);
17802    }
17803
17804    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17805            throws XmlPullParserException, IOException {
17806        String pkgName = null;
17807        int outerDepth = parser.getDepth();
17808        int type;
17809        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17810                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17811            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17812                continue;
17813            }
17814
17815            final String tagName = parser.getName();
17816            if (tagName.equals(TAG_GRANT)) {
17817                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17818                if (DEBUG_BACKUP) {
17819                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17820                }
17821            } else if (tagName.equals(TAG_PERMISSION)) {
17822
17823                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17824                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17825
17826                int newFlagSet = 0;
17827                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17828                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17829                }
17830                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17831                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17832                }
17833                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17834                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17835                }
17836                if (DEBUG_BACKUP) {
17837                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17838                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17839                }
17840                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17841                if (ps != null) {
17842                    // Already installed so we apply the grant immediately
17843                    if (DEBUG_BACKUP) {
17844                        Slog.v(TAG, "        + already installed; applying");
17845                    }
17846                    PermissionsState perms = ps.getPermissionsState();
17847                    BasePermission bp = mSettings.mPermissions.get(permName);
17848                    if (bp != null) {
17849                        if (isGranted) {
17850                            perms.grantRuntimePermission(bp, userId);
17851                        }
17852                        if (newFlagSet != 0) {
17853                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17854                        }
17855                    }
17856                } else {
17857                    // Need to wait for post-restore install to apply the grant
17858                    if (DEBUG_BACKUP) {
17859                        Slog.v(TAG, "        - not yet installed; saving for later");
17860                    }
17861                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17862                            isGranted, newFlagSet, userId);
17863                }
17864            } else {
17865                PackageManagerService.reportSettingsProblem(Log.WARN,
17866                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17867                XmlUtils.skipCurrentTag(parser);
17868            }
17869        }
17870
17871        scheduleWriteSettingsLocked();
17872        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17873    }
17874
17875    @Override
17876    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17877            int sourceUserId, int targetUserId, int flags) {
17878        mContext.enforceCallingOrSelfPermission(
17879                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17880        int callingUid = Binder.getCallingUid();
17881        enforceOwnerRights(ownerPackage, callingUid);
17882        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17883        if (intentFilter.countActions() == 0) {
17884            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17885            return;
17886        }
17887        synchronized (mPackages) {
17888            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17889                    ownerPackage, targetUserId, flags);
17890            CrossProfileIntentResolver resolver =
17891                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17892            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17893            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17894            if (existing != null) {
17895                int size = existing.size();
17896                for (int i = 0; i < size; i++) {
17897                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17898                        return;
17899                    }
17900                }
17901            }
17902            resolver.addFilter(newFilter);
17903            scheduleWritePackageRestrictionsLocked(sourceUserId);
17904        }
17905    }
17906
17907    @Override
17908    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17909        mContext.enforceCallingOrSelfPermission(
17910                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17911        int callingUid = Binder.getCallingUid();
17912        enforceOwnerRights(ownerPackage, callingUid);
17913        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17914        synchronized (mPackages) {
17915            CrossProfileIntentResolver resolver =
17916                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17917            ArraySet<CrossProfileIntentFilter> set =
17918                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17919            for (CrossProfileIntentFilter filter : set) {
17920                if (filter.getOwnerPackage().equals(ownerPackage)) {
17921                    resolver.removeFilter(filter);
17922                }
17923            }
17924            scheduleWritePackageRestrictionsLocked(sourceUserId);
17925        }
17926    }
17927
17928    // Enforcing that callingUid is owning pkg on userId
17929    private void enforceOwnerRights(String pkg, int callingUid) {
17930        // The system owns everything.
17931        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17932            return;
17933        }
17934        int callingUserId = UserHandle.getUserId(callingUid);
17935        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17936        if (pi == null) {
17937            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17938                    + callingUserId);
17939        }
17940        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17941            throw new SecurityException("Calling uid " + callingUid
17942                    + " does not own package " + pkg);
17943        }
17944    }
17945
17946    @Override
17947    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17948        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17949    }
17950
17951    private Intent getHomeIntent() {
17952        Intent intent = new Intent(Intent.ACTION_MAIN);
17953        intent.addCategory(Intent.CATEGORY_HOME);
17954        intent.addCategory(Intent.CATEGORY_DEFAULT);
17955        return intent;
17956    }
17957
17958    private IntentFilter getHomeFilter() {
17959        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17960        filter.addCategory(Intent.CATEGORY_HOME);
17961        filter.addCategory(Intent.CATEGORY_DEFAULT);
17962        return filter;
17963    }
17964
17965    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17966            int userId) {
17967        Intent intent  = getHomeIntent();
17968        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17969                PackageManager.GET_META_DATA, userId);
17970        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17971                true, false, false, userId);
17972
17973        allHomeCandidates.clear();
17974        if (list != null) {
17975            for (ResolveInfo ri : list) {
17976                allHomeCandidates.add(ri);
17977            }
17978        }
17979        return (preferred == null || preferred.activityInfo == null)
17980                ? null
17981                : new ComponentName(preferred.activityInfo.packageName,
17982                        preferred.activityInfo.name);
17983    }
17984
17985    @Override
17986    public void setHomeActivity(ComponentName comp, int userId) {
17987        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17988        getHomeActivitiesAsUser(homeActivities, userId);
17989
17990        boolean found = false;
17991
17992        final int size = homeActivities.size();
17993        final ComponentName[] set = new ComponentName[size];
17994        for (int i = 0; i < size; i++) {
17995            final ResolveInfo candidate = homeActivities.get(i);
17996            final ActivityInfo info = candidate.activityInfo;
17997            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17998            set[i] = activityName;
17999            if (!found && activityName.equals(comp)) {
18000                found = true;
18001            }
18002        }
18003        if (!found) {
18004            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18005                    + userId);
18006        }
18007        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18008                set, comp, userId);
18009    }
18010
18011    private @Nullable String getSetupWizardPackageName() {
18012        final Intent intent = new Intent(Intent.ACTION_MAIN);
18013        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18014
18015        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18016                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18017                        | MATCH_DISABLED_COMPONENTS,
18018                UserHandle.myUserId());
18019        if (matches.size() == 1) {
18020            return matches.get(0).getComponentInfo().packageName;
18021        } else {
18022            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18023                    + ": matches=" + matches);
18024            return null;
18025        }
18026    }
18027
18028    private @Nullable String getStorageManagerPackageName() {
18029        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18030
18031        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18032                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18033                        | MATCH_DISABLED_COMPONENTS,
18034                UserHandle.myUserId());
18035        if (matches.size() == 1) {
18036            return matches.get(0).getComponentInfo().packageName;
18037        } else {
18038            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18039                    + matches.size() + ": matches=" + matches);
18040            return null;
18041        }
18042    }
18043
18044    @Override
18045    public void setApplicationEnabledSetting(String appPackageName,
18046            int newState, int flags, int userId, String callingPackage) {
18047        if (!sUserManager.exists(userId)) return;
18048        if (callingPackage == null) {
18049            callingPackage = Integer.toString(Binder.getCallingUid());
18050        }
18051        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18052    }
18053
18054    @Override
18055    public void setComponentEnabledSetting(ComponentName componentName,
18056            int newState, int flags, int userId) {
18057        if (!sUserManager.exists(userId)) return;
18058        setEnabledSetting(componentName.getPackageName(),
18059                componentName.getClassName(), newState, flags, userId, null);
18060    }
18061
18062    private void setEnabledSetting(final String packageName, String className, int newState,
18063            final int flags, int userId, String callingPackage) {
18064        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18065              || newState == COMPONENT_ENABLED_STATE_ENABLED
18066              || newState == COMPONENT_ENABLED_STATE_DISABLED
18067              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18068              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18069            throw new IllegalArgumentException("Invalid new component state: "
18070                    + newState);
18071        }
18072        PackageSetting pkgSetting;
18073        final int uid = Binder.getCallingUid();
18074        final int permission;
18075        if (uid == Process.SYSTEM_UID) {
18076            permission = PackageManager.PERMISSION_GRANTED;
18077        } else {
18078            permission = mContext.checkCallingOrSelfPermission(
18079                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18080        }
18081        enforceCrossUserPermission(uid, userId,
18082                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18083        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18084        boolean sendNow = false;
18085        boolean isApp = (className == null);
18086        String componentName = isApp ? packageName : className;
18087        int packageUid = -1;
18088        ArrayList<String> components;
18089
18090        // writer
18091        synchronized (mPackages) {
18092            pkgSetting = mSettings.mPackages.get(packageName);
18093            if (pkgSetting == null) {
18094                if (className == null) {
18095                    throw new IllegalArgumentException("Unknown package: " + packageName);
18096                }
18097                throw new IllegalArgumentException(
18098                        "Unknown component: " + packageName + "/" + className);
18099            }
18100        }
18101
18102        // Limit who can change which apps
18103        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18104            // Don't allow apps that don't have permission to modify other apps
18105            if (!allowedByPermission) {
18106                throw new SecurityException(
18107                        "Permission Denial: attempt to change component state from pid="
18108                        + Binder.getCallingPid()
18109                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18110            }
18111            // Don't allow changing protected packages.
18112            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18113                throw new SecurityException("Cannot disable a protected package: " + packageName);
18114            }
18115        }
18116
18117        synchronized (mPackages) {
18118            if (uid == Process.SHELL_UID
18119                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18120                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18121                // unless it is a test package.
18122                int oldState = pkgSetting.getEnabled(userId);
18123                if (className == null
18124                    &&
18125                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18126                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18127                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18128                    &&
18129                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18130                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18131                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18132                    // ok
18133                } else {
18134                    throw new SecurityException(
18135                            "Shell cannot change component state for " + packageName + "/"
18136                            + className + " to " + newState);
18137                }
18138            }
18139            if (className == null) {
18140                // We're dealing with an application/package level state change
18141                if (pkgSetting.getEnabled(userId) == newState) {
18142                    // Nothing to do
18143                    return;
18144                }
18145                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18146                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18147                    // Don't care about who enables an app.
18148                    callingPackage = null;
18149                }
18150                pkgSetting.setEnabled(newState, userId, callingPackage);
18151                // pkgSetting.pkg.mSetEnabled = newState;
18152            } else {
18153                // We're dealing with a component level state change
18154                // First, verify that this is a valid class name.
18155                PackageParser.Package pkg = pkgSetting.pkg;
18156                if (pkg == null || !pkg.hasComponentClassName(className)) {
18157                    if (pkg != null &&
18158                            pkg.applicationInfo.targetSdkVersion >=
18159                                    Build.VERSION_CODES.JELLY_BEAN) {
18160                        throw new IllegalArgumentException("Component class " + className
18161                                + " does not exist in " + packageName);
18162                    } else {
18163                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18164                                + className + " does not exist in " + packageName);
18165                    }
18166                }
18167                switch (newState) {
18168                case COMPONENT_ENABLED_STATE_ENABLED:
18169                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18170                        return;
18171                    }
18172                    break;
18173                case COMPONENT_ENABLED_STATE_DISABLED:
18174                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18175                        return;
18176                    }
18177                    break;
18178                case COMPONENT_ENABLED_STATE_DEFAULT:
18179                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18180                        return;
18181                    }
18182                    break;
18183                default:
18184                    Slog.e(TAG, "Invalid new component state: " + newState);
18185                    return;
18186                }
18187            }
18188            scheduleWritePackageRestrictionsLocked(userId);
18189            components = mPendingBroadcasts.get(userId, packageName);
18190            final boolean newPackage = components == null;
18191            if (newPackage) {
18192                components = new ArrayList<String>();
18193            }
18194            if (!components.contains(componentName)) {
18195                components.add(componentName);
18196            }
18197            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18198                sendNow = true;
18199                // Purge entry from pending broadcast list if another one exists already
18200                // since we are sending one right away.
18201                mPendingBroadcasts.remove(userId, packageName);
18202            } else {
18203                if (newPackage) {
18204                    mPendingBroadcasts.put(userId, packageName, components);
18205                }
18206                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18207                    // Schedule a message
18208                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18209                }
18210            }
18211        }
18212
18213        long callingId = Binder.clearCallingIdentity();
18214        try {
18215            if (sendNow) {
18216                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18217                sendPackageChangedBroadcast(packageName,
18218                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18219            }
18220        } finally {
18221            Binder.restoreCallingIdentity(callingId);
18222        }
18223    }
18224
18225    @Override
18226    public void flushPackageRestrictionsAsUser(int userId) {
18227        if (!sUserManager.exists(userId)) {
18228            return;
18229        }
18230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18231                false /* checkShell */, "flushPackageRestrictions");
18232        synchronized (mPackages) {
18233            mSettings.writePackageRestrictionsLPr(userId);
18234            mDirtyUsers.remove(userId);
18235            if (mDirtyUsers.isEmpty()) {
18236                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18237            }
18238        }
18239    }
18240
18241    private void sendPackageChangedBroadcast(String packageName,
18242            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18243        if (DEBUG_INSTALL)
18244            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18245                    + componentNames);
18246        Bundle extras = new Bundle(4);
18247        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18248        String nameList[] = new String[componentNames.size()];
18249        componentNames.toArray(nameList);
18250        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18251        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18252        extras.putInt(Intent.EXTRA_UID, packageUid);
18253        // If this is not reporting a change of the overall package, then only send it
18254        // to registered receivers.  We don't want to launch a swath of apps for every
18255        // little component state change.
18256        final int flags = !componentNames.contains(packageName)
18257                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18258        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18259                new int[] {UserHandle.getUserId(packageUid)});
18260    }
18261
18262    @Override
18263    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18264        if (!sUserManager.exists(userId)) return;
18265        final int uid = Binder.getCallingUid();
18266        final int permission = mContext.checkCallingOrSelfPermission(
18267                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18268        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18269        enforceCrossUserPermission(uid, userId,
18270                true /* requireFullPermission */, true /* checkShell */, "stop package");
18271        // writer
18272        synchronized (mPackages) {
18273            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18274                    allowedByPermission, uid, userId)) {
18275                scheduleWritePackageRestrictionsLocked(userId);
18276            }
18277        }
18278    }
18279
18280    @Override
18281    public String getInstallerPackageName(String packageName) {
18282        // reader
18283        synchronized (mPackages) {
18284            return mSettings.getInstallerPackageNameLPr(packageName);
18285        }
18286    }
18287
18288    public boolean isOrphaned(String packageName) {
18289        // reader
18290        synchronized (mPackages) {
18291            return mSettings.isOrphaned(packageName);
18292        }
18293    }
18294
18295    @Override
18296    public int getApplicationEnabledSetting(String packageName, int userId) {
18297        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18298        int uid = Binder.getCallingUid();
18299        enforceCrossUserPermission(uid, userId,
18300                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18301        // reader
18302        synchronized (mPackages) {
18303            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18304        }
18305    }
18306
18307    @Override
18308    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18309        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18310        int uid = Binder.getCallingUid();
18311        enforceCrossUserPermission(uid, userId,
18312                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18313        // reader
18314        synchronized (mPackages) {
18315            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18316        }
18317    }
18318
18319    @Override
18320    public void enterSafeMode() {
18321        enforceSystemOrRoot("Only the system can request entering safe mode");
18322
18323        if (!mSystemReady) {
18324            mSafeMode = true;
18325        }
18326    }
18327
18328    @Override
18329    public void systemReady() {
18330        mSystemReady = true;
18331
18332        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18333        // disabled after already being started.
18334        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18335                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18336
18337        // Read the compatibilty setting when the system is ready.
18338        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18339                mContext.getContentResolver(),
18340                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18341        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18342        if (DEBUG_SETTINGS) {
18343            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18344        }
18345
18346        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18347
18348        synchronized (mPackages) {
18349            // Verify that all of the preferred activity components actually
18350            // exist.  It is possible for applications to be updated and at
18351            // that point remove a previously declared activity component that
18352            // had been set as a preferred activity.  We try to clean this up
18353            // the next time we encounter that preferred activity, but it is
18354            // possible for the user flow to never be able to return to that
18355            // situation so here we do a sanity check to make sure we haven't
18356            // left any junk around.
18357            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18358            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18359                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18360                removed.clear();
18361                for (PreferredActivity pa : pir.filterSet()) {
18362                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18363                        removed.add(pa);
18364                    }
18365                }
18366                if (removed.size() > 0) {
18367                    for (int r=0; r<removed.size(); r++) {
18368                        PreferredActivity pa = removed.get(r);
18369                        Slog.w(TAG, "Removing dangling preferred activity: "
18370                                + pa.mPref.mComponent);
18371                        pir.removeFilter(pa);
18372                    }
18373                    mSettings.writePackageRestrictionsLPr(
18374                            mSettings.mPreferredActivities.keyAt(i));
18375                }
18376            }
18377
18378            for (int userId : UserManagerService.getInstance().getUserIds()) {
18379                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18380                    grantPermissionsUserIds = ArrayUtils.appendInt(
18381                            grantPermissionsUserIds, userId);
18382                }
18383            }
18384        }
18385        sUserManager.systemReady();
18386
18387        // If we upgraded grant all default permissions before kicking off.
18388        for (int userId : grantPermissionsUserIds) {
18389            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18390        }
18391
18392        // If we did not grant default permissions, we preload from this the
18393        // default permission exceptions lazily to ensure we don't hit the
18394        // disk on a new user creation.
18395        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18396            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18397        }
18398
18399        // Kick off any messages waiting for system ready
18400        if (mPostSystemReadyMessages != null) {
18401            for (Message msg : mPostSystemReadyMessages) {
18402                msg.sendToTarget();
18403            }
18404            mPostSystemReadyMessages = null;
18405        }
18406
18407        // Watch for external volumes that come and go over time
18408        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18409        storage.registerListener(mStorageListener);
18410
18411        mInstallerService.systemReady();
18412        mPackageDexOptimizer.systemReady();
18413
18414        MountServiceInternal mountServiceInternal = LocalServices.getService(
18415                MountServiceInternal.class);
18416        mountServiceInternal.addExternalStoragePolicy(
18417                new MountServiceInternal.ExternalStorageMountPolicy() {
18418            @Override
18419            public int getMountMode(int uid, String packageName) {
18420                if (Process.isIsolated(uid)) {
18421                    return Zygote.MOUNT_EXTERNAL_NONE;
18422                }
18423                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18424                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18425                }
18426                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18427                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18428                }
18429                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18430                    return Zygote.MOUNT_EXTERNAL_READ;
18431                }
18432                return Zygote.MOUNT_EXTERNAL_WRITE;
18433            }
18434
18435            @Override
18436            public boolean hasExternalStorage(int uid, String packageName) {
18437                return true;
18438            }
18439        });
18440
18441        // Now that we're mostly running, clean up stale users and apps
18442        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18443        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18444    }
18445
18446    @Override
18447    public boolean isSafeMode() {
18448        return mSafeMode;
18449    }
18450
18451    @Override
18452    public boolean hasSystemUidErrors() {
18453        return mHasSystemUidErrors;
18454    }
18455
18456    static String arrayToString(int[] array) {
18457        StringBuffer buf = new StringBuffer(128);
18458        buf.append('[');
18459        if (array != null) {
18460            for (int i=0; i<array.length; i++) {
18461                if (i > 0) buf.append(", ");
18462                buf.append(array[i]);
18463            }
18464        }
18465        buf.append(']');
18466        return buf.toString();
18467    }
18468
18469    static class DumpState {
18470        public static final int DUMP_LIBS = 1 << 0;
18471        public static final int DUMP_FEATURES = 1 << 1;
18472        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18473        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18474        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18475        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18476        public static final int DUMP_PERMISSIONS = 1 << 6;
18477        public static final int DUMP_PACKAGES = 1 << 7;
18478        public static final int DUMP_SHARED_USERS = 1 << 8;
18479        public static final int DUMP_MESSAGES = 1 << 9;
18480        public static final int DUMP_PROVIDERS = 1 << 10;
18481        public static final int DUMP_VERIFIERS = 1 << 11;
18482        public static final int DUMP_PREFERRED = 1 << 12;
18483        public static final int DUMP_PREFERRED_XML = 1 << 13;
18484        public static final int DUMP_KEYSETS = 1 << 14;
18485        public static final int DUMP_VERSION = 1 << 15;
18486        public static final int DUMP_INSTALLS = 1 << 16;
18487        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18488        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18489        public static final int DUMP_FROZEN = 1 << 19;
18490        public static final int DUMP_DEXOPT = 1 << 20;
18491        public static final int DUMP_COMPILER_STATS = 1 << 21;
18492
18493        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18494
18495        private int mTypes;
18496
18497        private int mOptions;
18498
18499        private boolean mTitlePrinted;
18500
18501        private SharedUserSetting mSharedUser;
18502
18503        public boolean isDumping(int type) {
18504            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18505                return true;
18506            }
18507
18508            return (mTypes & type) != 0;
18509        }
18510
18511        public void setDump(int type) {
18512            mTypes |= type;
18513        }
18514
18515        public boolean isOptionEnabled(int option) {
18516            return (mOptions & option) != 0;
18517        }
18518
18519        public void setOptionEnabled(int option) {
18520            mOptions |= option;
18521        }
18522
18523        public boolean onTitlePrinted() {
18524            final boolean printed = mTitlePrinted;
18525            mTitlePrinted = true;
18526            return printed;
18527        }
18528
18529        public boolean getTitlePrinted() {
18530            return mTitlePrinted;
18531        }
18532
18533        public void setTitlePrinted(boolean enabled) {
18534            mTitlePrinted = enabled;
18535        }
18536
18537        public SharedUserSetting getSharedUser() {
18538            return mSharedUser;
18539        }
18540
18541        public void setSharedUser(SharedUserSetting user) {
18542            mSharedUser = user;
18543        }
18544    }
18545
18546    @Override
18547    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18548            FileDescriptor err, String[] args, ShellCallback callback,
18549            ResultReceiver resultReceiver) {
18550        (new PackageManagerShellCommand(this)).exec(
18551                this, in, out, err, args, callback, resultReceiver);
18552    }
18553
18554    @Override
18555    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18556        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18557                != PackageManager.PERMISSION_GRANTED) {
18558            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18559                    + Binder.getCallingPid()
18560                    + ", uid=" + Binder.getCallingUid()
18561                    + " without permission "
18562                    + android.Manifest.permission.DUMP);
18563            return;
18564        }
18565
18566        DumpState dumpState = new DumpState();
18567        boolean fullPreferred = false;
18568        boolean checkin = false;
18569
18570        String packageName = null;
18571        ArraySet<String> permissionNames = null;
18572
18573        int opti = 0;
18574        while (opti < args.length) {
18575            String opt = args[opti];
18576            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18577                break;
18578            }
18579            opti++;
18580
18581            if ("-a".equals(opt)) {
18582                // Right now we only know how to print all.
18583            } else if ("-h".equals(opt)) {
18584                pw.println("Package manager dump options:");
18585                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18586                pw.println("    --checkin: dump for a checkin");
18587                pw.println("    -f: print details of intent filters");
18588                pw.println("    -h: print this help");
18589                pw.println("  cmd may be one of:");
18590                pw.println("    l[ibraries]: list known shared libraries");
18591                pw.println("    f[eatures]: list device features");
18592                pw.println("    k[eysets]: print known keysets");
18593                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18594                pw.println("    perm[issions]: dump permissions");
18595                pw.println("    permission [name ...]: dump declaration and use of given permission");
18596                pw.println("    pref[erred]: print preferred package settings");
18597                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18598                pw.println("    prov[iders]: dump content providers");
18599                pw.println("    p[ackages]: dump installed packages");
18600                pw.println("    s[hared-users]: dump shared user IDs");
18601                pw.println("    m[essages]: print collected runtime messages");
18602                pw.println("    v[erifiers]: print package verifier info");
18603                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18604                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18605                pw.println("    version: print database version info");
18606                pw.println("    write: write current settings now");
18607                pw.println("    installs: details about install sessions");
18608                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18609                pw.println("    dexopt: dump dexopt state");
18610                pw.println("    compiler-stats: dump compiler statistics");
18611                pw.println("    <package.name>: info about given package");
18612                return;
18613            } else if ("--checkin".equals(opt)) {
18614                checkin = true;
18615            } else if ("-f".equals(opt)) {
18616                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18617            } else {
18618                pw.println("Unknown argument: " + opt + "; use -h for help");
18619            }
18620        }
18621
18622        // Is the caller requesting to dump a particular piece of data?
18623        if (opti < args.length) {
18624            String cmd = args[opti];
18625            opti++;
18626            // Is this a package name?
18627            if ("android".equals(cmd) || cmd.contains(".")) {
18628                packageName = cmd;
18629                // When dumping a single package, we always dump all of its
18630                // filter information since the amount of data will be reasonable.
18631                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18632            } else if ("check-permission".equals(cmd)) {
18633                if (opti >= args.length) {
18634                    pw.println("Error: check-permission missing permission argument");
18635                    return;
18636                }
18637                String perm = args[opti];
18638                opti++;
18639                if (opti >= args.length) {
18640                    pw.println("Error: check-permission missing package argument");
18641                    return;
18642                }
18643                String pkg = args[opti];
18644                opti++;
18645                int user = UserHandle.getUserId(Binder.getCallingUid());
18646                if (opti < args.length) {
18647                    try {
18648                        user = Integer.parseInt(args[opti]);
18649                    } catch (NumberFormatException e) {
18650                        pw.println("Error: check-permission user argument is not a number: "
18651                                + args[opti]);
18652                        return;
18653                    }
18654                }
18655                pw.println(checkPermission(perm, pkg, user));
18656                return;
18657            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18658                dumpState.setDump(DumpState.DUMP_LIBS);
18659            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18660                dumpState.setDump(DumpState.DUMP_FEATURES);
18661            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18662                if (opti >= args.length) {
18663                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18664                            | DumpState.DUMP_SERVICE_RESOLVERS
18665                            | DumpState.DUMP_RECEIVER_RESOLVERS
18666                            | DumpState.DUMP_CONTENT_RESOLVERS);
18667                } else {
18668                    while (opti < args.length) {
18669                        String name = args[opti];
18670                        if ("a".equals(name) || "activity".equals(name)) {
18671                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18672                        } else if ("s".equals(name) || "service".equals(name)) {
18673                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18674                        } else if ("r".equals(name) || "receiver".equals(name)) {
18675                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18676                        } else if ("c".equals(name) || "content".equals(name)) {
18677                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18678                        } else {
18679                            pw.println("Error: unknown resolver table type: " + name);
18680                            return;
18681                        }
18682                        opti++;
18683                    }
18684                }
18685            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18686                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18687            } else if ("permission".equals(cmd)) {
18688                if (opti >= args.length) {
18689                    pw.println("Error: permission requires permission name");
18690                    return;
18691                }
18692                permissionNames = new ArraySet<>();
18693                while (opti < args.length) {
18694                    permissionNames.add(args[opti]);
18695                    opti++;
18696                }
18697                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18698                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18699            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18700                dumpState.setDump(DumpState.DUMP_PREFERRED);
18701            } else if ("preferred-xml".equals(cmd)) {
18702                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18703                if (opti < args.length && "--full".equals(args[opti])) {
18704                    fullPreferred = true;
18705                    opti++;
18706                }
18707            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18708                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18709            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18710                dumpState.setDump(DumpState.DUMP_PACKAGES);
18711            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18712                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18713            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18714                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18715            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18716                dumpState.setDump(DumpState.DUMP_MESSAGES);
18717            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18718                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18719            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18720                    || "intent-filter-verifiers".equals(cmd)) {
18721                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18722            } else if ("version".equals(cmd)) {
18723                dumpState.setDump(DumpState.DUMP_VERSION);
18724            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18725                dumpState.setDump(DumpState.DUMP_KEYSETS);
18726            } else if ("installs".equals(cmd)) {
18727                dumpState.setDump(DumpState.DUMP_INSTALLS);
18728            } else if ("frozen".equals(cmd)) {
18729                dumpState.setDump(DumpState.DUMP_FROZEN);
18730            } else if ("dexopt".equals(cmd)) {
18731                dumpState.setDump(DumpState.DUMP_DEXOPT);
18732            } else if ("compiler-stats".equals(cmd)) {
18733                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18734            } else if ("write".equals(cmd)) {
18735                synchronized (mPackages) {
18736                    mSettings.writeLPr();
18737                    pw.println("Settings written.");
18738                    return;
18739                }
18740            }
18741        }
18742
18743        if (checkin) {
18744            pw.println("vers,1");
18745        }
18746
18747        // reader
18748        synchronized (mPackages) {
18749            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18750                if (!checkin) {
18751                    if (dumpState.onTitlePrinted())
18752                        pw.println();
18753                    pw.println("Database versions:");
18754                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18755                }
18756            }
18757
18758            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18759                if (!checkin) {
18760                    if (dumpState.onTitlePrinted())
18761                        pw.println();
18762                    pw.println("Verifiers:");
18763                    pw.print("  Required: ");
18764                    pw.print(mRequiredVerifierPackage);
18765                    pw.print(" (uid=");
18766                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18767                            UserHandle.USER_SYSTEM));
18768                    pw.println(")");
18769                } else if (mRequiredVerifierPackage != null) {
18770                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18771                    pw.print(",");
18772                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18773                            UserHandle.USER_SYSTEM));
18774                }
18775            }
18776
18777            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18778                    packageName == null) {
18779                if (mIntentFilterVerifierComponent != null) {
18780                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18781                    if (!checkin) {
18782                        if (dumpState.onTitlePrinted())
18783                            pw.println();
18784                        pw.println("Intent Filter Verifier:");
18785                        pw.print("  Using: ");
18786                        pw.print(verifierPackageName);
18787                        pw.print(" (uid=");
18788                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18789                                UserHandle.USER_SYSTEM));
18790                        pw.println(")");
18791                    } else if (verifierPackageName != null) {
18792                        pw.print("ifv,"); pw.print(verifierPackageName);
18793                        pw.print(",");
18794                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18795                                UserHandle.USER_SYSTEM));
18796                    }
18797                } else {
18798                    pw.println();
18799                    pw.println("No Intent Filter Verifier available!");
18800                }
18801            }
18802
18803            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18804                boolean printedHeader = false;
18805                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18806                while (it.hasNext()) {
18807                    String name = it.next();
18808                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18809                    if (!checkin) {
18810                        if (!printedHeader) {
18811                            if (dumpState.onTitlePrinted())
18812                                pw.println();
18813                            pw.println("Libraries:");
18814                            printedHeader = true;
18815                        }
18816                        pw.print("  ");
18817                    } else {
18818                        pw.print("lib,");
18819                    }
18820                    pw.print(name);
18821                    if (!checkin) {
18822                        pw.print(" -> ");
18823                    }
18824                    if (ent.path != null) {
18825                        if (!checkin) {
18826                            pw.print("(jar) ");
18827                            pw.print(ent.path);
18828                        } else {
18829                            pw.print(",jar,");
18830                            pw.print(ent.path);
18831                        }
18832                    } else {
18833                        if (!checkin) {
18834                            pw.print("(apk) ");
18835                            pw.print(ent.apk);
18836                        } else {
18837                            pw.print(",apk,");
18838                            pw.print(ent.apk);
18839                        }
18840                    }
18841                    pw.println();
18842                }
18843            }
18844
18845            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18846                if (dumpState.onTitlePrinted())
18847                    pw.println();
18848                if (!checkin) {
18849                    pw.println("Features:");
18850                }
18851
18852                for (FeatureInfo feat : mAvailableFeatures.values()) {
18853                    if (checkin) {
18854                        pw.print("feat,");
18855                        pw.print(feat.name);
18856                        pw.print(",");
18857                        pw.println(feat.version);
18858                    } else {
18859                        pw.print("  ");
18860                        pw.print(feat.name);
18861                        if (feat.version > 0) {
18862                            pw.print(" version=");
18863                            pw.print(feat.version);
18864                        }
18865                        pw.println();
18866                    }
18867                }
18868            }
18869
18870            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18871                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18872                        : "Activity Resolver Table:", "  ", packageName,
18873                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18874                    dumpState.setTitlePrinted(true);
18875                }
18876            }
18877            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18878                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18879                        : "Receiver Resolver Table:", "  ", packageName,
18880                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18881                    dumpState.setTitlePrinted(true);
18882                }
18883            }
18884            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18885                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18886                        : "Service Resolver Table:", "  ", packageName,
18887                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18888                    dumpState.setTitlePrinted(true);
18889                }
18890            }
18891            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18892                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18893                        : "Provider Resolver Table:", "  ", packageName,
18894                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18895                    dumpState.setTitlePrinted(true);
18896                }
18897            }
18898
18899            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18900                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18901                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18902                    int user = mSettings.mPreferredActivities.keyAt(i);
18903                    if (pir.dump(pw,
18904                            dumpState.getTitlePrinted()
18905                                ? "\nPreferred Activities User " + user + ":"
18906                                : "Preferred Activities User " + user + ":", "  ",
18907                            packageName, true, false)) {
18908                        dumpState.setTitlePrinted(true);
18909                    }
18910                }
18911            }
18912
18913            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18914                pw.flush();
18915                FileOutputStream fout = new FileOutputStream(fd);
18916                BufferedOutputStream str = new BufferedOutputStream(fout);
18917                XmlSerializer serializer = new FastXmlSerializer();
18918                try {
18919                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18920                    serializer.startDocument(null, true);
18921                    serializer.setFeature(
18922                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18923                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18924                    serializer.endDocument();
18925                    serializer.flush();
18926                } catch (IllegalArgumentException e) {
18927                    pw.println("Failed writing: " + e);
18928                } catch (IllegalStateException e) {
18929                    pw.println("Failed writing: " + e);
18930                } catch (IOException e) {
18931                    pw.println("Failed writing: " + e);
18932                }
18933            }
18934
18935            if (!checkin
18936                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18937                    && packageName == null) {
18938                pw.println();
18939                int count = mSettings.mPackages.size();
18940                if (count == 0) {
18941                    pw.println("No applications!");
18942                    pw.println();
18943                } else {
18944                    final String prefix = "  ";
18945                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18946                    if (allPackageSettings.size() == 0) {
18947                        pw.println("No domain preferred apps!");
18948                        pw.println();
18949                    } else {
18950                        pw.println("App verification status:");
18951                        pw.println();
18952                        count = 0;
18953                        for (PackageSetting ps : allPackageSettings) {
18954                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18955                            if (ivi == null || ivi.getPackageName() == null) continue;
18956                            pw.println(prefix + "Package: " + ivi.getPackageName());
18957                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18958                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18959                            pw.println();
18960                            count++;
18961                        }
18962                        if (count == 0) {
18963                            pw.println(prefix + "No app verification established.");
18964                            pw.println();
18965                        }
18966                        for (int userId : sUserManager.getUserIds()) {
18967                            pw.println("App linkages for user " + userId + ":");
18968                            pw.println();
18969                            count = 0;
18970                            for (PackageSetting ps : allPackageSettings) {
18971                                final long status = ps.getDomainVerificationStatusForUser(userId);
18972                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18973                                    continue;
18974                                }
18975                                pw.println(prefix + "Package: " + ps.name);
18976                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18977                                String statusStr = IntentFilterVerificationInfo.
18978                                        getStatusStringFromValue(status);
18979                                pw.println(prefix + "Status:  " + statusStr);
18980                                pw.println();
18981                                count++;
18982                            }
18983                            if (count == 0) {
18984                                pw.println(prefix + "No configured app linkages.");
18985                                pw.println();
18986                            }
18987                        }
18988                    }
18989                }
18990            }
18991
18992            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18993                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18994                if (packageName == null && permissionNames == null) {
18995                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18996                        if (iperm == 0) {
18997                            if (dumpState.onTitlePrinted())
18998                                pw.println();
18999                            pw.println("AppOp Permissions:");
19000                        }
19001                        pw.print("  AppOp Permission ");
19002                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19003                        pw.println(":");
19004                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19005                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19006                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19007                        }
19008                    }
19009                }
19010            }
19011
19012            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19013                boolean printedSomething = false;
19014                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19015                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19016                        continue;
19017                    }
19018                    if (!printedSomething) {
19019                        if (dumpState.onTitlePrinted())
19020                            pw.println();
19021                        pw.println("Registered ContentProviders:");
19022                        printedSomething = true;
19023                    }
19024                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19025                    pw.print("    "); pw.println(p.toString());
19026                }
19027                printedSomething = false;
19028                for (Map.Entry<String, PackageParser.Provider> entry :
19029                        mProvidersByAuthority.entrySet()) {
19030                    PackageParser.Provider p = entry.getValue();
19031                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19032                        continue;
19033                    }
19034                    if (!printedSomething) {
19035                        if (dumpState.onTitlePrinted())
19036                            pw.println();
19037                        pw.println("ContentProvider Authorities:");
19038                        printedSomething = true;
19039                    }
19040                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19041                    pw.print("    "); pw.println(p.toString());
19042                    if (p.info != null && p.info.applicationInfo != null) {
19043                        final String appInfo = p.info.applicationInfo.toString();
19044                        pw.print("      applicationInfo="); pw.println(appInfo);
19045                    }
19046                }
19047            }
19048
19049            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19050                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19051            }
19052
19053            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19054                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19055            }
19056
19057            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19058                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19059            }
19060
19061            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19062                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19063            }
19064
19065            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19066                // XXX should handle packageName != null by dumping only install data that
19067                // the given package is involved with.
19068                if (dumpState.onTitlePrinted()) pw.println();
19069                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19070            }
19071
19072            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19073                // XXX should handle packageName != null by dumping only install data that
19074                // the given package is involved with.
19075                if (dumpState.onTitlePrinted()) pw.println();
19076
19077                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19078                ipw.println();
19079                ipw.println("Frozen packages:");
19080                ipw.increaseIndent();
19081                if (mFrozenPackages.size() == 0) {
19082                    ipw.println("(none)");
19083                } else {
19084                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19085                        ipw.println(mFrozenPackages.valueAt(i));
19086                    }
19087                }
19088                ipw.decreaseIndent();
19089            }
19090
19091            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19092                if (dumpState.onTitlePrinted()) pw.println();
19093                dumpDexoptStateLPr(pw, packageName);
19094            }
19095
19096            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19097                if (dumpState.onTitlePrinted()) pw.println();
19098                dumpCompilerStatsLPr(pw, packageName);
19099            }
19100
19101            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19102                if (dumpState.onTitlePrinted()) pw.println();
19103                mSettings.dumpReadMessagesLPr(pw, dumpState);
19104
19105                pw.println();
19106                pw.println("Package warning messages:");
19107                BufferedReader in = null;
19108                String line = null;
19109                try {
19110                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19111                    while ((line = in.readLine()) != null) {
19112                        if (line.contains("ignored: updated version")) continue;
19113                        pw.println(line);
19114                    }
19115                } catch (IOException ignored) {
19116                } finally {
19117                    IoUtils.closeQuietly(in);
19118                }
19119            }
19120
19121            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19122                BufferedReader in = null;
19123                String line = null;
19124                try {
19125                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19126                    while ((line = in.readLine()) != null) {
19127                        if (line.contains("ignored: updated version")) continue;
19128                        pw.print("msg,");
19129                        pw.println(line);
19130                    }
19131                } catch (IOException ignored) {
19132                } finally {
19133                    IoUtils.closeQuietly(in);
19134                }
19135            }
19136        }
19137    }
19138
19139    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19140        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19141        ipw.println();
19142        ipw.println("Dexopt state:");
19143        ipw.increaseIndent();
19144        Collection<PackageParser.Package> packages = null;
19145        if (packageName != null) {
19146            PackageParser.Package targetPackage = mPackages.get(packageName);
19147            if (targetPackage != null) {
19148                packages = Collections.singletonList(targetPackage);
19149            } else {
19150                ipw.println("Unable to find package: " + packageName);
19151                return;
19152            }
19153        } else {
19154            packages = mPackages.values();
19155        }
19156
19157        for (PackageParser.Package pkg : packages) {
19158            ipw.println("[" + pkg.packageName + "]");
19159            ipw.increaseIndent();
19160            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19161            ipw.decreaseIndent();
19162        }
19163    }
19164
19165    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19166        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19167        ipw.println();
19168        ipw.println("Compiler stats:");
19169        ipw.increaseIndent();
19170        Collection<PackageParser.Package> packages = null;
19171        if (packageName != null) {
19172            PackageParser.Package targetPackage = mPackages.get(packageName);
19173            if (targetPackage != null) {
19174                packages = Collections.singletonList(targetPackage);
19175            } else {
19176                ipw.println("Unable to find package: " + packageName);
19177                return;
19178            }
19179        } else {
19180            packages = mPackages.values();
19181        }
19182
19183        for (PackageParser.Package pkg : packages) {
19184            ipw.println("[" + pkg.packageName + "]");
19185            ipw.increaseIndent();
19186
19187            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19188            if (stats == null) {
19189                ipw.println("(No recorded stats)");
19190            } else {
19191                stats.dump(ipw);
19192            }
19193            ipw.decreaseIndent();
19194        }
19195    }
19196
19197    private String dumpDomainString(String packageName) {
19198        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19199                .getList();
19200        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19201
19202        ArraySet<String> result = new ArraySet<>();
19203        if (iviList.size() > 0) {
19204            for (IntentFilterVerificationInfo ivi : iviList) {
19205                for (String host : ivi.getDomains()) {
19206                    result.add(host);
19207                }
19208            }
19209        }
19210        if (filters != null && filters.size() > 0) {
19211            for (IntentFilter filter : filters) {
19212                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19213                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19214                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19215                    result.addAll(filter.getHostsList());
19216                }
19217            }
19218        }
19219
19220        StringBuilder sb = new StringBuilder(result.size() * 16);
19221        for (String domain : result) {
19222            if (sb.length() > 0) sb.append(" ");
19223            sb.append(domain);
19224        }
19225        return sb.toString();
19226    }
19227
19228    // ------- apps on sdcard specific code -------
19229    static final boolean DEBUG_SD_INSTALL = false;
19230
19231    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19232
19233    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19234
19235    private boolean mMediaMounted = false;
19236
19237    static String getEncryptKey() {
19238        try {
19239            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19240                    SD_ENCRYPTION_KEYSTORE_NAME);
19241            if (sdEncKey == null) {
19242                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19243                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19244                if (sdEncKey == null) {
19245                    Slog.e(TAG, "Failed to create encryption keys");
19246                    return null;
19247                }
19248            }
19249            return sdEncKey;
19250        } catch (NoSuchAlgorithmException nsae) {
19251            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19252            return null;
19253        } catch (IOException ioe) {
19254            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19255            return null;
19256        }
19257    }
19258
19259    /*
19260     * Update media status on PackageManager.
19261     */
19262    @Override
19263    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19264        int callingUid = Binder.getCallingUid();
19265        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19266            throw new SecurityException("Media status can only be updated by the system");
19267        }
19268        // reader; this apparently protects mMediaMounted, but should probably
19269        // be a different lock in that case.
19270        synchronized (mPackages) {
19271            Log.i(TAG, "Updating external media status from "
19272                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19273                    + (mediaStatus ? "mounted" : "unmounted"));
19274            if (DEBUG_SD_INSTALL)
19275                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19276                        + ", mMediaMounted=" + mMediaMounted);
19277            if (mediaStatus == mMediaMounted) {
19278                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19279                        : 0, -1);
19280                mHandler.sendMessage(msg);
19281                return;
19282            }
19283            mMediaMounted = mediaStatus;
19284        }
19285        // Queue up an async operation since the package installation may take a
19286        // little while.
19287        mHandler.post(new Runnable() {
19288            public void run() {
19289                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19290            }
19291        });
19292    }
19293
19294    /**
19295     * Called by MountService when the initial ASECs to scan are available.
19296     * Should block until all the ASEC containers are finished being scanned.
19297     */
19298    public void scanAvailableAsecs() {
19299        updateExternalMediaStatusInner(true, false, false);
19300    }
19301
19302    /*
19303     * Collect information of applications on external media, map them against
19304     * existing containers and update information based on current mount status.
19305     * Please note that we always have to report status if reportStatus has been
19306     * set to true especially when unloading packages.
19307     */
19308    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19309            boolean externalStorage) {
19310        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19311        int[] uidArr = EmptyArray.INT;
19312
19313        final String[] list = PackageHelper.getSecureContainerList();
19314        if (ArrayUtils.isEmpty(list)) {
19315            Log.i(TAG, "No secure containers found");
19316        } else {
19317            // Process list of secure containers and categorize them
19318            // as active or stale based on their package internal state.
19319
19320            // reader
19321            synchronized (mPackages) {
19322                for (String cid : list) {
19323                    // Leave stages untouched for now; installer service owns them
19324                    if (PackageInstallerService.isStageName(cid)) continue;
19325
19326                    if (DEBUG_SD_INSTALL)
19327                        Log.i(TAG, "Processing container " + cid);
19328                    String pkgName = getAsecPackageName(cid);
19329                    if (pkgName == null) {
19330                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19331                        continue;
19332                    }
19333                    if (DEBUG_SD_INSTALL)
19334                        Log.i(TAG, "Looking for pkg : " + pkgName);
19335
19336                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19337                    if (ps == null) {
19338                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19339                        continue;
19340                    }
19341
19342                    /*
19343                     * Skip packages that are not external if we're unmounting
19344                     * external storage.
19345                     */
19346                    if (externalStorage && !isMounted && !isExternal(ps)) {
19347                        continue;
19348                    }
19349
19350                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19351                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19352                    // The package status is changed only if the code path
19353                    // matches between settings and the container id.
19354                    if (ps.codePathString != null
19355                            && ps.codePathString.startsWith(args.getCodePath())) {
19356                        if (DEBUG_SD_INSTALL) {
19357                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19358                                    + " at code path: " + ps.codePathString);
19359                        }
19360
19361                        // We do have a valid package installed on sdcard
19362                        processCids.put(args, ps.codePathString);
19363                        final int uid = ps.appId;
19364                        if (uid != -1) {
19365                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19366                        }
19367                    } else {
19368                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19369                                + ps.codePathString);
19370                    }
19371                }
19372            }
19373
19374            Arrays.sort(uidArr);
19375        }
19376
19377        // Process packages with valid entries.
19378        if (isMounted) {
19379            if (DEBUG_SD_INSTALL)
19380                Log.i(TAG, "Loading packages");
19381            loadMediaPackages(processCids, uidArr, externalStorage);
19382            startCleaningPackages();
19383            mInstallerService.onSecureContainersAvailable();
19384        } else {
19385            if (DEBUG_SD_INSTALL)
19386                Log.i(TAG, "Unloading packages");
19387            unloadMediaPackages(processCids, uidArr, reportStatus);
19388        }
19389    }
19390
19391    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19392            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19393        final int size = infos.size();
19394        final String[] packageNames = new String[size];
19395        final int[] packageUids = new int[size];
19396        for (int i = 0; i < size; i++) {
19397            final ApplicationInfo info = infos.get(i);
19398            packageNames[i] = info.packageName;
19399            packageUids[i] = info.uid;
19400        }
19401        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19402                finishedReceiver);
19403    }
19404
19405    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19406            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19407        sendResourcesChangedBroadcast(mediaStatus, replacing,
19408                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19409    }
19410
19411    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19412            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19413        int size = pkgList.length;
19414        if (size > 0) {
19415            // Send broadcasts here
19416            Bundle extras = new Bundle();
19417            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19418            if (uidArr != null) {
19419                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19420            }
19421            if (replacing) {
19422                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19423            }
19424            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19425                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19426            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19427        }
19428    }
19429
19430   /*
19431     * Look at potentially valid container ids from processCids If package
19432     * information doesn't match the one on record or package scanning fails,
19433     * the cid is added to list of removeCids. We currently don't delete stale
19434     * containers.
19435     */
19436    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19437            boolean externalStorage) {
19438        ArrayList<String> pkgList = new ArrayList<String>();
19439        Set<AsecInstallArgs> keys = processCids.keySet();
19440
19441        for (AsecInstallArgs args : keys) {
19442            String codePath = processCids.get(args);
19443            if (DEBUG_SD_INSTALL)
19444                Log.i(TAG, "Loading container : " + args.cid);
19445            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19446            try {
19447                // Make sure there are no container errors first.
19448                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19449                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19450                            + " when installing from sdcard");
19451                    continue;
19452                }
19453                // Check code path here.
19454                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19455                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19456                            + " does not match one in settings " + codePath);
19457                    continue;
19458                }
19459                // Parse package
19460                int parseFlags = mDefParseFlags;
19461                if (args.isExternalAsec()) {
19462                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19463                }
19464                if (args.isFwdLocked()) {
19465                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19466                }
19467
19468                synchronized (mInstallLock) {
19469                    PackageParser.Package pkg = null;
19470                    try {
19471                        // Sadly we don't know the package name yet to freeze it
19472                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19473                                SCAN_IGNORE_FROZEN, 0, null);
19474                    } catch (PackageManagerException e) {
19475                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19476                    }
19477                    // Scan the package
19478                    if (pkg != null) {
19479                        /*
19480                         * TODO why is the lock being held? doPostInstall is
19481                         * called in other places without the lock. This needs
19482                         * to be straightened out.
19483                         */
19484                        // writer
19485                        synchronized (mPackages) {
19486                            retCode = PackageManager.INSTALL_SUCCEEDED;
19487                            pkgList.add(pkg.packageName);
19488                            // Post process args
19489                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19490                                    pkg.applicationInfo.uid);
19491                        }
19492                    } else {
19493                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19494                    }
19495                }
19496
19497            } finally {
19498                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19499                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19500                }
19501            }
19502        }
19503        // writer
19504        synchronized (mPackages) {
19505            // If the platform SDK has changed since the last time we booted,
19506            // we need to re-grant app permission to catch any new ones that
19507            // appear. This is really a hack, and means that apps can in some
19508            // cases get permissions that the user didn't initially explicitly
19509            // allow... it would be nice to have some better way to handle
19510            // this situation.
19511            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19512                    : mSettings.getInternalVersion();
19513            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19514                    : StorageManager.UUID_PRIVATE_INTERNAL;
19515
19516            int updateFlags = UPDATE_PERMISSIONS_ALL;
19517            if (ver.sdkVersion != mSdkVersion) {
19518                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19519                        + mSdkVersion + "; regranting permissions for external");
19520                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19521            }
19522            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19523
19524            // Yay, everything is now upgraded
19525            ver.forceCurrent();
19526
19527            // can downgrade to reader
19528            // Persist settings
19529            mSettings.writeLPr();
19530        }
19531        // Send a broadcast to let everyone know we are done processing
19532        if (pkgList.size() > 0) {
19533            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19534        }
19535    }
19536
19537   /*
19538     * Utility method to unload a list of specified containers
19539     */
19540    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19541        // Just unmount all valid containers.
19542        for (AsecInstallArgs arg : cidArgs) {
19543            synchronized (mInstallLock) {
19544                arg.doPostDeleteLI(false);
19545           }
19546       }
19547   }
19548
19549    /*
19550     * Unload packages mounted on external media. This involves deleting package
19551     * data from internal structures, sending broadcasts about disabled packages,
19552     * gc'ing to free up references, unmounting all secure containers
19553     * corresponding to packages on external media, and posting a
19554     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19555     * that we always have to post this message if status has been requested no
19556     * matter what.
19557     */
19558    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19559            final boolean reportStatus) {
19560        if (DEBUG_SD_INSTALL)
19561            Log.i(TAG, "unloading media packages");
19562        ArrayList<String> pkgList = new ArrayList<String>();
19563        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19564        final Set<AsecInstallArgs> keys = processCids.keySet();
19565        for (AsecInstallArgs args : keys) {
19566            String pkgName = args.getPackageName();
19567            if (DEBUG_SD_INSTALL)
19568                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19569            // Delete package internally
19570            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19571            synchronized (mInstallLock) {
19572                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19573                final boolean res;
19574                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19575                        "unloadMediaPackages")) {
19576                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19577                            null);
19578                }
19579                if (res) {
19580                    pkgList.add(pkgName);
19581                } else {
19582                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19583                    failedList.add(args);
19584                }
19585            }
19586        }
19587
19588        // reader
19589        synchronized (mPackages) {
19590            // We didn't update the settings after removing each package;
19591            // write them now for all packages.
19592            mSettings.writeLPr();
19593        }
19594
19595        // We have to absolutely send UPDATED_MEDIA_STATUS only
19596        // after confirming that all the receivers processed the ordered
19597        // broadcast when packages get disabled, force a gc to clean things up.
19598        // and unload all the containers.
19599        if (pkgList.size() > 0) {
19600            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19601                    new IIntentReceiver.Stub() {
19602                public void performReceive(Intent intent, int resultCode, String data,
19603                        Bundle extras, boolean ordered, boolean sticky,
19604                        int sendingUser) throws RemoteException {
19605                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19606                            reportStatus ? 1 : 0, 1, keys);
19607                    mHandler.sendMessage(msg);
19608                }
19609            });
19610        } else {
19611            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19612                    keys);
19613            mHandler.sendMessage(msg);
19614        }
19615    }
19616
19617    private void loadPrivatePackages(final VolumeInfo vol) {
19618        mHandler.post(new Runnable() {
19619            @Override
19620            public void run() {
19621                loadPrivatePackagesInner(vol);
19622            }
19623        });
19624    }
19625
19626    private void loadPrivatePackagesInner(VolumeInfo vol) {
19627        final String volumeUuid = vol.fsUuid;
19628        if (TextUtils.isEmpty(volumeUuid)) {
19629            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19630            return;
19631        }
19632
19633        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19634        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19635        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19636
19637        final VersionInfo ver;
19638        final List<PackageSetting> packages;
19639        synchronized (mPackages) {
19640            ver = mSettings.findOrCreateVersion(volumeUuid);
19641            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19642        }
19643
19644        for (PackageSetting ps : packages) {
19645            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19646            synchronized (mInstallLock) {
19647                final PackageParser.Package pkg;
19648                try {
19649                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19650                    loaded.add(pkg.applicationInfo);
19651
19652                } catch (PackageManagerException e) {
19653                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19654                }
19655
19656                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19657                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19658                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19659                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19660                }
19661            }
19662        }
19663
19664        // Reconcile app data for all started/unlocked users
19665        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19666        final UserManager um = mContext.getSystemService(UserManager.class);
19667        UserManagerInternal umInternal = getUserManagerInternal();
19668        for (UserInfo user : um.getUsers()) {
19669            final int flags;
19670            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19671                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19672            } else if (umInternal.isUserRunning(user.id)) {
19673                flags = StorageManager.FLAG_STORAGE_DE;
19674            } else {
19675                continue;
19676            }
19677
19678            try {
19679                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19680                synchronized (mInstallLock) {
19681                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19682                }
19683            } catch (IllegalStateException e) {
19684                // Device was probably ejected, and we'll process that event momentarily
19685                Slog.w(TAG, "Failed to prepare storage: " + e);
19686            }
19687        }
19688
19689        synchronized (mPackages) {
19690            int updateFlags = UPDATE_PERMISSIONS_ALL;
19691            if (ver.sdkVersion != mSdkVersion) {
19692                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19693                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19694                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19695            }
19696            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19697
19698            // Yay, everything is now upgraded
19699            ver.forceCurrent();
19700
19701            mSettings.writeLPr();
19702        }
19703
19704        for (PackageFreezer freezer : freezers) {
19705            freezer.close();
19706        }
19707
19708        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19709        sendResourcesChangedBroadcast(true, false, loaded, null);
19710    }
19711
19712    private void unloadPrivatePackages(final VolumeInfo vol) {
19713        mHandler.post(new Runnable() {
19714            @Override
19715            public void run() {
19716                unloadPrivatePackagesInner(vol);
19717            }
19718        });
19719    }
19720
19721    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19722        final String volumeUuid = vol.fsUuid;
19723        if (TextUtils.isEmpty(volumeUuid)) {
19724            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19725            return;
19726        }
19727
19728        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19729        synchronized (mInstallLock) {
19730        synchronized (mPackages) {
19731            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19732            for (PackageSetting ps : packages) {
19733                if (ps.pkg == null) continue;
19734
19735                final ApplicationInfo info = ps.pkg.applicationInfo;
19736                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19737                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19738
19739                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19740                        "unloadPrivatePackagesInner")) {
19741                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19742                            false, null)) {
19743                        unloaded.add(info);
19744                    } else {
19745                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19746                    }
19747                }
19748
19749                // Try very hard to release any references to this package
19750                // so we don't risk the system server being killed due to
19751                // open FDs
19752                AttributeCache.instance().removePackage(ps.name);
19753            }
19754
19755            mSettings.writeLPr();
19756        }
19757        }
19758
19759        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19760        sendResourcesChangedBroadcast(false, false, unloaded, null);
19761
19762        // Try very hard to release any references to this path so we don't risk
19763        // the system server being killed due to open FDs
19764        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19765
19766        for (int i = 0; i < 3; i++) {
19767            System.gc();
19768            System.runFinalization();
19769        }
19770    }
19771
19772    /**
19773     * Prepare storage areas for given user on all mounted devices.
19774     */
19775    void prepareUserData(int userId, int userSerial, int flags) {
19776        synchronized (mInstallLock) {
19777            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19778            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19779                final String volumeUuid = vol.getFsUuid();
19780                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19781            }
19782        }
19783    }
19784
19785    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19786            boolean allowRecover) {
19787        // Prepare storage and verify that serial numbers are consistent; if
19788        // there's a mismatch we need to destroy to avoid leaking data
19789        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19790        try {
19791            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19792
19793            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19794                UserManagerService.enforceSerialNumber(
19795                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19796                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19797                    UserManagerService.enforceSerialNumber(
19798                            Environment.getDataSystemDeDirectory(userId), userSerial);
19799                }
19800            }
19801            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19802                UserManagerService.enforceSerialNumber(
19803                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19804                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19805                    UserManagerService.enforceSerialNumber(
19806                            Environment.getDataSystemCeDirectory(userId), userSerial);
19807                }
19808            }
19809
19810            synchronized (mInstallLock) {
19811                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19812            }
19813        } catch (Exception e) {
19814            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19815                    + " because we failed to prepare: " + e);
19816            destroyUserDataLI(volumeUuid, userId,
19817                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19818
19819            if (allowRecover) {
19820                // Try one last time; if we fail again we're really in trouble
19821                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19822            }
19823        }
19824    }
19825
19826    /**
19827     * Destroy storage areas for given user on all mounted devices.
19828     */
19829    void destroyUserData(int userId, int flags) {
19830        synchronized (mInstallLock) {
19831            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19832            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19833                final String volumeUuid = vol.getFsUuid();
19834                destroyUserDataLI(volumeUuid, userId, flags);
19835            }
19836        }
19837    }
19838
19839    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19840        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19841        try {
19842            // Clean up app data, profile data, and media data
19843            mInstaller.destroyUserData(volumeUuid, userId, flags);
19844
19845            // Clean up system data
19846            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19847                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19848                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19849                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19850                }
19851                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19852                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19853                }
19854            }
19855
19856            // Data with special labels is now gone, so finish the job
19857            storage.destroyUserStorage(volumeUuid, userId, flags);
19858
19859        } catch (Exception e) {
19860            logCriticalInfo(Log.WARN,
19861                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19862        }
19863    }
19864
19865    /**
19866     * Examine all users present on given mounted volume, and destroy data
19867     * belonging to users that are no longer valid, or whose user ID has been
19868     * recycled.
19869     */
19870    private void reconcileUsers(String volumeUuid) {
19871        final List<File> files = new ArrayList<>();
19872        Collections.addAll(files, FileUtils
19873                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19874        Collections.addAll(files, FileUtils
19875                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19876        Collections.addAll(files, FileUtils
19877                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19878        Collections.addAll(files, FileUtils
19879                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19880        for (File file : files) {
19881            if (!file.isDirectory()) continue;
19882
19883            final int userId;
19884            final UserInfo info;
19885            try {
19886                userId = Integer.parseInt(file.getName());
19887                info = sUserManager.getUserInfo(userId);
19888            } catch (NumberFormatException e) {
19889                Slog.w(TAG, "Invalid user directory " + file);
19890                continue;
19891            }
19892
19893            boolean destroyUser = false;
19894            if (info == null) {
19895                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19896                        + " because no matching user was found");
19897                destroyUser = true;
19898            } else if (!mOnlyCore) {
19899                try {
19900                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19901                } catch (IOException e) {
19902                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19903                            + " because we failed to enforce serial number: " + e);
19904                    destroyUser = true;
19905                }
19906            }
19907
19908            if (destroyUser) {
19909                synchronized (mInstallLock) {
19910                    destroyUserDataLI(volumeUuid, userId,
19911                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19912                }
19913            }
19914        }
19915    }
19916
19917    private void assertPackageKnown(String volumeUuid, String packageName)
19918            throws PackageManagerException {
19919        synchronized (mPackages) {
19920            final PackageSetting ps = mSettings.mPackages.get(packageName);
19921            if (ps == null) {
19922                throw new PackageManagerException("Package " + packageName + " is unknown");
19923            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19924                throw new PackageManagerException(
19925                        "Package " + packageName + " found on unknown volume " + volumeUuid
19926                                + "; expected volume " + ps.volumeUuid);
19927            }
19928        }
19929    }
19930
19931    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19932            throws PackageManagerException {
19933        synchronized (mPackages) {
19934            final PackageSetting ps = mSettings.mPackages.get(packageName);
19935            if (ps == null) {
19936                throw new PackageManagerException("Package " + packageName + " is unknown");
19937            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19938                throw new PackageManagerException(
19939                        "Package " + packageName + " found on unknown volume " + volumeUuid
19940                                + "; expected volume " + ps.volumeUuid);
19941            } else if (!ps.getInstalled(userId)) {
19942                throw new PackageManagerException(
19943                        "Package " + packageName + " not installed for user " + userId);
19944            }
19945        }
19946    }
19947
19948    /**
19949     * Examine all apps present on given mounted volume, and destroy apps that
19950     * aren't expected, either due to uninstallation or reinstallation on
19951     * another volume.
19952     */
19953    private void reconcileApps(String volumeUuid) {
19954        final File[] files = FileUtils
19955                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19956        for (File file : files) {
19957            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19958                    && !PackageInstallerService.isStageName(file.getName());
19959            if (!isPackage) {
19960                // Ignore entries which are not packages
19961                continue;
19962            }
19963
19964            try {
19965                final PackageLite pkg = PackageParser.parsePackageLite(file,
19966                        PackageParser.PARSE_MUST_BE_APK);
19967                assertPackageKnown(volumeUuid, pkg.packageName);
19968
19969            } catch (PackageParserException | PackageManagerException e) {
19970                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19971                synchronized (mInstallLock) {
19972                    removeCodePathLI(file);
19973                }
19974            }
19975        }
19976    }
19977
19978    /**
19979     * Reconcile all app data for the given user.
19980     * <p>
19981     * Verifies that directories exist and that ownership and labeling is
19982     * correct for all installed apps on all mounted volumes.
19983     */
19984    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19985        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19986        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19987            final String volumeUuid = vol.getFsUuid();
19988            synchronized (mInstallLock) {
19989                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19990            }
19991        }
19992    }
19993
19994    /**
19995     * Reconcile all app data on given mounted volume.
19996     * <p>
19997     * Destroys app data that isn't expected, either due to uninstallation or
19998     * reinstallation on another volume.
19999     * <p>
20000     * Verifies that directories exist and that ownership and labeling is
20001     * correct for all installed apps.
20002     */
20003    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20004            boolean migrateAppData) {
20005        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20006                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20007
20008        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20009        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20010
20011        // First look for stale data that doesn't belong, and check if things
20012        // have changed since we did our last restorecon
20013        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20014            if (StorageManager.isFileEncryptedNativeOrEmulated()
20015                    && !StorageManager.isUserKeyUnlocked(userId)) {
20016                throw new RuntimeException(
20017                        "Yikes, someone asked us to reconcile CE storage while " + userId
20018                                + " was still locked; this would have caused massive data loss!");
20019            }
20020
20021            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20022            for (File file : files) {
20023                final String packageName = file.getName();
20024                try {
20025                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20026                } catch (PackageManagerException e) {
20027                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20028                    try {
20029                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20030                                StorageManager.FLAG_STORAGE_CE, 0);
20031                    } catch (InstallerException e2) {
20032                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20033                    }
20034                }
20035            }
20036        }
20037        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20038            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20039            for (File file : files) {
20040                final String packageName = file.getName();
20041                try {
20042                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20043                } catch (PackageManagerException e) {
20044                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20045                    try {
20046                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20047                                StorageManager.FLAG_STORAGE_DE, 0);
20048                    } catch (InstallerException e2) {
20049                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20050                    }
20051                }
20052            }
20053        }
20054
20055        // Ensure that data directories are ready to roll for all packages
20056        // installed for this volume and user
20057        final List<PackageSetting> packages;
20058        synchronized (mPackages) {
20059            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20060        }
20061        int preparedCount = 0;
20062        for (PackageSetting ps : packages) {
20063            final String packageName = ps.name;
20064            if (ps.pkg == null) {
20065                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20066                // TODO: might be due to legacy ASEC apps; we should circle back
20067                // and reconcile again once they're scanned
20068                continue;
20069            }
20070
20071            if (ps.getInstalled(userId)) {
20072                prepareAppDataLIF(ps.pkg, userId, flags);
20073
20074                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20075                    // We may have just shuffled around app data directories, so
20076                    // prepare them one more time
20077                    prepareAppDataLIF(ps.pkg, userId, flags);
20078                }
20079
20080                preparedCount++;
20081            }
20082        }
20083
20084        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20085    }
20086
20087    /**
20088     * Prepare app data for the given app just after it was installed or
20089     * upgraded. This method carefully only touches users that it's installed
20090     * for, and it forces a restorecon to handle any seinfo changes.
20091     * <p>
20092     * Verifies that directories exist and that ownership and labeling is
20093     * correct for all installed apps. If there is an ownership mismatch, it
20094     * will try recovering system apps by wiping data; third-party app data is
20095     * left intact.
20096     * <p>
20097     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20098     */
20099    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20100        final PackageSetting ps;
20101        synchronized (mPackages) {
20102            ps = mSettings.mPackages.get(pkg.packageName);
20103            mSettings.writeKernelMappingLPr(ps);
20104        }
20105
20106        final UserManager um = mContext.getSystemService(UserManager.class);
20107        UserManagerInternal umInternal = getUserManagerInternal();
20108        for (UserInfo user : um.getUsers()) {
20109            final int flags;
20110            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20111                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20112            } else if (umInternal.isUserRunning(user.id)) {
20113                flags = StorageManager.FLAG_STORAGE_DE;
20114            } else {
20115                continue;
20116            }
20117
20118            if (ps.getInstalled(user.id)) {
20119                // TODO: when user data is locked, mark that we're still dirty
20120                prepareAppDataLIF(pkg, user.id, flags);
20121            }
20122        }
20123    }
20124
20125    /**
20126     * Prepare app data for the given app.
20127     * <p>
20128     * Verifies that directories exist and that ownership and labeling is
20129     * correct for all installed apps. If there is an ownership mismatch, this
20130     * will try recovering system apps by wiping data; third-party app data is
20131     * left intact.
20132     */
20133    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20134        if (pkg == null) {
20135            Slog.wtf(TAG, "Package was null!", new Throwable());
20136            return;
20137        }
20138        prepareAppDataLeafLIF(pkg, userId, flags);
20139        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20140        for (int i = 0; i < childCount; i++) {
20141            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20142        }
20143    }
20144
20145    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20146        if (DEBUG_APP_DATA) {
20147            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20148                    + Integer.toHexString(flags));
20149        }
20150
20151        final String volumeUuid = pkg.volumeUuid;
20152        final String packageName = pkg.packageName;
20153        final ApplicationInfo app = pkg.applicationInfo;
20154        final int appId = UserHandle.getAppId(app.uid);
20155
20156        Preconditions.checkNotNull(app.seinfo);
20157
20158        try {
20159            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20160                    appId, app.seinfo, app.targetSdkVersion);
20161        } catch (InstallerException e) {
20162            if (app.isSystemApp()) {
20163                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20164                        + ", but trying to recover: " + e);
20165                destroyAppDataLeafLIF(pkg, userId, flags);
20166                try {
20167                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20168                            appId, app.seinfo, app.targetSdkVersion);
20169                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20170                } catch (InstallerException e2) {
20171                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20172                }
20173            } else {
20174                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20175            }
20176        }
20177
20178        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20179            try {
20180                // CE storage is unlocked right now, so read out the inode and
20181                // remember for use later when it's locked
20182                // TODO: mark this structure as dirty so we persist it!
20183                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20184                        StorageManager.FLAG_STORAGE_CE);
20185                synchronized (mPackages) {
20186                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20187                    if (ps != null) {
20188                        ps.setCeDataInode(ceDataInode, userId);
20189                    }
20190                }
20191            } catch (InstallerException e) {
20192                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20193            }
20194        }
20195
20196        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20197    }
20198
20199    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20200        if (pkg == null) {
20201            Slog.wtf(TAG, "Package was null!", new Throwable());
20202            return;
20203        }
20204        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20206        for (int i = 0; i < childCount; i++) {
20207            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20208        }
20209    }
20210
20211    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20212        final String volumeUuid = pkg.volumeUuid;
20213        final String packageName = pkg.packageName;
20214        final ApplicationInfo app = pkg.applicationInfo;
20215
20216        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20217            // Create a native library symlink only if we have native libraries
20218            // and if the native libraries are 32 bit libraries. We do not provide
20219            // this symlink for 64 bit libraries.
20220            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20221                final String nativeLibPath = app.nativeLibraryDir;
20222                try {
20223                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20224                            nativeLibPath, userId);
20225                } catch (InstallerException e) {
20226                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20227                }
20228            }
20229        }
20230    }
20231
20232    /**
20233     * For system apps on non-FBE devices, this method migrates any existing
20234     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20235     * requested by the app.
20236     */
20237    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20238        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20239                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20240            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20241                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20242            try {
20243                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20244                        storageTarget);
20245            } catch (InstallerException e) {
20246                logCriticalInfo(Log.WARN,
20247                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20248            }
20249            return true;
20250        } else {
20251            return false;
20252        }
20253    }
20254
20255    public PackageFreezer freezePackage(String packageName, String killReason) {
20256        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20257    }
20258
20259    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20260        return new PackageFreezer(packageName, userId, killReason);
20261    }
20262
20263    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20264            String killReason) {
20265        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20266    }
20267
20268    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20269            String killReason) {
20270        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20271            return new PackageFreezer();
20272        } else {
20273            return freezePackage(packageName, userId, killReason);
20274        }
20275    }
20276
20277    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20278            String killReason) {
20279        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20280    }
20281
20282    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20283            String killReason) {
20284        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20285            return new PackageFreezer();
20286        } else {
20287            return freezePackage(packageName, userId, killReason);
20288        }
20289    }
20290
20291    /**
20292     * Class that freezes and kills the given package upon creation, and
20293     * unfreezes it upon closing. This is typically used when doing surgery on
20294     * app code/data to prevent the app from running while you're working.
20295     */
20296    private class PackageFreezer implements AutoCloseable {
20297        private final String mPackageName;
20298        private final PackageFreezer[] mChildren;
20299
20300        private final boolean mWeFroze;
20301
20302        private final AtomicBoolean mClosed = new AtomicBoolean();
20303        private final CloseGuard mCloseGuard = CloseGuard.get();
20304
20305        /**
20306         * Create and return a stub freezer that doesn't actually do anything,
20307         * typically used when someone requested
20308         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20309         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20310         */
20311        public PackageFreezer() {
20312            mPackageName = null;
20313            mChildren = null;
20314            mWeFroze = false;
20315            mCloseGuard.open("close");
20316        }
20317
20318        public PackageFreezer(String packageName, int userId, String killReason) {
20319            synchronized (mPackages) {
20320                mPackageName = packageName;
20321                mWeFroze = mFrozenPackages.add(mPackageName);
20322
20323                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20324                if (ps != null) {
20325                    killApplication(ps.name, ps.appId, userId, killReason);
20326                }
20327
20328                final PackageParser.Package p = mPackages.get(packageName);
20329                if (p != null && p.childPackages != null) {
20330                    final int N = p.childPackages.size();
20331                    mChildren = new PackageFreezer[N];
20332                    for (int i = 0; i < N; i++) {
20333                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20334                                userId, killReason);
20335                    }
20336                } else {
20337                    mChildren = null;
20338                }
20339            }
20340            mCloseGuard.open("close");
20341        }
20342
20343        @Override
20344        protected void finalize() throws Throwable {
20345            try {
20346                mCloseGuard.warnIfOpen();
20347                close();
20348            } finally {
20349                super.finalize();
20350            }
20351        }
20352
20353        @Override
20354        public void close() {
20355            mCloseGuard.close();
20356            if (mClosed.compareAndSet(false, true)) {
20357                synchronized (mPackages) {
20358                    if (mWeFroze) {
20359                        mFrozenPackages.remove(mPackageName);
20360                    }
20361
20362                    if (mChildren != null) {
20363                        for (PackageFreezer freezer : mChildren) {
20364                            freezer.close();
20365                        }
20366                    }
20367                }
20368            }
20369        }
20370    }
20371
20372    /**
20373     * Verify that given package is currently frozen.
20374     */
20375    private void checkPackageFrozen(String packageName) {
20376        synchronized (mPackages) {
20377            if (!mFrozenPackages.contains(packageName)) {
20378                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20379            }
20380        }
20381    }
20382
20383    @Override
20384    public int movePackage(final String packageName, final String volumeUuid) {
20385        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20386
20387        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20388        final int moveId = mNextMoveId.getAndIncrement();
20389        mHandler.post(new Runnable() {
20390            @Override
20391            public void run() {
20392                try {
20393                    movePackageInternal(packageName, volumeUuid, moveId, user);
20394                } catch (PackageManagerException e) {
20395                    Slog.w(TAG, "Failed to move " + packageName, e);
20396                    mMoveCallbacks.notifyStatusChanged(moveId,
20397                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20398                }
20399            }
20400        });
20401        return moveId;
20402    }
20403
20404    private void movePackageInternal(final String packageName, final String volumeUuid,
20405            final int moveId, UserHandle user) throws PackageManagerException {
20406        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20407        final PackageManager pm = mContext.getPackageManager();
20408
20409        final boolean currentAsec;
20410        final String currentVolumeUuid;
20411        final File codeFile;
20412        final String installerPackageName;
20413        final String packageAbiOverride;
20414        final int appId;
20415        final String seinfo;
20416        final String label;
20417        final int targetSdkVersion;
20418        final PackageFreezer freezer;
20419        final int[] installedUserIds;
20420
20421        // reader
20422        synchronized (mPackages) {
20423            final PackageParser.Package pkg = mPackages.get(packageName);
20424            final PackageSetting ps = mSettings.mPackages.get(packageName);
20425            if (pkg == null || ps == null) {
20426                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20427            }
20428
20429            if (pkg.applicationInfo.isSystemApp()) {
20430                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20431                        "Cannot move system application");
20432            }
20433
20434            if (pkg.applicationInfo.isExternalAsec()) {
20435                currentAsec = true;
20436                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20437            } else if (pkg.applicationInfo.isForwardLocked()) {
20438                currentAsec = true;
20439                currentVolumeUuid = "forward_locked";
20440            } else {
20441                currentAsec = false;
20442                currentVolumeUuid = ps.volumeUuid;
20443
20444                final File probe = new File(pkg.codePath);
20445                final File probeOat = new File(probe, "oat");
20446                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20447                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20448                            "Move only supported for modern cluster style installs");
20449                }
20450            }
20451
20452            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20453                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20454                        "Package already moved to " + volumeUuid);
20455            }
20456            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20457                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20458                        "Device admin cannot be moved");
20459            }
20460
20461            if (mFrozenPackages.contains(packageName)) {
20462                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20463                        "Failed to move already frozen package");
20464            }
20465
20466            codeFile = new File(pkg.codePath);
20467            installerPackageName = ps.installerPackageName;
20468            packageAbiOverride = ps.cpuAbiOverrideString;
20469            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20470            seinfo = pkg.applicationInfo.seinfo;
20471            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20472            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20473            freezer = freezePackage(packageName, "movePackageInternal");
20474            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20475        }
20476
20477        final Bundle extras = new Bundle();
20478        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20479        extras.putString(Intent.EXTRA_TITLE, label);
20480        mMoveCallbacks.notifyCreated(moveId, extras);
20481
20482        int installFlags;
20483        final boolean moveCompleteApp;
20484        final File measurePath;
20485
20486        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20487            installFlags = INSTALL_INTERNAL;
20488            moveCompleteApp = !currentAsec;
20489            measurePath = Environment.getDataAppDirectory(volumeUuid);
20490        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20491            installFlags = INSTALL_EXTERNAL;
20492            moveCompleteApp = false;
20493            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20494        } else {
20495            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20496            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20497                    || !volume.isMountedWritable()) {
20498                freezer.close();
20499                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20500                        "Move location not mounted private volume");
20501            }
20502
20503            Preconditions.checkState(!currentAsec);
20504
20505            installFlags = INSTALL_INTERNAL;
20506            moveCompleteApp = true;
20507            measurePath = Environment.getDataAppDirectory(volumeUuid);
20508        }
20509
20510        final PackageStats stats = new PackageStats(null, -1);
20511        synchronized (mInstaller) {
20512            for (int userId : installedUserIds) {
20513                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20514                    freezer.close();
20515                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20516                            "Failed to measure package size");
20517                }
20518            }
20519        }
20520
20521        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20522                + stats.dataSize);
20523
20524        final long startFreeBytes = measurePath.getFreeSpace();
20525        final long sizeBytes;
20526        if (moveCompleteApp) {
20527            sizeBytes = stats.codeSize + stats.dataSize;
20528        } else {
20529            sizeBytes = stats.codeSize;
20530        }
20531
20532        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20533            freezer.close();
20534            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20535                    "Not enough free space to move");
20536        }
20537
20538        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20539
20540        final CountDownLatch installedLatch = new CountDownLatch(1);
20541        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20542            @Override
20543            public void onUserActionRequired(Intent intent) throws RemoteException {
20544                throw new IllegalStateException();
20545            }
20546
20547            @Override
20548            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20549                    Bundle extras) throws RemoteException {
20550                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20551                        + PackageManager.installStatusToString(returnCode, msg));
20552
20553                installedLatch.countDown();
20554                freezer.close();
20555
20556                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20557                switch (status) {
20558                    case PackageInstaller.STATUS_SUCCESS:
20559                        mMoveCallbacks.notifyStatusChanged(moveId,
20560                                PackageManager.MOVE_SUCCEEDED);
20561                        break;
20562                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20563                        mMoveCallbacks.notifyStatusChanged(moveId,
20564                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20565                        break;
20566                    default:
20567                        mMoveCallbacks.notifyStatusChanged(moveId,
20568                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20569                        break;
20570                }
20571            }
20572        };
20573
20574        final MoveInfo move;
20575        if (moveCompleteApp) {
20576            // Kick off a thread to report progress estimates
20577            new Thread() {
20578                @Override
20579                public void run() {
20580                    while (true) {
20581                        try {
20582                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20583                                break;
20584                            }
20585                        } catch (InterruptedException ignored) {
20586                        }
20587
20588                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20589                        final int progress = 10 + (int) MathUtils.constrain(
20590                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20591                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20592                    }
20593                }
20594            }.start();
20595
20596            final String dataAppName = codeFile.getName();
20597            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20598                    dataAppName, appId, seinfo, targetSdkVersion);
20599        } else {
20600            move = null;
20601        }
20602
20603        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20604
20605        final Message msg = mHandler.obtainMessage(INIT_COPY);
20606        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20607        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20608                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20609                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20610        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20611        msg.obj = params;
20612
20613        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20614                System.identityHashCode(msg.obj));
20615        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20616                System.identityHashCode(msg.obj));
20617
20618        mHandler.sendMessage(msg);
20619    }
20620
20621    @Override
20622    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20623        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20624
20625        final int realMoveId = mNextMoveId.getAndIncrement();
20626        final Bundle extras = new Bundle();
20627        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20628        mMoveCallbacks.notifyCreated(realMoveId, extras);
20629
20630        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20631            @Override
20632            public void onCreated(int moveId, Bundle extras) {
20633                // Ignored
20634            }
20635
20636            @Override
20637            public void onStatusChanged(int moveId, int status, long estMillis) {
20638                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20639            }
20640        };
20641
20642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20643        storage.setPrimaryStorageUuid(volumeUuid, callback);
20644        return realMoveId;
20645    }
20646
20647    @Override
20648    public int getMoveStatus(int moveId) {
20649        mContext.enforceCallingOrSelfPermission(
20650                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20651        return mMoveCallbacks.mLastStatus.get(moveId);
20652    }
20653
20654    @Override
20655    public void registerMoveCallback(IPackageMoveObserver callback) {
20656        mContext.enforceCallingOrSelfPermission(
20657                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20658        mMoveCallbacks.register(callback);
20659    }
20660
20661    @Override
20662    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20663        mContext.enforceCallingOrSelfPermission(
20664                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20665        mMoveCallbacks.unregister(callback);
20666    }
20667
20668    @Override
20669    public boolean setInstallLocation(int loc) {
20670        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20671                null);
20672        if (getInstallLocation() == loc) {
20673            return true;
20674        }
20675        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20676                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20677            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20678                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20679            return true;
20680        }
20681        return false;
20682   }
20683
20684    @Override
20685    public int getInstallLocation() {
20686        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20687                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20688                PackageHelper.APP_INSTALL_AUTO);
20689    }
20690
20691    /** Called by UserManagerService */
20692    void cleanUpUser(UserManagerService userManager, int userHandle) {
20693        synchronized (mPackages) {
20694            mDirtyUsers.remove(userHandle);
20695            mUserNeedsBadging.delete(userHandle);
20696            mSettings.removeUserLPw(userHandle);
20697            mPendingBroadcasts.remove(userHandle);
20698            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20699            removeUnusedPackagesLPw(userManager, userHandle);
20700        }
20701    }
20702
20703    /**
20704     * We're removing userHandle and would like to remove any downloaded packages
20705     * that are no longer in use by any other user.
20706     * @param userHandle the user being removed
20707     */
20708    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20709        final boolean DEBUG_CLEAN_APKS = false;
20710        int [] users = userManager.getUserIds();
20711        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20712        while (psit.hasNext()) {
20713            PackageSetting ps = psit.next();
20714            if (ps.pkg == null) {
20715                continue;
20716            }
20717            final String packageName = ps.pkg.packageName;
20718            // Skip over if system app
20719            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20720                continue;
20721            }
20722            if (DEBUG_CLEAN_APKS) {
20723                Slog.i(TAG, "Checking package " + packageName);
20724            }
20725            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20726            if (keep) {
20727                if (DEBUG_CLEAN_APKS) {
20728                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20729                }
20730            } else {
20731                for (int i = 0; i < users.length; i++) {
20732                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20733                        keep = true;
20734                        if (DEBUG_CLEAN_APKS) {
20735                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20736                                    + users[i]);
20737                        }
20738                        break;
20739                    }
20740                }
20741            }
20742            if (!keep) {
20743                if (DEBUG_CLEAN_APKS) {
20744                    Slog.i(TAG, "  Removing package " + packageName);
20745                }
20746                mHandler.post(new Runnable() {
20747                    public void run() {
20748                        deletePackageX(packageName, userHandle, 0);
20749                    } //end run
20750                });
20751            }
20752        }
20753    }
20754
20755    /** Called by UserManagerService */
20756    void createNewUser(int userId, String[] disallowedPackages) {
20757        synchronized (mInstallLock) {
20758            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20759        }
20760        synchronized (mPackages) {
20761            scheduleWritePackageRestrictionsLocked(userId);
20762            scheduleWritePackageListLocked(userId);
20763            applyFactoryDefaultBrowserLPw(userId);
20764            primeDomainVerificationsLPw(userId);
20765        }
20766    }
20767
20768    void onNewUserCreated(final int userId) {
20769        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20770        // If permission review for legacy apps is required, we represent
20771        // dagerous permissions for such apps as always granted runtime
20772        // permissions to keep per user flag state whether review is needed.
20773        // Hence, if a new user is added we have to propagate dangerous
20774        // permission grants for these legacy apps.
20775        if (mPermissionReviewRequired) {
20776            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20777                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20778        }
20779    }
20780
20781    @Override
20782    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20783        mContext.enforceCallingOrSelfPermission(
20784                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20785                "Only package verification agents can read the verifier device identity");
20786
20787        synchronized (mPackages) {
20788            return mSettings.getVerifierDeviceIdentityLPw();
20789        }
20790    }
20791
20792    @Override
20793    public void setPermissionEnforced(String permission, boolean enforced) {
20794        // TODO: Now that we no longer change GID for storage, this should to away.
20795        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20796                "setPermissionEnforced");
20797        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20798            synchronized (mPackages) {
20799                if (mSettings.mReadExternalStorageEnforced == null
20800                        || mSettings.mReadExternalStorageEnforced != enforced) {
20801                    mSettings.mReadExternalStorageEnforced = enforced;
20802                    mSettings.writeLPr();
20803                }
20804            }
20805            // kill any non-foreground processes so we restart them and
20806            // grant/revoke the GID.
20807            final IActivityManager am = ActivityManager.getService();
20808            if (am != null) {
20809                final long token = Binder.clearCallingIdentity();
20810                try {
20811                    am.killProcessesBelowForeground("setPermissionEnforcement");
20812                } catch (RemoteException e) {
20813                } finally {
20814                    Binder.restoreCallingIdentity(token);
20815                }
20816            }
20817        } else {
20818            throw new IllegalArgumentException("No selective enforcement for " + permission);
20819        }
20820    }
20821
20822    @Override
20823    @Deprecated
20824    public boolean isPermissionEnforced(String permission) {
20825        return true;
20826    }
20827
20828    @Override
20829    public boolean isStorageLow() {
20830        final long token = Binder.clearCallingIdentity();
20831        try {
20832            final DeviceStorageMonitorInternal
20833                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20834            if (dsm != null) {
20835                return dsm.isMemoryLow();
20836            } else {
20837                return false;
20838            }
20839        } finally {
20840            Binder.restoreCallingIdentity(token);
20841        }
20842    }
20843
20844    @Override
20845    public IPackageInstaller getPackageInstaller() {
20846        return mInstallerService;
20847    }
20848
20849    private boolean userNeedsBadging(int userId) {
20850        int index = mUserNeedsBadging.indexOfKey(userId);
20851        if (index < 0) {
20852            final UserInfo userInfo;
20853            final long token = Binder.clearCallingIdentity();
20854            try {
20855                userInfo = sUserManager.getUserInfo(userId);
20856            } finally {
20857                Binder.restoreCallingIdentity(token);
20858            }
20859            final boolean b;
20860            if (userInfo != null && userInfo.isManagedProfile()) {
20861                b = true;
20862            } else {
20863                b = false;
20864            }
20865            mUserNeedsBadging.put(userId, b);
20866            return b;
20867        }
20868        return mUserNeedsBadging.valueAt(index);
20869    }
20870
20871    @Override
20872    public KeySet getKeySetByAlias(String packageName, String alias) {
20873        if (packageName == null || alias == null) {
20874            return null;
20875        }
20876        synchronized(mPackages) {
20877            final PackageParser.Package pkg = mPackages.get(packageName);
20878            if (pkg == null) {
20879                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20880                throw new IllegalArgumentException("Unknown package: " + packageName);
20881            }
20882            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20883            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20884        }
20885    }
20886
20887    @Override
20888    public KeySet getSigningKeySet(String packageName) {
20889        if (packageName == null) {
20890            return null;
20891        }
20892        synchronized(mPackages) {
20893            final PackageParser.Package pkg = mPackages.get(packageName);
20894            if (pkg == null) {
20895                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20896                throw new IllegalArgumentException("Unknown package: " + packageName);
20897            }
20898            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20899                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20900                throw new SecurityException("May not access signing KeySet of other apps.");
20901            }
20902            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20903            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20904        }
20905    }
20906
20907    @Override
20908    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20909        if (packageName == null || ks == null) {
20910            return false;
20911        }
20912        synchronized(mPackages) {
20913            final PackageParser.Package pkg = mPackages.get(packageName);
20914            if (pkg == null) {
20915                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20916                throw new IllegalArgumentException("Unknown package: " + packageName);
20917            }
20918            IBinder ksh = ks.getToken();
20919            if (ksh instanceof KeySetHandle) {
20920                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20921                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20922            }
20923            return false;
20924        }
20925    }
20926
20927    @Override
20928    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20929        if (packageName == null || ks == null) {
20930            return false;
20931        }
20932        synchronized(mPackages) {
20933            final PackageParser.Package pkg = mPackages.get(packageName);
20934            if (pkg == null) {
20935                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20936                throw new IllegalArgumentException("Unknown package: " + packageName);
20937            }
20938            IBinder ksh = ks.getToken();
20939            if (ksh instanceof KeySetHandle) {
20940                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20941                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20942            }
20943            return false;
20944        }
20945    }
20946
20947    private void deletePackageIfUnusedLPr(final String packageName) {
20948        PackageSetting ps = mSettings.mPackages.get(packageName);
20949        if (ps == null) {
20950            return;
20951        }
20952        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20953            // TODO Implement atomic delete if package is unused
20954            // It is currently possible that the package will be deleted even if it is installed
20955            // after this method returns.
20956            mHandler.post(new Runnable() {
20957                public void run() {
20958                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20959                }
20960            });
20961        }
20962    }
20963
20964    /**
20965     * Check and throw if the given before/after packages would be considered a
20966     * downgrade.
20967     */
20968    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20969            throws PackageManagerException {
20970        if (after.versionCode < before.mVersionCode) {
20971            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20972                    "Update version code " + after.versionCode + " is older than current "
20973                    + before.mVersionCode);
20974        } else if (after.versionCode == before.mVersionCode) {
20975            if (after.baseRevisionCode < before.baseRevisionCode) {
20976                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20977                        "Update base revision code " + after.baseRevisionCode
20978                        + " is older than current " + before.baseRevisionCode);
20979            }
20980
20981            if (!ArrayUtils.isEmpty(after.splitNames)) {
20982                for (int i = 0; i < after.splitNames.length; i++) {
20983                    final String splitName = after.splitNames[i];
20984                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20985                    if (j != -1) {
20986                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20987                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20988                                    "Update split " + splitName + " revision code "
20989                                    + after.splitRevisionCodes[i] + " is older than current "
20990                                    + before.splitRevisionCodes[j]);
20991                        }
20992                    }
20993                }
20994            }
20995        }
20996    }
20997
20998    private static class MoveCallbacks extends Handler {
20999        private static final int MSG_CREATED = 1;
21000        private static final int MSG_STATUS_CHANGED = 2;
21001
21002        private final RemoteCallbackList<IPackageMoveObserver>
21003                mCallbacks = new RemoteCallbackList<>();
21004
21005        private final SparseIntArray mLastStatus = new SparseIntArray();
21006
21007        public MoveCallbacks(Looper looper) {
21008            super(looper);
21009        }
21010
21011        public void register(IPackageMoveObserver callback) {
21012            mCallbacks.register(callback);
21013        }
21014
21015        public void unregister(IPackageMoveObserver callback) {
21016            mCallbacks.unregister(callback);
21017        }
21018
21019        @Override
21020        public void handleMessage(Message msg) {
21021            final SomeArgs args = (SomeArgs) msg.obj;
21022            final int n = mCallbacks.beginBroadcast();
21023            for (int i = 0; i < n; i++) {
21024                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21025                try {
21026                    invokeCallback(callback, msg.what, args);
21027                } catch (RemoteException ignored) {
21028                }
21029            }
21030            mCallbacks.finishBroadcast();
21031            args.recycle();
21032        }
21033
21034        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21035                throws RemoteException {
21036            switch (what) {
21037                case MSG_CREATED: {
21038                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21039                    break;
21040                }
21041                case MSG_STATUS_CHANGED: {
21042                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21043                    break;
21044                }
21045            }
21046        }
21047
21048        private void notifyCreated(int moveId, Bundle extras) {
21049            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21050
21051            final SomeArgs args = SomeArgs.obtain();
21052            args.argi1 = moveId;
21053            args.arg2 = extras;
21054            obtainMessage(MSG_CREATED, args).sendToTarget();
21055        }
21056
21057        private void notifyStatusChanged(int moveId, int status) {
21058            notifyStatusChanged(moveId, status, -1);
21059        }
21060
21061        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21062            Slog.v(TAG, "Move " + moveId + " status " + status);
21063
21064            final SomeArgs args = SomeArgs.obtain();
21065            args.argi1 = moveId;
21066            args.argi2 = status;
21067            args.arg3 = estMillis;
21068            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21069
21070            synchronized (mLastStatus) {
21071                mLastStatus.put(moveId, status);
21072            }
21073        }
21074    }
21075
21076    private final static class OnPermissionChangeListeners extends Handler {
21077        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21078
21079        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21080                new RemoteCallbackList<>();
21081
21082        public OnPermissionChangeListeners(Looper looper) {
21083            super(looper);
21084        }
21085
21086        @Override
21087        public void handleMessage(Message msg) {
21088            switch (msg.what) {
21089                case MSG_ON_PERMISSIONS_CHANGED: {
21090                    final int uid = msg.arg1;
21091                    handleOnPermissionsChanged(uid);
21092                } break;
21093            }
21094        }
21095
21096        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21097            mPermissionListeners.register(listener);
21098
21099        }
21100
21101        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21102            mPermissionListeners.unregister(listener);
21103        }
21104
21105        public void onPermissionsChanged(int uid) {
21106            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21107                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21108            }
21109        }
21110
21111        private void handleOnPermissionsChanged(int uid) {
21112            final int count = mPermissionListeners.beginBroadcast();
21113            try {
21114                for (int i = 0; i < count; i++) {
21115                    IOnPermissionsChangeListener callback = mPermissionListeners
21116                            .getBroadcastItem(i);
21117                    try {
21118                        callback.onPermissionsChanged(uid);
21119                    } catch (RemoteException e) {
21120                        Log.e(TAG, "Permission listener is dead", e);
21121                    }
21122                }
21123            } finally {
21124                mPermissionListeners.finishBroadcast();
21125            }
21126        }
21127    }
21128
21129    private class PackageManagerInternalImpl extends PackageManagerInternal {
21130        @Override
21131        public void setLocationPackagesProvider(PackagesProvider provider) {
21132            synchronized (mPackages) {
21133                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21134            }
21135        }
21136
21137        @Override
21138        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21139            synchronized (mPackages) {
21140                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21141            }
21142        }
21143
21144        @Override
21145        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21146            synchronized (mPackages) {
21147                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21148            }
21149        }
21150
21151        @Override
21152        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21153            synchronized (mPackages) {
21154                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21155            }
21156        }
21157
21158        @Override
21159        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21160            synchronized (mPackages) {
21161                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21162            }
21163        }
21164
21165        @Override
21166        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21167            synchronized (mPackages) {
21168                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21169            }
21170        }
21171
21172        @Override
21173        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21174            synchronized (mPackages) {
21175                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21176                        packageName, userId);
21177            }
21178        }
21179
21180        @Override
21181        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21182            synchronized (mPackages) {
21183                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21184                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21185                        packageName, userId);
21186            }
21187        }
21188
21189        @Override
21190        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21191            synchronized (mPackages) {
21192                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21193                        packageName, userId);
21194            }
21195        }
21196
21197        @Override
21198        public void setKeepUninstalledPackages(final List<String> packageList) {
21199            Preconditions.checkNotNull(packageList);
21200            List<String> removedFromList = null;
21201            synchronized (mPackages) {
21202                if (mKeepUninstalledPackages != null) {
21203                    final int packagesCount = mKeepUninstalledPackages.size();
21204                    for (int i = 0; i < packagesCount; i++) {
21205                        String oldPackage = mKeepUninstalledPackages.get(i);
21206                        if (packageList != null && packageList.contains(oldPackage)) {
21207                            continue;
21208                        }
21209                        if (removedFromList == null) {
21210                            removedFromList = new ArrayList<>();
21211                        }
21212                        removedFromList.add(oldPackage);
21213                    }
21214                }
21215                mKeepUninstalledPackages = new ArrayList<>(packageList);
21216                if (removedFromList != null) {
21217                    final int removedCount = removedFromList.size();
21218                    for (int i = 0; i < removedCount; i++) {
21219                        deletePackageIfUnusedLPr(removedFromList.get(i));
21220                    }
21221                }
21222            }
21223        }
21224
21225        @Override
21226        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21227            synchronized (mPackages) {
21228                // If we do not support permission review, done.
21229                if (!mPermissionReviewRequired) {
21230                    return false;
21231                }
21232
21233                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21234                if (packageSetting == null) {
21235                    return false;
21236                }
21237
21238                // Permission review applies only to apps not supporting the new permission model.
21239                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21240                    return false;
21241                }
21242
21243                // Legacy apps have the permission and get user consent on launch.
21244                PermissionsState permissionsState = packageSetting.getPermissionsState();
21245                return permissionsState.isPermissionReviewRequired(userId);
21246            }
21247        }
21248
21249        @Override
21250        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21251            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21252        }
21253
21254        @Override
21255        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21256                int userId) {
21257            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21258        }
21259
21260        @Override
21261        public void setDeviceAndProfileOwnerPackages(
21262                int deviceOwnerUserId, String deviceOwnerPackage,
21263                SparseArray<String> profileOwnerPackages) {
21264            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21265                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21266        }
21267
21268        @Override
21269        public boolean isPackageDataProtected(int userId, String packageName) {
21270            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21271        }
21272
21273        @Override
21274        public boolean isPackageEphemeral(int userId, String packageName) {
21275            synchronized (mPackages) {
21276                PackageParser.Package p = mPackages.get(packageName);
21277                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21278            }
21279        }
21280
21281        @Override
21282        public boolean wasPackageEverLaunched(String packageName, int userId) {
21283            synchronized (mPackages) {
21284                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21285            }
21286        }
21287
21288        @Override
21289        public void grantRuntimePermission(String packageName, String name, int userId,
21290                boolean overridePolicy) {
21291            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21292                    overridePolicy);
21293        }
21294
21295        @Override
21296        public void revokeRuntimePermission(String packageName, String name, int userId,
21297                boolean overridePolicy) {
21298            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21299                    overridePolicy);
21300        }
21301
21302        @Override
21303        public String getNameForUid(int uid) {
21304            return PackageManagerService.this.getNameForUid(uid);
21305        }
21306    }
21307
21308    @Override
21309    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21310        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21311        synchronized (mPackages) {
21312            final long identity = Binder.clearCallingIdentity();
21313            try {
21314                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21315                        packageNames, userId);
21316            } finally {
21317                Binder.restoreCallingIdentity(identity);
21318            }
21319        }
21320    }
21321
21322    private static void enforceSystemOrPhoneCaller(String tag) {
21323        int callingUid = Binder.getCallingUid();
21324        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21325            throw new SecurityException(
21326                    "Cannot call " + tag + " from UID " + callingUid);
21327        }
21328    }
21329
21330    boolean isHistoricalPackageUsageAvailable() {
21331        return mPackageUsage.isHistoricalPackageUsageAvailable();
21332    }
21333
21334    /**
21335     * Return a <b>copy</b> of the collection of packages known to the package manager.
21336     * @return A copy of the values of mPackages.
21337     */
21338    Collection<PackageParser.Package> getPackages() {
21339        synchronized (mPackages) {
21340            return new ArrayList<>(mPackages.values());
21341        }
21342    }
21343
21344    /**
21345     * Logs process start information (including base APK hash) to the security log.
21346     * @hide
21347     */
21348    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21349            String apkFile, int pid) {
21350        if (!SecurityLog.isLoggingEnabled()) {
21351            return;
21352        }
21353        Bundle data = new Bundle();
21354        data.putLong("startTimestamp", System.currentTimeMillis());
21355        data.putString("processName", processName);
21356        data.putInt("uid", uid);
21357        data.putString("seinfo", seinfo);
21358        data.putString("apkFile", apkFile);
21359        data.putInt("pid", pid);
21360        Message msg = mProcessLoggingHandler.obtainMessage(
21361                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21362        msg.setData(data);
21363        mProcessLoggingHandler.sendMessage(msg);
21364    }
21365
21366    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21367        return mCompilerStats.getPackageStats(pkgName);
21368    }
21369
21370    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21371        return getOrCreateCompilerPackageStats(pkg.packageName);
21372    }
21373
21374    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21375        return mCompilerStats.getOrCreatePackageStats(pkgName);
21376    }
21377
21378    public void deleteCompilerPackageStats(String pkgName) {
21379        mCompilerStats.deletePackageStats(pkgName);
21380    }
21381}
21382