PackageManagerService.java revision 99407db8ddb70141a9582b4d9f5d5012067748fe
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_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
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.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.security.KeyStore;
201import android.security.SystemKeyStore;
202import android.system.ErrnoException;
203import android.system.Os;
204import android.text.TextUtils;
205import android.text.format.DateUtils;
206import android.util.ArrayMap;
207import android.util.ArraySet;
208import android.util.AtomicFile;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedInputStream;
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.InputStream;
281import java.io.PrintWriter;
282import java.nio.charset.StandardCharsets;
283import java.security.DigestInputStream;
284import java.security.MessageDigest;
285import java.security.NoSuchAlgorithmException;
286import java.security.PublicKey;
287import java.security.cert.Certificate;
288import java.security.cert.CertificateEncodingException;
289import java.security.cert.CertificateException;
290import java.text.SimpleDateFormat;
291import java.util.ArrayList;
292import java.util.Arrays;
293import java.util.Collection;
294import java.util.Collections;
295import java.util.Comparator;
296import java.util.Date;
297import java.util.HashSet;
298import java.util.Iterator;
299import java.util.List;
300import java.util.Map;
301import java.util.Objects;
302import java.util.Set;
303import java.util.concurrent.CountDownLatch;
304import java.util.concurrent.TimeUnit;
305import java.util.concurrent.atomic.AtomicBoolean;
306import java.util.concurrent.atomic.AtomicInteger;
307import java.util.concurrent.atomic.AtomicLong;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = false;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370
371    private static final boolean DISABLE_EPHEMERAL_APPS = true;
372
373    private static final int RADIO_UID = Process.PHONE_UID;
374    private static final int LOG_UID = Process.LOG_UID;
375    private static final int NFC_UID = Process.NFC_UID;
376    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377    private static final int SHELL_UID = Process.SHELL_UID;
378
379    // Cap the size of permission trees that 3rd party apps can define
380    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382    // Suffix used during package installation when copying/moving
383    // package apks to install directory.
384    private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386    static final int SCAN_NO_DEX = 1<<1;
387    static final int SCAN_FORCE_DEX = 1<<2;
388    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389    static final int SCAN_NEW_INSTALL = 1<<4;
390    static final int SCAN_NO_PATHS = 1<<5;
391    static final int SCAN_UPDATE_TIME = 1<<6;
392    static final int SCAN_DEFER_DEX = 1<<7;
393    static final int SCAN_BOOTING = 1<<8;
394    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396    static final int SCAN_REPLACING = 1<<11;
397    static final int SCAN_REQUIRE_KNOWN = 1<<12;
398    static final int SCAN_MOVE = 1<<13;
399    static final int SCAN_INITIAL = 1<<14;
400    static final int SCAN_CHECK_ONLY = 1<<15;
401    static final int SCAN_DONT_KILL_APP = 1<<17;
402    static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404    static final int REMOVE_CHATTY = 1<<16;
405
406    private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408    /**
409     * Timeout (in milliseconds) after which the watchdog should declare that
410     * our handler thread is wedged.  The usual default for such things is one
411     * minute but we sometimes do very lengthy I/O operations on this thread,
412     * such as installing multi-gigabyte applications, so ours needs to be longer.
413     */
414    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416    /**
417     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419     * settings entry if available, otherwise we use the hardcoded default.  If it's been
420     * more than this long since the last fstrim, we force one during the boot sequence.
421     *
422     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423     * one gets run at the next available charging+idle time.  This final mandatory
424     * no-fstrim check kicks in only of the other scheduling criteria is never met.
425     */
426    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428    /**
429     * Whether verification is enabled by default.
430     */
431    private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433    /**
434     * The default maximum time to wait for the verification agent to return in
435     * milliseconds.
436     */
437    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439    /**
440     * The default response for package verification timeout.
441     *
442     * This can be either PackageManager.VERIFICATION_ALLOW or
443     * PackageManager.VERIFICATION_REJECT.
444     */
445    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447    static final String PLATFORM_PACKAGE_NAME = "android";
448
449    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452            DEFAULT_CONTAINER_PACKAGE,
453            "com.android.defcontainer.DefaultContainerService");
454
455    private static final String KILL_APP_REASON_GIDS_CHANGED =
456            "permission grant or revoke changed gids";
457
458    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459            "permissions revoked";
460
461    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    final ProtectedPackages mProtectedPackages = new ProtectedPackages();
626
627    boolean mRestoredSettings;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128
1129    private class PackageUsage {
1130        private static final int WRITE_INTERVAL
1131            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1132
1133        private final Object mFileLock = new Object();
1134        private final AtomicLong mLastWritten = new AtomicLong(0);
1135        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1136
1137        private boolean mIsHistoricalPackageUsageAvailable = true;
1138
1139        boolean isHistoricalPackageUsageAvailable() {
1140            return mIsHistoricalPackageUsageAvailable;
1141        }
1142
1143        void write(boolean force) {
1144            if (force) {
1145                writeInternal();
1146                return;
1147            }
1148            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1149                && !DEBUG_DEXOPT) {
1150                return;
1151            }
1152            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1153                new Thread("PackageUsage_DiskWriter") {
1154                    @Override
1155                    public void run() {
1156                        try {
1157                            writeInternal();
1158                        } finally {
1159                            mBackgroundWriteRunning.set(false);
1160                        }
1161                    }
1162                }.start();
1163            }
1164        }
1165
1166        private void writeInternal() {
1167            synchronized (mPackages) {
1168                synchronized (mFileLock) {
1169                    AtomicFile file = getFile();
1170                    FileOutputStream f = null;
1171                    try {
1172                        f = file.startWrite();
1173                        BufferedOutputStream out = new BufferedOutputStream(f);
1174                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1175                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1176                        StringBuilder sb = new StringBuilder();
1177
1178                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1179                        sb.append('\n');
1180                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1181
1182                        for (PackageParser.Package pkg : mPackages.values()) {
1183                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1184                                continue;
1185                            }
1186                            sb.setLength(0);
1187                            sb.append(pkg.packageName);
1188                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1189                                sb.append(' ');
1190                                sb.append(usageTimeInMillis);
1191                            }
1192                            sb.append('\n');
1193                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1194                        }
1195                        out.flush();
1196                        file.finishWrite(f);
1197                    } catch (IOException e) {
1198                        if (f != null) {
1199                            file.failWrite(f);
1200                        }
1201                        Log.e(TAG, "Failed to write package usage times", e);
1202                    }
1203                }
1204            }
1205            mLastWritten.set(SystemClock.elapsedRealtime());
1206        }
1207
1208        void readLP() {
1209            synchronized (mFileLock) {
1210                AtomicFile file = getFile();
1211                BufferedInputStream in = null;
1212                try {
1213                    in = new BufferedInputStream(file.openRead());
1214                    StringBuffer sb = new StringBuffer();
1215
1216                    String firstLine = readLine(in, sb);
1217                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1218                        readVersion1LP(in, sb);
1219                    } else {
1220                        readVersion0LP(in, sb, firstLine);
1221                    }
1222                } catch (FileNotFoundException expected) {
1223                    mIsHistoricalPackageUsageAvailable = false;
1224                } catch (IOException e) {
1225                    Log.w(TAG, "Failed to read package usage times", e);
1226                } finally {
1227                    IoUtils.closeQuietly(in);
1228                }
1229            }
1230            mLastWritten.set(SystemClock.elapsedRealtime());
1231        }
1232
1233        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1234                throws IOException {
1235            // Initial version of the file had no version number and stored one
1236            // package-timestamp pair per line.
1237            // Note that the first line has already been read from the InputStream.
1238            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1239                String[] tokens = line.split(" ");
1240                if (tokens.length != 2) {
1241                    throw new IOException("Failed to parse " + line +
1242                            " as package-timestamp pair.");
1243                }
1244
1245                String packageName = tokens[0];
1246                PackageParser.Package pkg = mPackages.get(packageName);
1247                if (pkg == null) {
1248                    continue;
1249                }
1250
1251                long timestamp = parseAsLong(tokens[1]);
1252                for (int reason = 0;
1253                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1254                        reason++) {
1255                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1256                }
1257            }
1258        }
1259
1260        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1261            // Version 1 of the file started with the corresponding version
1262            // number and then stored a package name and eight timestamps per line.
1263            String line;
1264            while ((line = readLine(in, sb)) != null) {
1265                String[] tokens = line.split(" ");
1266                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1267                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1268                }
1269
1270                String packageName = tokens[0];
1271                PackageParser.Package pkg = mPackages.get(packageName);
1272                if (pkg == null) {
1273                    continue;
1274                }
1275
1276                for (int reason = 0;
1277                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1278                        reason++) {
1279                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1280                }
1281            }
1282        }
1283
1284        private long parseAsLong(String token) throws IOException {
1285            try {
1286                return Long.parseLong(token);
1287            } catch (NumberFormatException e) {
1288                throw new IOException("Failed to parse " + token + " as a long.", e);
1289            }
1290        }
1291
1292        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1293            return readToken(in, sb, '\n');
1294        }
1295
1296        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1297                throws IOException {
1298            sb.setLength(0);
1299            while (true) {
1300                int ch = in.read();
1301                if (ch == -1) {
1302                    if (sb.length() == 0) {
1303                        return null;
1304                    }
1305                    throw new IOException("Unexpected EOF");
1306                }
1307                if (ch == endOfToken) {
1308                    return sb.toString();
1309                }
1310                sb.append((char)ch);
1311            }
1312        }
1313
1314        private AtomicFile getFile() {
1315            File dataDir = Environment.getDataDirectory();
1316            File systemDir = new File(dataDir, "system");
1317            File fname = new File(systemDir, "package-usage.list");
1318            return new AtomicFile(fname);
1319        }
1320
1321        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1322        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1323    }
1324
1325    class PackageHandler extends Handler {
1326        private boolean mBound = false;
1327        final ArrayList<HandlerParams> mPendingInstalls =
1328            new ArrayList<HandlerParams>();
1329
1330        private boolean connectToService() {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1332                    " DefaultContainerService");
1333            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1334            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1335            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1336                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1337                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1338                mBound = true;
1339                return true;
1340            }
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1342            return false;
1343        }
1344
1345        private void disconnectService() {
1346            mContainerService = null;
1347            mBound = false;
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1349            mContext.unbindService(mDefContainerConn);
1350            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351        }
1352
1353        PackageHandler(Looper looper) {
1354            super(looper);
1355        }
1356
1357        public void handleMessage(Message msg) {
1358            try {
1359                doHandleMessage(msg);
1360            } finally {
1361                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1362            }
1363        }
1364
1365        void doHandleMessage(Message msg) {
1366            switch (msg.what) {
1367                case INIT_COPY: {
1368                    HandlerParams params = (HandlerParams) msg.obj;
1369                    int idx = mPendingInstalls.size();
1370                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1371                    // If a bind was already initiated we dont really
1372                    // need to do anything. The pending install
1373                    // will be processed later on.
1374                    if (!mBound) {
1375                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1376                                System.identityHashCode(mHandler));
1377                        // If this is the only one pending we might
1378                        // have to bind to the service again.
1379                        if (!connectToService()) {
1380                            Slog.e(TAG, "Failed to bind to media container service");
1381                            params.serviceError();
1382                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1383                                    System.identityHashCode(mHandler));
1384                            if (params.traceMethod != null) {
1385                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1386                                        params.traceCookie);
1387                            }
1388                            return;
1389                        } else {
1390                            // Once we bind to the service, the first
1391                            // pending request will be processed.
1392                            mPendingInstalls.add(idx, params);
1393                        }
1394                    } else {
1395                        mPendingInstalls.add(idx, params);
1396                        // Already bound to the service. Just make
1397                        // sure we trigger off processing the first request.
1398                        if (idx == 0) {
1399                            mHandler.sendEmptyMessage(MCS_BOUND);
1400                        }
1401                    }
1402                    break;
1403                }
1404                case MCS_BOUND: {
1405                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1406                    if (msg.obj != null) {
1407                        mContainerService = (IMediaContainerService) msg.obj;
1408                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1409                                System.identityHashCode(mHandler));
1410                    }
1411                    if (mContainerService == null) {
1412                        if (!mBound) {
1413                            // Something seriously wrong since we are not bound and we are not
1414                            // waiting for connection. Bail out.
1415                            Slog.e(TAG, "Cannot bind to media container service");
1416                            for (HandlerParams params : mPendingInstalls) {
1417                                // Indicate service bind error
1418                                params.serviceError();
1419                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                                        System.identityHashCode(params));
1421                                if (params.traceMethod != null) {
1422                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1423                                            params.traceMethod, params.traceCookie);
1424                                }
1425                                return;
1426                            }
1427                            mPendingInstalls.clear();
1428                        } else {
1429                            Slog.w(TAG, "Waiting to connect to media container service");
1430                        }
1431                    } else if (mPendingInstalls.size() > 0) {
1432                        HandlerParams params = mPendingInstalls.get(0);
1433                        if (params != null) {
1434                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1435                                    System.identityHashCode(params));
1436                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1437                            if (params.startCopy()) {
1438                                // We are done...  look for more work or to
1439                                // go idle.
1440                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1441                                        "Checking for more work or unbind...");
1442                                // Delete pending install
1443                                if (mPendingInstalls.size() > 0) {
1444                                    mPendingInstalls.remove(0);
1445                                }
1446                                if (mPendingInstalls.size() == 0) {
1447                                    if (mBound) {
1448                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1449                                                "Posting delayed MCS_UNBIND");
1450                                        removeMessages(MCS_UNBIND);
1451                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1452                                        // Unbind after a little delay, to avoid
1453                                        // continual thrashing.
1454                                        sendMessageDelayed(ubmsg, 10000);
1455                                    }
1456                                } else {
1457                                    // There are more pending requests in queue.
1458                                    // Just post MCS_BOUND message to trigger processing
1459                                    // of next pending install.
1460                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1461                                            "Posting MCS_BOUND for next work");
1462                                    mHandler.sendEmptyMessage(MCS_BOUND);
1463                                }
1464                            }
1465                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1466                        }
1467                    } else {
1468                        // Should never happen ideally.
1469                        Slog.w(TAG, "Empty queue");
1470                    }
1471                    break;
1472                }
1473                case MCS_RECONNECT: {
1474                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1475                    if (mPendingInstalls.size() > 0) {
1476                        if (mBound) {
1477                            disconnectService();
1478                        }
1479                        if (!connectToService()) {
1480                            Slog.e(TAG, "Failed to bind to media container service");
1481                            for (HandlerParams params : mPendingInstalls) {
1482                                // Indicate service bind error
1483                                params.serviceError();
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                        System.identityHashCode(params));
1486                            }
1487                            mPendingInstalls.clear();
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_UNBIND: {
1493                    // If there is no actual work left, then time to unbind.
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1495
1496                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1497                        if (mBound) {
1498                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1499
1500                            disconnectService();
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        // There are more pending requests in queue.
1504                        // Just post MCS_BOUND message to trigger processing
1505                        // of next pending install.
1506                        mHandler.sendEmptyMessage(MCS_BOUND);
1507                    }
1508
1509                    break;
1510                }
1511                case MCS_GIVE_UP: {
1512                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1513                    HandlerParams params = mPendingInstalls.remove(0);
1514                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1515                            System.identityHashCode(params));
1516                    break;
1517                }
1518                case SEND_PENDING_BROADCAST: {
1519                    String packages[];
1520                    ArrayList<String> components[];
1521                    int size = 0;
1522                    int uids[];
1523                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1524                    synchronized (mPackages) {
1525                        if (mPendingBroadcasts == null) {
1526                            return;
1527                        }
1528                        size = mPendingBroadcasts.size();
1529                        if (size <= 0) {
1530                            // Nothing to be done. Just return
1531                            return;
1532                        }
1533                        packages = new String[size];
1534                        components = new ArrayList[size];
1535                        uids = new int[size];
1536                        int i = 0;  // filling out the above arrays
1537
1538                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1539                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1540                            Iterator<Map.Entry<String, ArrayList<String>>> it
1541                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1542                                            .entrySet().iterator();
1543                            while (it.hasNext() && i < size) {
1544                                Map.Entry<String, ArrayList<String>> ent = it.next();
1545                                packages[i] = ent.getKey();
1546                                components[i] = ent.getValue();
1547                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1548                                uids[i] = (ps != null)
1549                                        ? UserHandle.getUid(packageUserId, ps.appId)
1550                                        : -1;
1551                                i++;
1552                            }
1553                        }
1554                        size = i;
1555                        mPendingBroadcasts.clear();
1556                    }
1557                    // Send broadcasts
1558                    for (int i = 0; i < size; i++) {
1559                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                    break;
1563                }
1564                case START_CLEANING_PACKAGE: {
1565                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1566                    final String packageName = (String)msg.obj;
1567                    final int userId = msg.arg1;
1568                    final boolean andCode = msg.arg2 != 0;
1569                    synchronized (mPackages) {
1570                        if (userId == UserHandle.USER_ALL) {
1571                            int[] users = sUserManager.getUserIds();
1572                            for (int user : users) {
1573                                mSettings.addPackageToCleanLPw(
1574                                        new PackageCleanItem(user, packageName, andCode));
1575                            }
1576                        } else {
1577                            mSettings.addPackageToCleanLPw(
1578                                    new PackageCleanItem(userId, packageName, andCode));
1579                        }
1580                    }
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1582                    startCleaningPackages();
1583                } break;
1584                case POST_INSTALL: {
1585                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1586
1587                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1588                    final boolean didRestore = (msg.arg2 != 0);
1589                    mRunningInstalls.delete(msg.arg1);
1590
1591                    if (data != null) {
1592                        InstallArgs args = data.args;
1593                        PackageInstalledInfo parentRes = data.res;
1594
1595                        final boolean grantPermissions = (args.installFlags
1596                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1597                        final boolean killApp = (args.installFlags
1598                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1599                        final String[] grantedPermissions = args.installGrantPermissions;
1600
1601                        // Handle the parent package
1602                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1603                                grantedPermissions, didRestore, args.installerPackageName,
1604                                args.observer);
1605
1606                        // Handle the child packages
1607                        final int childCount = (parentRes.addedChildPackages != null)
1608                                ? parentRes.addedChildPackages.size() : 0;
1609                        for (int i = 0; i < childCount; i++) {
1610                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1611                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1612                                    grantedPermissions, false, args.installerPackageName,
1613                                    args.observer);
1614                        }
1615
1616                        // Log tracing if needed
1617                        if (args.traceMethod != null) {
1618                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1619                                    args.traceCookie);
1620                        }
1621                    } else {
1622                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1623                    }
1624
1625                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1626                } break;
1627                case UPDATED_MEDIA_STATUS: {
1628                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1629                    boolean reportStatus = msg.arg1 == 1;
1630                    boolean doGc = msg.arg2 == 1;
1631                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1632                    if (doGc) {
1633                        // Force a gc to clear up stale containers.
1634                        Runtime.getRuntime().gc();
1635                    }
1636                    if (msg.obj != null) {
1637                        @SuppressWarnings("unchecked")
1638                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1639                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1640                        // Unload containers
1641                        unloadAllContainers(args);
1642                    }
1643                    if (reportStatus) {
1644                        try {
1645                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1646                            PackageHelper.getMountService().finishMediaUpdate();
1647                        } catch (RemoteException e) {
1648                            Log.e(TAG, "MountService not running?");
1649                        }
1650                    }
1651                } break;
1652                case WRITE_SETTINGS: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    synchronized (mPackages) {
1655                        removeMessages(WRITE_SETTINGS);
1656                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1657                        mSettings.writeLPr();
1658                        mDirtyUsers.clear();
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                } break;
1662                case WRITE_PACKAGE_RESTRICTIONS: {
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1664                    synchronized (mPackages) {
1665                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1666                        for (int userId : mDirtyUsers) {
1667                            mSettings.writePackageRestrictionsLPr(userId);
1668                        }
1669                        mDirtyUsers.clear();
1670                    }
1671                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1672                } break;
1673                case WRITE_PACKAGE_LIST: {
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1675                    synchronized (mPackages) {
1676                        removeMessages(WRITE_PACKAGE_LIST);
1677                        mSettings.writePackageListLPr(msg.arg1);
1678                    }
1679                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1680                } break;
1681                case CHECK_PENDING_VERIFICATION: {
1682                    final int verificationId = msg.arg1;
1683                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1684
1685                    if ((state != null) && !state.timeoutExtended()) {
1686                        final InstallArgs args = state.getInstallArgs();
1687                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1688
1689                        Slog.i(TAG, "Verification timed out for " + originUri);
1690                        mPendingVerification.remove(verificationId);
1691
1692                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1693
1694                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1695                            Slog.i(TAG, "Continuing with installation of " + originUri);
1696                            state.setVerifierResponse(Binder.getCallingUid(),
1697                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1698                            broadcastPackageVerified(verificationId, originUri,
1699                                    PackageManager.VERIFICATION_ALLOW,
1700                                    state.getInstallArgs().getUser());
1701                            try {
1702                                ret = args.copyApk(mContainerService, true);
1703                            } catch (RemoteException e) {
1704                                Slog.e(TAG, "Could not contact the ContainerService");
1705                            }
1706                        } else {
1707                            broadcastPackageVerified(verificationId, originUri,
1708                                    PackageManager.VERIFICATION_REJECT,
1709                                    state.getInstallArgs().getUser());
1710                        }
1711
1712                        Trace.asyncTraceEnd(
1713                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1714
1715                        processPendingInstall(args, ret);
1716                        mHandler.sendEmptyMessage(MCS_UNBIND);
1717                    }
1718                    break;
1719                }
1720                case PACKAGE_VERIFIED: {
1721                    final int verificationId = msg.arg1;
1722
1723                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1724                    if (state == null) {
1725                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1726                        break;
1727                    }
1728
1729                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1730
1731                    state.setVerifierResponse(response.callerUid, response.code);
1732
1733                    if (state.isVerificationComplete()) {
1734                        mPendingVerification.remove(verificationId);
1735
1736                        final InstallArgs args = state.getInstallArgs();
1737                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1738
1739                        int ret;
1740                        if (state.isInstallAllowed()) {
1741                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1742                            broadcastPackageVerified(verificationId, originUri,
1743                                    response.code, state.getInstallArgs().getUser());
1744                            try {
1745                                ret = args.copyApk(mContainerService, true);
1746                            } catch (RemoteException e) {
1747                                Slog.e(TAG, "Could not contact the ContainerService");
1748                            }
1749                        } else {
1750                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1751                        }
1752
1753                        Trace.asyncTraceEnd(
1754                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1755
1756                        processPendingInstall(args, ret);
1757                        mHandler.sendEmptyMessage(MCS_UNBIND);
1758                    }
1759
1760                    break;
1761                }
1762                case START_INTENT_FILTER_VERIFICATIONS: {
1763                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1764                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1765                            params.replacing, params.pkg);
1766                    break;
1767                }
1768                case INTENT_FILTER_VERIFIED: {
1769                    final int verificationId = msg.arg1;
1770
1771                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1772                            verificationId);
1773                    if (state == null) {
1774                        Slog.w(TAG, "Invalid IntentFilter verification token "
1775                                + verificationId + " received");
1776                        break;
1777                    }
1778
1779                    final int userId = state.getUserId();
1780
1781                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1782                            "Processing IntentFilter verification with token:"
1783                            + verificationId + " and userId:" + userId);
1784
1785                    final IntentFilterVerificationResponse response =
1786                            (IntentFilterVerificationResponse) msg.obj;
1787
1788                    state.setVerifierResponse(response.callerUid, response.code);
1789
1790                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1791                            "IntentFilter verification with token:" + verificationId
1792                            + " and userId:" + userId
1793                            + " is settings verifier response with response code:"
1794                            + response.code);
1795
1796                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1797                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1798                                + response.getFailedDomainsString());
1799                    }
1800
1801                    if (state.isVerificationComplete()) {
1802                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1803                    } else {
1804                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1805                                "IntentFilter verification with token:" + verificationId
1806                                + " was not said to be complete");
1807                    }
1808
1809                    break;
1810                }
1811            }
1812        }
1813    }
1814
1815    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1816            boolean killApp, String[] grantedPermissions,
1817            boolean launchedForRestore, String installerPackage,
1818            IPackageInstallObserver2 installObserver) {
1819        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1820            // Send the removed broadcasts
1821            if (res.removedInfo != null) {
1822                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1823            }
1824
1825            // Now that we successfully installed the package, grant runtime
1826            // permissions if requested before broadcasting the install.
1827            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1828                    >= Build.VERSION_CODES.M) {
1829                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1830            }
1831
1832            final boolean update = res.removedInfo != null
1833                    && res.removedInfo.removedPackage != null;
1834
1835            // If this is the first time we have child packages for a disabled privileged
1836            // app that had no children, we grant requested runtime permissions to the new
1837            // children if the parent on the system image had them already granted.
1838            if (res.pkg.parentPackage != null) {
1839                synchronized (mPackages) {
1840                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1841                }
1842            }
1843
1844            synchronized (mPackages) {
1845                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1846            }
1847
1848            final String packageName = res.pkg.applicationInfo.packageName;
1849            Bundle extras = new Bundle(1);
1850            extras.putInt(Intent.EXTRA_UID, res.uid);
1851
1852            // Determine the set of users who are adding this package for
1853            // the first time vs. those who are seeing an update.
1854            int[] firstUsers = EMPTY_INT_ARRAY;
1855            int[] updateUsers = EMPTY_INT_ARRAY;
1856            if (res.origUsers == null || res.origUsers.length == 0) {
1857                firstUsers = res.newUsers;
1858            } else {
1859                for (int newUser : res.newUsers) {
1860                    boolean isNew = true;
1861                    for (int origUser : res.origUsers) {
1862                        if (origUser == newUser) {
1863                            isNew = false;
1864                            break;
1865                        }
1866                    }
1867                    if (isNew) {
1868                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1869                    } else {
1870                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1871                    }
1872                }
1873            }
1874
1875            // Send installed broadcasts if the install/update is not ephemeral
1876            if (!isEphemeral(res.pkg)) {
1877                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1878
1879                // Send added for users that see the package for the first time
1880                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1881                        extras, 0 /*flags*/, null /*targetPackage*/,
1882                        null /*finishedReceiver*/, firstUsers);
1883
1884                // Send added for users that don't see the package for the first time
1885                if (update) {
1886                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1887                }
1888                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1889                        extras, 0 /*flags*/, null /*targetPackage*/,
1890                        null /*finishedReceiver*/, updateUsers);
1891
1892                // Send replaced for users that don't see the package for the first time
1893                if (update) {
1894                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1895                            packageName, extras, 0 /*flags*/,
1896                            null /*targetPackage*/, null /*finishedReceiver*/,
1897                            updateUsers);
1898                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1899                            null /*package*/, null /*extras*/, 0 /*flags*/,
1900                            packageName /*targetPackage*/,
1901                            null /*finishedReceiver*/, updateUsers);
1902                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1903                    // First-install and we did a restore, so we're responsible for the
1904                    // first-launch broadcast.
1905                    if (DEBUG_BACKUP) {
1906                        Slog.i(TAG, "Post-restore of " + packageName
1907                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1908                    }
1909                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1910                }
1911
1912                // Send broadcast package appeared if forward locked/external for all users
1913                // treat asec-hosted packages like removable media on upgrade
1914                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1915                    if (DEBUG_INSTALL) {
1916                        Slog.i(TAG, "upgrading pkg " + res.pkg
1917                                + " is ASEC-hosted -> AVAILABLE");
1918                    }
1919                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1920                    ArrayList<String> pkgList = new ArrayList<>(1);
1921                    pkgList.add(packageName);
1922                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1923                }
1924            }
1925
1926            // Work that needs to happen on first install within each user
1927            if (firstUsers != null && firstUsers.length > 0) {
1928                synchronized (mPackages) {
1929                    for (int userId : firstUsers) {
1930                        // If this app is a browser and it's newly-installed for some
1931                        // users, clear any default-browser state in those users. The
1932                        // app's nature doesn't depend on the user, so we can just check
1933                        // its browser nature in any user and generalize.
1934                        if (packageIsBrowser(packageName, userId)) {
1935                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1936                        }
1937
1938                        // We may also need to apply pending (restored) runtime
1939                        // permission grants within these users.
1940                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1941                    }
1942                }
1943            }
1944
1945            // Log current value of "unknown sources" setting
1946            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1947                    getUnknownSourcesSettings());
1948
1949            // Force a gc to clear up things
1950            Runtime.getRuntime().gc();
1951
1952            // Remove the replaced package's older resources safely now
1953            // We delete after a gc for applications  on sdcard.
1954            if (res.removedInfo != null && res.removedInfo.args != null) {
1955                synchronized (mInstallLock) {
1956                    res.removedInfo.args.doPostDeleteLI(true);
1957                }
1958            }
1959        }
1960
1961        // If someone is watching installs - notify them
1962        if (installObserver != null) {
1963            try {
1964                Bundle extras = extrasForInstallResult(res);
1965                installObserver.onPackageInstalled(res.name, res.returnCode,
1966                        res.returnMsg, extras);
1967            } catch (RemoteException e) {
1968                Slog.i(TAG, "Observer no longer exists.");
1969            }
1970        }
1971    }
1972
1973    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1974            PackageParser.Package pkg) {
1975        if (pkg.parentPackage == null) {
1976            return;
1977        }
1978        if (pkg.requestedPermissions == null) {
1979            return;
1980        }
1981        final PackageSetting disabledSysParentPs = mSettings
1982                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1983        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1984                || !disabledSysParentPs.isPrivileged()
1985                || (disabledSysParentPs.childPackageNames != null
1986                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1987            return;
1988        }
1989        final int[] allUserIds = sUserManager.getUserIds();
1990        final int permCount = pkg.requestedPermissions.size();
1991        for (int i = 0; i < permCount; i++) {
1992            String permission = pkg.requestedPermissions.get(i);
1993            BasePermission bp = mSettings.mPermissions.get(permission);
1994            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1995                continue;
1996            }
1997            for (int userId : allUserIds) {
1998                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1999                        permission, userId)) {
2000                    grantRuntimePermission(pkg.packageName, permission, userId);
2001                }
2002            }
2003        }
2004    }
2005
2006    private StorageEventListener mStorageListener = new StorageEventListener() {
2007        @Override
2008        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2009            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2010                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2011                    final String volumeUuid = vol.getFsUuid();
2012
2013                    // Clean up any users or apps that were removed or recreated
2014                    // while this volume was missing
2015                    reconcileUsers(volumeUuid);
2016                    reconcileApps(volumeUuid);
2017
2018                    // Clean up any install sessions that expired or were
2019                    // cancelled while this volume was missing
2020                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2021
2022                    loadPrivatePackages(vol);
2023
2024                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2025                    unloadPrivatePackages(vol);
2026                }
2027            }
2028
2029            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2030                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2031                    updateExternalMediaStatus(true, false);
2032                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2033                    updateExternalMediaStatus(false, false);
2034                }
2035            }
2036        }
2037
2038        @Override
2039        public void onVolumeForgotten(String fsUuid) {
2040            if (TextUtils.isEmpty(fsUuid)) {
2041                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2042                return;
2043            }
2044
2045            // Remove any apps installed on the forgotten volume
2046            synchronized (mPackages) {
2047                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2048                for (PackageSetting ps : packages) {
2049                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2050                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2051                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2052                }
2053
2054                mSettings.onVolumeForgotten(fsUuid);
2055                mSettings.writeLPr();
2056            }
2057        }
2058    };
2059
2060    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2061            String[] grantedPermissions) {
2062        for (int userId : userIds) {
2063            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2064        }
2065
2066        // We could have touched GID membership, so flush out packages.list
2067        synchronized (mPackages) {
2068            mSettings.writePackageListLPr();
2069        }
2070    }
2071
2072    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2073            String[] grantedPermissions) {
2074        SettingBase sb = (SettingBase) pkg.mExtras;
2075        if (sb == null) {
2076            return;
2077        }
2078
2079        PermissionsState permissionsState = sb.getPermissionsState();
2080
2081        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2082                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2083
2084        for (String permission : pkg.requestedPermissions) {
2085            final BasePermission bp;
2086            synchronized (mPackages) {
2087                bp = mSettings.mPermissions.get(permission);
2088            }
2089            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2090                    && (grantedPermissions == null
2091                           || ArrayUtils.contains(grantedPermissions, permission))) {
2092                final int flags = permissionsState.getPermissionFlags(permission, userId);
2093                // Installer cannot change immutable permissions.
2094                if ((flags & immutableFlags) == 0) {
2095                    grantRuntimePermission(pkg.packageName, permission, userId);
2096                }
2097            }
2098        }
2099    }
2100
2101    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2102        Bundle extras = null;
2103        switch (res.returnCode) {
2104            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2105                extras = new Bundle();
2106                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2107                        res.origPermission);
2108                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2109                        res.origPackage);
2110                break;
2111            }
2112            case PackageManager.INSTALL_SUCCEEDED: {
2113                extras = new Bundle();
2114                extras.putBoolean(Intent.EXTRA_REPLACING,
2115                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2116                break;
2117            }
2118        }
2119        return extras;
2120    }
2121
2122    void scheduleWriteSettingsLocked() {
2123        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2124            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2125        }
2126    }
2127
2128    void scheduleWritePackageListLocked(int userId) {
2129        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2130            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2131            msg.arg1 = userId;
2132            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2133        }
2134    }
2135
2136    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2137        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2138        scheduleWritePackageRestrictionsLocked(userId);
2139    }
2140
2141    void scheduleWritePackageRestrictionsLocked(int userId) {
2142        final int[] userIds = (userId == UserHandle.USER_ALL)
2143                ? sUserManager.getUserIds() : new int[]{userId};
2144        for (int nextUserId : userIds) {
2145            if (!sUserManager.exists(nextUserId)) return;
2146            mDirtyUsers.add(nextUserId);
2147            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2148                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2149            }
2150        }
2151    }
2152
2153    public static PackageManagerService main(Context context, Installer installer,
2154            boolean factoryTest, boolean onlyCore) {
2155        // Self-check for initial settings.
2156        PackageManagerServiceCompilerMapping.checkProperties();
2157
2158        PackageManagerService m = new PackageManagerService(context, installer,
2159                factoryTest, onlyCore);
2160        m.enableSystemUserPackages();
2161        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2162        // disabled after already being started.
2163        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2164                UserHandle.USER_SYSTEM);
2165        ServiceManager.addService("package", m);
2166        return m;
2167    }
2168
2169    private void enableSystemUserPackages() {
2170        if (!UserManager.isSplitSystemUser()) {
2171            return;
2172        }
2173        // For system user, enable apps based on the following conditions:
2174        // - app is whitelisted or belong to one of these groups:
2175        //   -- system app which has no launcher icons
2176        //   -- system app which has INTERACT_ACROSS_USERS permission
2177        //   -- system IME app
2178        // - app is not in the blacklist
2179        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2180        Set<String> enableApps = new ArraySet<>();
2181        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2182                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2183                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2184        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2185        enableApps.addAll(wlApps);
2186        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2187                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2188        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2189        enableApps.removeAll(blApps);
2190        Log.i(TAG, "Applications installed for system user: " + enableApps);
2191        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2192                UserHandle.SYSTEM);
2193        final int allAppsSize = allAps.size();
2194        synchronized (mPackages) {
2195            for (int i = 0; i < allAppsSize; i++) {
2196                String pName = allAps.get(i);
2197                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2198                // Should not happen, but we shouldn't be failing if it does
2199                if (pkgSetting == null) {
2200                    continue;
2201                }
2202                boolean install = enableApps.contains(pName);
2203                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2204                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2205                            + " for system user");
2206                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2207                }
2208            }
2209        }
2210    }
2211
2212    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2213        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2214                Context.DISPLAY_SERVICE);
2215        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2216    }
2217
2218    public PackageManagerService(Context context, Installer installer,
2219            boolean factoryTest, boolean onlyCore) {
2220        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2221                SystemClock.uptimeMillis());
2222
2223        if (mSdkVersion <= 0) {
2224            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2225        }
2226
2227        mContext = context;
2228        mFactoryTest = factoryTest;
2229        mOnlyCore = onlyCore;
2230        mMetrics = new DisplayMetrics();
2231        mSettings = new Settings(mPackages);
2232        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2233                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2234        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244
2245        String separateProcesses = SystemProperties.get("debug.separate_processes");
2246        if (separateProcesses != null && separateProcesses.length() > 0) {
2247            if ("*".equals(separateProcesses)) {
2248                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2249                mSeparateProcesses = null;
2250                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2251            } else {
2252                mDefParseFlags = 0;
2253                mSeparateProcesses = separateProcesses.split(",");
2254                Slog.w(TAG, "Running with debug.separate_processes: "
2255                        + separateProcesses);
2256            }
2257        } else {
2258            mDefParseFlags = 0;
2259            mSeparateProcesses = null;
2260        }
2261
2262        mInstaller = installer;
2263        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2264                "*dexopt*");
2265        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2266
2267        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2268                FgThread.get().getLooper());
2269
2270        getDefaultDisplayMetrics(context, mMetrics);
2271
2272        SystemConfig systemConfig = SystemConfig.getInstance();
2273        mGlobalGids = systemConfig.getGlobalGids();
2274        mSystemPermissions = systemConfig.getSystemPermissions();
2275        mAvailableFeatures = systemConfig.getAvailableFeatures();
2276
2277        synchronized (mInstallLock) {
2278        // writer
2279        synchronized (mPackages) {
2280            mHandlerThread = new ServiceThread(TAG,
2281                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2282            mHandlerThread.start();
2283            mHandler = new PackageHandler(mHandlerThread.getLooper());
2284            mProcessLoggingHandler = new ProcessLoggingHandler();
2285            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2286
2287            File dataDir = Environment.getDataDirectory();
2288            mAppInstallDir = new File(dataDir, "app");
2289            mAppLib32InstallDir = new File(dataDir, "app-lib");
2290            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2291            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2292            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2293
2294            sUserManager = new UserManagerService(context, this, mPackages);
2295
2296            // Propagate permission configuration in to package manager.
2297            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2298                    = systemConfig.getPermissions();
2299            for (int i=0; i<permConfig.size(); i++) {
2300                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2301                BasePermission bp = mSettings.mPermissions.get(perm.name);
2302                if (bp == null) {
2303                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2304                    mSettings.mPermissions.put(perm.name, bp);
2305                }
2306                if (perm.gids != null) {
2307                    bp.setGids(perm.gids, perm.perUser);
2308                }
2309            }
2310
2311            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2312            for (int i=0; i<libConfig.size(); i++) {
2313                mSharedLibraries.put(libConfig.keyAt(i),
2314                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2315            }
2316
2317            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2318
2319            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2320
2321            String customResolverActivity = Resources.getSystem().getString(
2322                    R.string.config_customResolverActivity);
2323            if (TextUtils.isEmpty(customResolverActivity)) {
2324                customResolverActivity = null;
2325            } else {
2326                mCustomResolverComponentName = ComponentName.unflattenFromString(
2327                        customResolverActivity);
2328            }
2329
2330            long startTime = SystemClock.uptimeMillis();
2331
2332            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2333                    startTime);
2334
2335            // Set flag to monitor and not change apk file paths when
2336            // scanning install directories.
2337            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2338
2339            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2340            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2341
2342            if (bootClassPath == null) {
2343                Slog.w(TAG, "No BOOTCLASSPATH found!");
2344            }
2345
2346            if (systemServerClassPath == null) {
2347                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2348            }
2349
2350            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2351            final String[] dexCodeInstructionSets =
2352                    getDexCodeInstructionSets(
2353                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2354
2355            /**
2356             * Ensure all external libraries have had dexopt run on them.
2357             */
2358            if (mSharedLibraries.size() > 0) {
2359                // NOTE: For now, we're compiling these system "shared libraries"
2360                // (and framework jars) into all available architectures. It's possible
2361                // to compile them only when we come across an app that uses them (there's
2362                // already logic for that in scanPackageLI) but that adds some complexity.
2363                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2364                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2365                        final String lib = libEntry.path;
2366                        if (lib == null) {
2367                            continue;
2368                        }
2369
2370                        try {
2371                            // Shared libraries do not have profiles so we perform a full
2372                            // AOT compilation (if needed).
2373                            int dexoptNeeded = DexFile.getDexOptNeeded(
2374                                    lib, dexCodeInstructionSet,
2375                                    getCompilerFilterForReason(REASON_SHARED_APK),
2376                                    false /* newProfile */);
2377                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2378                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2379                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2380                                        getCompilerFilterForReason(REASON_SHARED_APK),
2381                                        StorageManager.UUID_PRIVATE_INTERNAL,
2382                                        SKIP_SHARED_LIBRARY_CHECK);
2383                            }
2384                        } catch (FileNotFoundException e) {
2385                            Slog.w(TAG, "Library not found: " + lib);
2386                        } catch (IOException | InstallerException e) {
2387                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2388                                    + e.getMessage());
2389                        }
2390                    }
2391                }
2392            }
2393
2394            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2395
2396            final VersionInfo ver = mSettings.getInternalVersion();
2397            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2398
2399            // when upgrading from pre-M, promote system app permissions from install to runtime
2400            mPromoteSystemApps =
2401                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2402
2403            // When upgrading from pre-N, we need to handle package extraction like first boot,
2404            // as there is no profiling data available.
2405            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2406
2407            // save off the names of pre-existing system packages prior to scanning; we don't
2408            // want to automatically grant runtime permissions for new system apps
2409            if (mPromoteSystemApps) {
2410                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2411                while (pkgSettingIter.hasNext()) {
2412                    PackageSetting ps = pkgSettingIter.next();
2413                    if (isSystemApp(ps)) {
2414                        mExistingSystemPackages.add(ps.name);
2415                    }
2416                }
2417            }
2418
2419            // Collect vendor overlay packages.
2420            // (Do this before scanning any apps.)
2421            // For security and version matching reason, only consider
2422            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2423            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2424            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2425                    | PackageParser.PARSE_IS_SYSTEM
2426                    | PackageParser.PARSE_IS_SYSTEM_DIR
2427                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2428
2429            // Find base frameworks (resource packages without code).
2430            scanDirTracedLI(frameworkDir, mDefParseFlags
2431                    | PackageParser.PARSE_IS_SYSTEM
2432                    | PackageParser.PARSE_IS_SYSTEM_DIR
2433                    | PackageParser.PARSE_IS_PRIVILEGED,
2434                    scanFlags | SCAN_NO_DEX, 0);
2435
2436            // Collected privileged system packages.
2437            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2438            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2439                    | PackageParser.PARSE_IS_SYSTEM
2440                    | PackageParser.PARSE_IS_SYSTEM_DIR
2441                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2442
2443            // Collect ordinary system packages.
2444            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2445            scanDirTracedLI(systemAppDir, mDefParseFlags
2446                    | PackageParser.PARSE_IS_SYSTEM
2447                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2448
2449            // Collect all vendor packages.
2450            File vendorAppDir = new File("/vendor/app");
2451            try {
2452                vendorAppDir = vendorAppDir.getCanonicalFile();
2453            } catch (IOException e) {
2454                // failed to look up canonical path, continue with original one
2455            }
2456            scanDirTracedLI(vendorAppDir, mDefParseFlags
2457                    | PackageParser.PARSE_IS_SYSTEM
2458                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2459
2460            // Collect all OEM packages.
2461            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2462            scanDirTracedLI(oemAppDir, mDefParseFlags
2463                    | PackageParser.PARSE_IS_SYSTEM
2464                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2465
2466            // Prune any system packages that no longer exist.
2467            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2468            if (!mOnlyCore) {
2469                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2470                while (psit.hasNext()) {
2471                    PackageSetting ps = psit.next();
2472
2473                    /*
2474                     * If this is not a system app, it can't be a
2475                     * disable system app.
2476                     */
2477                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2478                        continue;
2479                    }
2480
2481                    /*
2482                     * If the package is scanned, it's not erased.
2483                     */
2484                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2485                    if (scannedPkg != null) {
2486                        /*
2487                         * If the system app is both scanned and in the
2488                         * disabled packages list, then it must have been
2489                         * added via OTA. Remove it from the currently
2490                         * scanned package so the previously user-installed
2491                         * application can be scanned.
2492                         */
2493                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2494                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2495                                    + ps.name + "; removing system app.  Last known codePath="
2496                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2497                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2498                                    + scannedPkg.mVersionCode);
2499                            removePackageLI(scannedPkg, true);
2500                            mExpectingBetter.put(ps.name, ps.codePath);
2501                        }
2502
2503                        continue;
2504                    }
2505
2506                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2507                        psit.remove();
2508                        logCriticalInfo(Log.WARN, "System package " + ps.name
2509                                + " no longer exists; it's data will be wiped");
2510                        // Actual deletion of code and data will be handled by later
2511                        // reconciliation step
2512                    } else {
2513                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2514                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2515                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2516                        }
2517                    }
2518                }
2519            }
2520
2521            //look for any incomplete package installations
2522            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2523            for (int i = 0; i < deletePkgsList.size(); i++) {
2524                // Actual deletion of code and data will be handled by later
2525                // reconciliation step
2526                final String packageName = deletePkgsList.get(i).name;
2527                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2528                synchronized (mPackages) {
2529                    mSettings.removePackageLPw(packageName);
2530                }
2531            }
2532
2533            //delete tmp files
2534            deleteTempPackageFiles();
2535
2536            // Remove any shared userIDs that have no associated packages
2537            mSettings.pruneSharedUsersLPw();
2538
2539            if (!mOnlyCore) {
2540                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2541                        SystemClock.uptimeMillis());
2542                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2543
2544                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2545                        | PackageParser.PARSE_FORWARD_LOCK,
2546                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2547
2548                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2549                        | PackageParser.PARSE_IS_EPHEMERAL,
2550                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2551
2552                /**
2553                 * Remove disable package settings for any updated system
2554                 * apps that were removed via an OTA. If they're not a
2555                 * previously-updated app, remove them completely.
2556                 * Otherwise, just revoke their system-level permissions.
2557                 */
2558                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2559                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2560                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2561
2562                    String msg;
2563                    if (deletedPkg == null) {
2564                        msg = "Updated system package " + deletedAppName
2565                                + " no longer exists; it's data will be wiped";
2566                        // Actual deletion of code and data will be handled by later
2567                        // reconciliation step
2568                    } else {
2569                        msg = "Updated system app + " + deletedAppName
2570                                + " no longer present; removing system privileges for "
2571                                + deletedAppName;
2572
2573                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2574
2575                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2576                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2577                    }
2578                    logCriticalInfo(Log.WARN, msg);
2579                }
2580
2581                /**
2582                 * Make sure all system apps that we expected to appear on
2583                 * the userdata partition actually showed up. If they never
2584                 * appeared, crawl back and revive the system version.
2585                 */
2586                for (int i = 0; i < mExpectingBetter.size(); i++) {
2587                    final String packageName = mExpectingBetter.keyAt(i);
2588                    if (!mPackages.containsKey(packageName)) {
2589                        final File scanFile = mExpectingBetter.valueAt(i);
2590
2591                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2592                                + " but never showed up; reverting to system");
2593
2594                        int reparseFlags = mDefParseFlags;
2595                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2596                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2597                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                                    | PackageParser.PARSE_IS_PRIVILEGED;
2599                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2602                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2603                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2604                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2605                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2606                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2607                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2608                        } else {
2609                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2610                            continue;
2611                        }
2612
2613                        mSettings.enableSystemPackageLPw(packageName);
2614
2615                        try {
2616                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2617                        } catch (PackageManagerException e) {
2618                            Slog.e(TAG, "Failed to parse original system package: "
2619                                    + e.getMessage());
2620                        }
2621                    }
2622                }
2623            }
2624            mExpectingBetter.clear();
2625
2626            // Resolve protected action filters. Only the setup wizard is allowed to
2627            // have a high priority filter for these actions.
2628            mSetupWizardPackage = getSetupWizardPackageName();
2629            if (mProtectedFilters.size() > 0) {
2630                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2631                    Slog.i(TAG, "No setup wizard;"
2632                        + " All protected intents capped to priority 0");
2633                }
2634                for (ActivityIntentInfo filter : mProtectedFilters) {
2635                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2636                        if (DEBUG_FILTERS) {
2637                            Slog.i(TAG, "Found setup wizard;"
2638                                + " allow priority " + filter.getPriority() + ";"
2639                                + " package: " + filter.activity.info.packageName
2640                                + " activity: " + filter.activity.className
2641                                + " priority: " + filter.getPriority());
2642                        }
2643                        // skip setup wizard; allow it to keep the high priority filter
2644                        continue;
2645                    }
2646                    Slog.w(TAG, "Protected action; cap priority to 0;"
2647                            + " package: " + filter.activity.info.packageName
2648                            + " activity: " + filter.activity.className
2649                            + " origPrio: " + filter.getPriority());
2650                    filter.setPriority(0);
2651                }
2652            }
2653            mDeferProtectedFilters = false;
2654            mProtectedFilters.clear();
2655
2656            // Now that we know all of the shared libraries, update all clients to have
2657            // the correct library paths.
2658            updateAllSharedLibrariesLPw();
2659
2660            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2661                // NOTE: We ignore potential failures here during a system scan (like
2662                // the rest of the commands above) because there's precious little we
2663                // can do about it. A settings error is reported, though.
2664                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2665                        false /* boot complete */);
2666            }
2667
2668            // Now that we know all the packages we are keeping,
2669            // read and update their last usage times.
2670            mPackageUsage.readLP();
2671
2672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2673                    SystemClock.uptimeMillis());
2674            Slog.i(TAG, "Time to scan packages: "
2675                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2676                    + " seconds");
2677
2678            // If the platform SDK has changed since the last time we booted,
2679            // we need to re-grant app permission to catch any new ones that
2680            // appear.  This is really a hack, and means that apps can in some
2681            // cases get permissions that the user didn't initially explicitly
2682            // allow...  it would be nice to have some better way to handle
2683            // this situation.
2684            int updateFlags = UPDATE_PERMISSIONS_ALL;
2685            if (ver.sdkVersion != mSdkVersion) {
2686                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2687                        + mSdkVersion + "; regranting permissions for internal storage");
2688                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2689            }
2690            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2691            ver.sdkVersion = mSdkVersion;
2692
2693            // If this is the first boot or an update from pre-M, and it is a normal
2694            // boot, then we need to initialize the default preferred apps across
2695            // all defined users.
2696            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2697                for (UserInfo user : sUserManager.getUsers(true)) {
2698                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2699                    applyFactoryDefaultBrowserLPw(user.id);
2700                    primeDomainVerificationsLPw(user.id);
2701                }
2702            }
2703
2704            // Prepare storage for system user really early during boot,
2705            // since core system apps like SettingsProvider and SystemUI
2706            // can't wait for user to start
2707            final int storageFlags;
2708            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE;
2710            } else {
2711                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2712            }
2713            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2714                    storageFlags);
2715
2716            // If this is first boot after an OTA, and a normal boot, then
2717            // we need to clear code cache directories.
2718            // Note that we do *not* clear the application profiles. These remain valid
2719            // across OTAs and are used to drive profile verification (post OTA) and
2720            // profile compilation (without waiting to collect a fresh set of profiles).
2721            if (mIsUpgrade && !onlyCore) {
2722                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2723                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2724                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2725                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2726                        // No apps are running this early, so no need to freeze
2727                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2728                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2729                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2730                    }
2731                }
2732                ver.fingerprint = Build.FINGERPRINT;
2733            }
2734
2735            checkDefaultBrowser();
2736
2737            // clear only after permissions and other defaults have been updated
2738            mExistingSystemPackages.clear();
2739            mPromoteSystemApps = false;
2740
2741            // All the changes are done during package scanning.
2742            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2743
2744            // can downgrade to reader
2745            mSettings.writeLPr();
2746
2747            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2748            // early on (before the package manager declares itself as early) because other
2749            // components in the system server might ask for package contexts for these apps.
2750            //
2751            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2752            // (i.e, that the data partition is unavailable).
2753            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2754                long start = System.nanoTime();
2755                List<PackageParser.Package> coreApps = new ArrayList<>();
2756                for (PackageParser.Package pkg : mPackages.values()) {
2757                    if (pkg.coreApp) {
2758                        coreApps.add(pkg);
2759                    }
2760                }
2761
2762                int[] stats = performDexOpt(coreApps, false,
2763                        getCompilerFilterForReason(REASON_CORE_APP));
2764
2765                final int elapsedTimeSeconds =
2766                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2767                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2768
2769                if (DEBUG_DEXOPT) {
2770                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2771                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2772                }
2773
2774
2775                // TODO: Should we log these stats to tron too ?
2776                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2777                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2778                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2779                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2780            }
2781
2782            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2783                    SystemClock.uptimeMillis());
2784
2785            if (!mOnlyCore) {
2786                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2787                mRequiredInstallerPackage = getRequiredInstallerLPr();
2788                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2789                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2790                        mIntentFilterVerifierComponent);
2791                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2792                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2793                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2794                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2795            } else {
2796                mRequiredVerifierPackage = null;
2797                mRequiredInstallerPackage = null;
2798                mIntentFilterVerifierComponent = null;
2799                mIntentFilterVerifier = null;
2800                mServicesSystemSharedLibraryPackageName = null;
2801                mSharedSystemSharedLibraryPackageName = null;
2802            }
2803
2804            mInstallerService = new PackageInstallerService(context, this);
2805
2806            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2807            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2808            // both the installer and resolver must be present to enable ephemeral
2809            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2810                if (DEBUG_EPHEMERAL) {
2811                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2812                            + " installer:" + ephemeralInstallerComponent);
2813                }
2814                mEphemeralResolverComponent = ephemeralResolverComponent;
2815                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2816                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2817                mEphemeralResolverConnection =
2818                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2819            } else {
2820                if (DEBUG_EPHEMERAL) {
2821                    final String missingComponent =
2822                            (ephemeralResolverComponent == null)
2823                            ? (ephemeralInstallerComponent == null)
2824                                    ? "resolver and installer"
2825                                    : "resolver"
2826                            : "installer";
2827                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2828                }
2829                mEphemeralResolverComponent = null;
2830                mEphemeralInstallerComponent = null;
2831                mEphemeralResolverConnection = null;
2832            }
2833
2834            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2835        } // synchronized (mPackages)
2836        } // synchronized (mInstallLock)
2837
2838        // Now after opening every single application zip, make sure they
2839        // are all flushed.  Not really needed, but keeps things nice and
2840        // tidy.
2841        Runtime.getRuntime().gc();
2842
2843        // The initial scanning above does many calls into installd while
2844        // holding the mPackages lock, but we're mostly interested in yelling
2845        // once we have a booted system.
2846        mInstaller.setWarnIfHeld(mPackages);
2847
2848        // Expose private service for system components to use.
2849        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2850    }
2851
2852    @Override
2853    public boolean isFirstBoot() {
2854        return !mRestoredSettings;
2855    }
2856
2857    @Override
2858    public boolean isOnlyCoreApps() {
2859        return mOnlyCore;
2860    }
2861
2862    @Override
2863    public boolean isUpgrade() {
2864        return mIsUpgrade;
2865    }
2866
2867    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2868        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2869
2870        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2871                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2872                UserHandle.USER_SYSTEM);
2873        if (matches.size() == 1) {
2874            return matches.get(0).getComponentInfo().packageName;
2875        } else {
2876            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2877            return null;
2878        }
2879    }
2880
2881    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2882        synchronized (mPackages) {
2883            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2884            if (libraryEntry == null) {
2885                throw new IllegalStateException("Missing required shared library:" + libraryName);
2886            }
2887            return libraryEntry.apk;
2888        }
2889    }
2890
2891    private @NonNull String getRequiredInstallerLPr() {
2892        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2893        intent.addCategory(Intent.CATEGORY_DEFAULT);
2894        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2895
2896        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2897                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2898                UserHandle.USER_SYSTEM);
2899        if (matches.size() == 1) {
2900            ResolveInfo resolveInfo = matches.get(0);
2901            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2902                throw new RuntimeException("The installer must be a privileged app");
2903            }
2904            return matches.get(0).getComponentInfo().packageName;
2905        } else {
2906            throw new RuntimeException("There must be exactly one installer; found " + matches);
2907        }
2908    }
2909
2910    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2911        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2912
2913        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2914                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2915                UserHandle.USER_SYSTEM);
2916        ResolveInfo best = null;
2917        final int N = matches.size();
2918        for (int i = 0; i < N; i++) {
2919            final ResolveInfo cur = matches.get(i);
2920            final String packageName = cur.getComponentInfo().packageName;
2921            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2922                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2923                continue;
2924            }
2925
2926            if (best == null || cur.priority > best.priority) {
2927                best = cur;
2928            }
2929        }
2930
2931        if (best != null) {
2932            return best.getComponentInfo().getComponentName();
2933        } else {
2934            throw new RuntimeException("There must be at least one intent filter verifier");
2935        }
2936    }
2937
2938    private @Nullable ComponentName getEphemeralResolverLPr() {
2939        final String[] packageArray =
2940                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2941        if (packageArray.length == 0) {
2942            if (DEBUG_EPHEMERAL) {
2943                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2944            }
2945            return null;
2946        }
2947
2948        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2949        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2950                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2951                UserHandle.USER_SYSTEM);
2952
2953        final int N = resolvers.size();
2954        if (N == 0) {
2955            if (DEBUG_EPHEMERAL) {
2956                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2957            }
2958            return null;
2959        }
2960
2961        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2962        for (int i = 0; i < N; i++) {
2963            final ResolveInfo info = resolvers.get(i);
2964
2965            if (info.serviceInfo == null) {
2966                continue;
2967            }
2968
2969            final String packageName = info.serviceInfo.packageName;
2970            if (!possiblePackages.contains(packageName)) {
2971                if (DEBUG_EPHEMERAL) {
2972                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2973                            + " pkg: " + packageName + ", info:" + info);
2974                }
2975                continue;
2976            }
2977
2978            if (DEBUG_EPHEMERAL) {
2979                Slog.v(TAG, "Ephemeral resolver found;"
2980                        + " pkg: " + packageName + ", info:" + info);
2981            }
2982            return new ComponentName(packageName, info.serviceInfo.name);
2983        }
2984        if (DEBUG_EPHEMERAL) {
2985            Slog.v(TAG, "Ephemeral resolver NOT found");
2986        }
2987        return null;
2988    }
2989
2990    private @Nullable ComponentName getEphemeralInstallerLPr() {
2991        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2992        intent.addCategory(Intent.CATEGORY_DEFAULT);
2993        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2994
2995        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2996                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2997                UserHandle.USER_SYSTEM);
2998        if (matches.size() == 0) {
2999            return null;
3000        } else if (matches.size() == 1) {
3001            return matches.get(0).getComponentInfo().getComponentName();
3002        } else {
3003            throw new RuntimeException(
3004                    "There must be at most one ephemeral installer; found " + matches);
3005        }
3006    }
3007
3008    private void primeDomainVerificationsLPw(int userId) {
3009        if (DEBUG_DOMAIN_VERIFICATION) {
3010            Slog.d(TAG, "Priming domain verifications in user " + userId);
3011        }
3012
3013        SystemConfig systemConfig = SystemConfig.getInstance();
3014        ArraySet<String> packages = systemConfig.getLinkedApps();
3015        ArraySet<String> domains = new ArraySet<String>();
3016
3017        for (String packageName : packages) {
3018            PackageParser.Package pkg = mPackages.get(packageName);
3019            if (pkg != null) {
3020                if (!pkg.isSystemApp()) {
3021                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3022                    continue;
3023                }
3024
3025                domains.clear();
3026                for (PackageParser.Activity a : pkg.activities) {
3027                    for (ActivityIntentInfo filter : a.intents) {
3028                        if (hasValidDomains(filter)) {
3029                            domains.addAll(filter.getHostsList());
3030                        }
3031                    }
3032                }
3033
3034                if (domains.size() > 0) {
3035                    if (DEBUG_DOMAIN_VERIFICATION) {
3036                        Slog.v(TAG, "      + " + packageName);
3037                    }
3038                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3039                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3040                    // and then 'always' in the per-user state actually used for intent resolution.
3041                    final IntentFilterVerificationInfo ivi;
3042                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3043                            new ArrayList<String>(domains));
3044                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3045                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3046                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3047                } else {
3048                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3049                            + "' does not handle web links");
3050                }
3051            } else {
3052                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3053            }
3054        }
3055
3056        scheduleWritePackageRestrictionsLocked(userId);
3057        scheduleWriteSettingsLocked();
3058    }
3059
3060    private void applyFactoryDefaultBrowserLPw(int userId) {
3061        // The default browser app's package name is stored in a string resource,
3062        // with a product-specific overlay used for vendor customization.
3063        String browserPkg = mContext.getResources().getString(
3064                com.android.internal.R.string.default_browser);
3065        if (!TextUtils.isEmpty(browserPkg)) {
3066            // non-empty string => required to be a known package
3067            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3068            if (ps == null) {
3069                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3070                browserPkg = null;
3071            } else {
3072                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3073            }
3074        }
3075
3076        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3077        // default.  If there's more than one, just leave everything alone.
3078        if (browserPkg == null) {
3079            calculateDefaultBrowserLPw(userId);
3080        }
3081    }
3082
3083    private void calculateDefaultBrowserLPw(int userId) {
3084        List<String> allBrowsers = resolveAllBrowserApps(userId);
3085        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3086        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3087    }
3088
3089    private List<String> resolveAllBrowserApps(int userId) {
3090        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3091        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3092                PackageManager.MATCH_ALL, userId);
3093
3094        final int count = list.size();
3095        List<String> result = new ArrayList<String>(count);
3096        for (int i=0; i<count; i++) {
3097            ResolveInfo info = list.get(i);
3098            if (info.activityInfo == null
3099                    || !info.handleAllWebDataURI
3100                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3101                    || result.contains(info.activityInfo.packageName)) {
3102                continue;
3103            }
3104            result.add(info.activityInfo.packageName);
3105        }
3106
3107        return result;
3108    }
3109
3110    private boolean packageIsBrowser(String packageName, int userId) {
3111        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3112                PackageManager.MATCH_ALL, userId);
3113        final int N = list.size();
3114        for (int i = 0; i < N; i++) {
3115            ResolveInfo info = list.get(i);
3116            if (packageName.equals(info.activityInfo.packageName)) {
3117                return true;
3118            }
3119        }
3120        return false;
3121    }
3122
3123    private void checkDefaultBrowser() {
3124        final int myUserId = UserHandle.myUserId();
3125        final String packageName = getDefaultBrowserPackageName(myUserId);
3126        if (packageName != null) {
3127            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3128            if (info == null) {
3129                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3130                synchronized (mPackages) {
3131                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3132                }
3133            }
3134        }
3135    }
3136
3137    @Override
3138    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3139            throws RemoteException {
3140        try {
3141            return super.onTransact(code, data, reply, flags);
3142        } catch (RuntimeException e) {
3143            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3144                Slog.wtf(TAG, "Package Manager Crash", e);
3145            }
3146            throw e;
3147        }
3148    }
3149
3150    static int[] appendInts(int[] cur, int[] add) {
3151        if (add == null) return cur;
3152        if (cur == null) return add;
3153        final int N = add.length;
3154        for (int i=0; i<N; i++) {
3155            cur = appendInt(cur, add[i]);
3156        }
3157        return cur;
3158    }
3159
3160    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3161        if (!sUserManager.exists(userId)) return null;
3162        if (ps == null) {
3163            return null;
3164        }
3165        final PackageParser.Package p = ps.pkg;
3166        if (p == null) {
3167            return null;
3168        }
3169
3170        final PermissionsState permissionsState = ps.getPermissionsState();
3171
3172        final int[] gids = permissionsState.computeGids(userId);
3173        final Set<String> permissions = permissionsState.getPermissions(userId);
3174        final PackageUserState state = ps.readUserState(userId);
3175
3176        return PackageParser.generatePackageInfo(p, gids, flags,
3177                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3178    }
3179
3180    @Override
3181    public void checkPackageStartable(String packageName, int userId) {
3182        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3183
3184        synchronized (mPackages) {
3185            final PackageSetting ps = mSettings.mPackages.get(packageName);
3186            if (ps == null) {
3187                throw new SecurityException("Package " + packageName + " was not found!");
3188            }
3189
3190            if (!ps.getInstalled(userId)) {
3191                throw new SecurityException(
3192                        "Package " + packageName + " was not installed for user " + userId + "!");
3193            }
3194
3195            if (mSafeMode && !ps.isSystem()) {
3196                throw new SecurityException("Package " + packageName + " not a system app!");
3197            }
3198
3199            if (mFrozenPackages.contains(packageName)) {
3200                throw new SecurityException("Package " + packageName + " is currently frozen!");
3201            }
3202
3203            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3204                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3205                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3206            }
3207        }
3208    }
3209
3210    @Override
3211    public boolean isPackageAvailable(String packageName, int userId) {
3212        if (!sUserManager.exists(userId)) return false;
3213        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3214                false /* requireFullPermission */, false /* checkShell */, "is package available");
3215        synchronized (mPackages) {
3216            PackageParser.Package p = mPackages.get(packageName);
3217            if (p != null) {
3218                final PackageSetting ps = (PackageSetting) p.mExtras;
3219                if (ps != null) {
3220                    final PackageUserState state = ps.readUserState(userId);
3221                    if (state != null) {
3222                        return PackageParser.isAvailable(state);
3223                    }
3224                }
3225            }
3226        }
3227        return false;
3228    }
3229
3230    @Override
3231    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3232        if (!sUserManager.exists(userId)) return null;
3233        flags = updateFlagsForPackage(flags, userId, packageName);
3234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3235                false /* requireFullPermission */, false /* checkShell */, "get package info");
3236        // reader
3237        synchronized (mPackages) {
3238            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3239            PackageParser.Package p = null;
3240            if (matchFactoryOnly) {
3241                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3242                if (ps != null) {
3243                    return generatePackageInfo(ps, flags, userId);
3244                }
3245            }
3246            if (p == null) {
3247                p = mPackages.get(packageName);
3248                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3249                    return null;
3250                }
3251            }
3252            if (DEBUG_PACKAGE_INFO)
3253                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3254            if (p != null) {
3255                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3256            }
3257            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3258                final PackageSetting ps = mSettings.mPackages.get(packageName);
3259                return generatePackageInfo(ps, flags, userId);
3260            }
3261        }
3262        return null;
3263    }
3264
3265    @Override
3266    public String[] currentToCanonicalPackageNames(String[] names) {
3267        String[] out = new String[names.length];
3268        // reader
3269        synchronized (mPackages) {
3270            for (int i=names.length-1; i>=0; i--) {
3271                PackageSetting ps = mSettings.mPackages.get(names[i]);
3272                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3273            }
3274        }
3275        return out;
3276    }
3277
3278    @Override
3279    public String[] canonicalToCurrentPackageNames(String[] names) {
3280        String[] out = new String[names.length];
3281        // reader
3282        synchronized (mPackages) {
3283            for (int i=names.length-1; i>=0; i--) {
3284                String cur = mSettings.mRenamedPackages.get(names[i]);
3285                out[i] = cur != null ? cur : names[i];
3286            }
3287        }
3288        return out;
3289    }
3290
3291    @Override
3292    public int getPackageUid(String packageName, int flags, int userId) {
3293        if (!sUserManager.exists(userId)) return -1;
3294        flags = updateFlagsForPackage(flags, userId, packageName);
3295        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3296                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3297
3298        // reader
3299        synchronized (mPackages) {
3300            final PackageParser.Package p = mPackages.get(packageName);
3301            if (p != null && p.isMatch(flags)) {
3302                return UserHandle.getUid(userId, p.applicationInfo.uid);
3303            }
3304            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3305                final PackageSetting ps = mSettings.mPackages.get(packageName);
3306                if (ps != null && ps.isMatch(flags)) {
3307                    return UserHandle.getUid(userId, ps.appId);
3308                }
3309            }
3310        }
3311
3312        return -1;
3313    }
3314
3315    @Override
3316    public int[] getPackageGids(String packageName, int flags, int userId) {
3317        if (!sUserManager.exists(userId)) return null;
3318        flags = updateFlagsForPackage(flags, userId, packageName);
3319        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3320                false /* requireFullPermission */, false /* checkShell */,
3321                "getPackageGids");
3322
3323        // reader
3324        synchronized (mPackages) {
3325            final PackageParser.Package p = mPackages.get(packageName);
3326            if (p != null && p.isMatch(flags)) {
3327                PackageSetting ps = (PackageSetting) p.mExtras;
3328                return ps.getPermissionsState().computeGids(userId);
3329            }
3330            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3331                final PackageSetting ps = mSettings.mPackages.get(packageName);
3332                if (ps != null && ps.isMatch(flags)) {
3333                    return ps.getPermissionsState().computeGids(userId);
3334                }
3335            }
3336        }
3337
3338        return null;
3339    }
3340
3341    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3342        if (bp.perm != null) {
3343            return PackageParser.generatePermissionInfo(bp.perm, flags);
3344        }
3345        PermissionInfo pi = new PermissionInfo();
3346        pi.name = bp.name;
3347        pi.packageName = bp.sourcePackage;
3348        pi.nonLocalizedLabel = bp.name;
3349        pi.protectionLevel = bp.protectionLevel;
3350        return pi;
3351    }
3352
3353    @Override
3354    public PermissionInfo getPermissionInfo(String name, int flags) {
3355        // reader
3356        synchronized (mPackages) {
3357            final BasePermission p = mSettings.mPermissions.get(name);
3358            if (p != null) {
3359                return generatePermissionInfo(p, flags);
3360            }
3361            return null;
3362        }
3363    }
3364
3365    @Override
3366    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3367            int flags) {
3368        // reader
3369        synchronized (mPackages) {
3370            if (group != null && !mPermissionGroups.containsKey(group)) {
3371                // This is thrown as NameNotFoundException
3372                return null;
3373            }
3374
3375            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3376            for (BasePermission p : mSettings.mPermissions.values()) {
3377                if (group == null) {
3378                    if (p.perm == null || p.perm.info.group == null) {
3379                        out.add(generatePermissionInfo(p, flags));
3380                    }
3381                } else {
3382                    if (p.perm != null && group.equals(p.perm.info.group)) {
3383                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3384                    }
3385                }
3386            }
3387            return new ParceledListSlice<>(out);
3388        }
3389    }
3390
3391    @Override
3392    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3393        // reader
3394        synchronized (mPackages) {
3395            return PackageParser.generatePermissionGroupInfo(
3396                    mPermissionGroups.get(name), flags);
3397        }
3398    }
3399
3400    @Override
3401    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3402        // reader
3403        synchronized (mPackages) {
3404            final int N = mPermissionGroups.size();
3405            ArrayList<PermissionGroupInfo> out
3406                    = new ArrayList<PermissionGroupInfo>(N);
3407            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3408                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3409            }
3410            return new ParceledListSlice<>(out);
3411        }
3412    }
3413
3414    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3415            int userId) {
3416        if (!sUserManager.exists(userId)) return null;
3417        PackageSetting ps = mSettings.mPackages.get(packageName);
3418        if (ps != null) {
3419            if (ps.pkg == null) {
3420                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3421                if (pInfo != null) {
3422                    return pInfo.applicationInfo;
3423                }
3424                return null;
3425            }
3426            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3427                    ps.readUserState(userId), userId);
3428        }
3429        return null;
3430    }
3431
3432    @Override
3433    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3434        if (!sUserManager.exists(userId)) return null;
3435        flags = updateFlagsForApplication(flags, userId, packageName);
3436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3437                false /* requireFullPermission */, false /* checkShell */, "get application info");
3438        // writer
3439        synchronized (mPackages) {
3440            PackageParser.Package p = mPackages.get(packageName);
3441            if (DEBUG_PACKAGE_INFO) Log.v(
3442                    TAG, "getApplicationInfo " + packageName
3443                    + ": " + p);
3444            if (p != null) {
3445                PackageSetting ps = mSettings.mPackages.get(packageName);
3446                if (ps == null) return null;
3447                // Note: isEnabledLP() does not apply here - always return info
3448                return PackageParser.generateApplicationInfo(
3449                        p, flags, ps.readUserState(userId), userId);
3450            }
3451            if ("android".equals(packageName)||"system".equals(packageName)) {
3452                return mAndroidApplication;
3453            }
3454            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3455                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3456            }
3457        }
3458        return null;
3459    }
3460
3461    @Override
3462    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3463            final IPackageDataObserver observer) {
3464        mContext.enforceCallingOrSelfPermission(
3465                android.Manifest.permission.CLEAR_APP_CACHE, null);
3466        // Queue up an async operation since clearing cache may take a little while.
3467        mHandler.post(new Runnable() {
3468            public void run() {
3469                mHandler.removeCallbacks(this);
3470                boolean success = true;
3471                synchronized (mInstallLock) {
3472                    try {
3473                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3474                    } catch (InstallerException e) {
3475                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3476                        success = false;
3477                    }
3478                }
3479                if (observer != null) {
3480                    try {
3481                        observer.onRemoveCompleted(null, success);
3482                    } catch (RemoteException e) {
3483                        Slog.w(TAG, "RemoveException when invoking call back");
3484                    }
3485                }
3486            }
3487        });
3488    }
3489
3490    @Override
3491    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3492            final IntentSender pi) {
3493        mContext.enforceCallingOrSelfPermission(
3494                android.Manifest.permission.CLEAR_APP_CACHE, null);
3495        // Queue up an async operation since clearing cache may take a little while.
3496        mHandler.post(new Runnable() {
3497            public void run() {
3498                mHandler.removeCallbacks(this);
3499                boolean success = true;
3500                synchronized (mInstallLock) {
3501                    try {
3502                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3503                    } catch (InstallerException e) {
3504                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3505                        success = false;
3506                    }
3507                }
3508                if(pi != null) {
3509                    try {
3510                        // Callback via pending intent
3511                        int code = success ? 1 : 0;
3512                        pi.sendIntent(null, code, null,
3513                                null, null);
3514                    } catch (SendIntentException e1) {
3515                        Slog.i(TAG, "Failed to send pending intent");
3516                    }
3517                }
3518            }
3519        });
3520    }
3521
3522    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3523        synchronized (mInstallLock) {
3524            try {
3525                mInstaller.freeCache(volumeUuid, freeStorageSize);
3526            } catch (InstallerException e) {
3527                throw new IOException("Failed to free enough space", e);
3528            }
3529        }
3530    }
3531
3532    /**
3533     * Update given flags based on encryption status of current user.
3534     */
3535    private int updateFlags(int flags, int userId) {
3536        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3537                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3538            // Caller expressed an explicit opinion about what encryption
3539            // aware/unaware components they want to see, so fall through and
3540            // give them what they want
3541        } else {
3542            // Caller expressed no opinion, so match based on user state
3543            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3544                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3545            } else {
3546                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3547            }
3548        }
3549        return flags;
3550    }
3551
3552    private UserManagerInternal getUserManagerInternal() {
3553        if (mUserManagerInternal == null) {
3554            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3555        }
3556        return mUserManagerInternal;
3557    }
3558
3559    /**
3560     * Update given flags when being used to request {@link PackageInfo}.
3561     */
3562    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3563        boolean triaged = true;
3564        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3565                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3566            // Caller is asking for component details, so they'd better be
3567            // asking for specific encryption matching behavior, or be triaged
3568            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3569                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3570                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3571                triaged = false;
3572            }
3573        }
3574        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3575                | PackageManager.MATCH_SYSTEM_ONLY
3576                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3577            triaged = false;
3578        }
3579        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3580            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3581                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3582        }
3583        return updateFlags(flags, userId);
3584    }
3585
3586    /**
3587     * Update given flags when being used to request {@link ApplicationInfo}.
3588     */
3589    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3590        return updateFlagsForPackage(flags, userId, cookie);
3591    }
3592
3593    /**
3594     * Update given flags when being used to request {@link ComponentInfo}.
3595     */
3596    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3597        if (cookie instanceof Intent) {
3598            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3599                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3600            }
3601        }
3602
3603        boolean triaged = true;
3604        // Caller is asking for component details, so they'd better be
3605        // asking for specific encryption matching behavior, or be triaged
3606        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3607                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3608                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3609            triaged = false;
3610        }
3611        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3612            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3613                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3614        }
3615
3616        return updateFlags(flags, userId);
3617    }
3618
3619    /**
3620     * Update given flags when being used to request {@link ResolveInfo}.
3621     */
3622    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3623        // Safe mode means we shouldn't match any third-party components
3624        if (mSafeMode) {
3625            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3626        }
3627
3628        return updateFlagsForComponent(flags, userId, cookie);
3629    }
3630
3631    @Override
3632    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3633        if (!sUserManager.exists(userId)) return null;
3634        flags = updateFlagsForComponent(flags, userId, component);
3635        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3636                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3637        synchronized (mPackages) {
3638            PackageParser.Activity a = mActivities.mActivities.get(component);
3639
3640            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3641            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3642                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3643                if (ps == null) return null;
3644                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3645                        userId);
3646            }
3647            if (mResolveComponentName.equals(component)) {
3648                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3649                        new PackageUserState(), userId);
3650            }
3651        }
3652        return null;
3653    }
3654
3655    @Override
3656    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3657            String resolvedType) {
3658        synchronized (mPackages) {
3659            if (component.equals(mResolveComponentName)) {
3660                // The resolver supports EVERYTHING!
3661                return true;
3662            }
3663            PackageParser.Activity a = mActivities.mActivities.get(component);
3664            if (a == null) {
3665                return false;
3666            }
3667            for (int i=0; i<a.intents.size(); i++) {
3668                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3669                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3670                    return true;
3671                }
3672            }
3673            return false;
3674        }
3675    }
3676
3677    @Override
3678    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3679        if (!sUserManager.exists(userId)) return null;
3680        flags = updateFlagsForComponent(flags, userId, component);
3681        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3682                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3683        synchronized (mPackages) {
3684            PackageParser.Activity a = mReceivers.mActivities.get(component);
3685            if (DEBUG_PACKAGE_INFO) Log.v(
3686                TAG, "getReceiverInfo " + component + ": " + a);
3687            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3688                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3689                if (ps == null) return null;
3690                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3691                        userId);
3692            }
3693        }
3694        return null;
3695    }
3696
3697    @Override
3698    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3699        if (!sUserManager.exists(userId)) return null;
3700        flags = updateFlagsForComponent(flags, userId, component);
3701        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3702                false /* requireFullPermission */, false /* checkShell */, "get service info");
3703        synchronized (mPackages) {
3704            PackageParser.Service s = mServices.mServices.get(component);
3705            if (DEBUG_PACKAGE_INFO) Log.v(
3706                TAG, "getServiceInfo " + component + ": " + s);
3707            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3708                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3709                if (ps == null) return null;
3710                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3711                        userId);
3712            }
3713        }
3714        return null;
3715    }
3716
3717    @Override
3718    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3719        if (!sUserManager.exists(userId)) return null;
3720        flags = updateFlagsForComponent(flags, userId, component);
3721        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3722                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3723        synchronized (mPackages) {
3724            PackageParser.Provider p = mProviders.mProviders.get(component);
3725            if (DEBUG_PACKAGE_INFO) Log.v(
3726                TAG, "getProviderInfo " + component + ": " + p);
3727            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3728                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3729                if (ps == null) return null;
3730                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3731                        userId);
3732            }
3733        }
3734        return null;
3735    }
3736
3737    @Override
3738    public String[] getSystemSharedLibraryNames() {
3739        Set<String> libSet;
3740        synchronized (mPackages) {
3741            libSet = mSharedLibraries.keySet();
3742            int size = libSet.size();
3743            if (size > 0) {
3744                String[] libs = new String[size];
3745                libSet.toArray(libs);
3746                return libs;
3747            }
3748        }
3749        return null;
3750    }
3751
3752    @Override
3753    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3754        synchronized (mPackages) {
3755            return mServicesSystemSharedLibraryPackageName;
3756        }
3757    }
3758
3759    @Override
3760    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3761        synchronized (mPackages) {
3762            return mSharedSystemSharedLibraryPackageName;
3763        }
3764    }
3765
3766    @Override
3767    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3768        synchronized (mPackages) {
3769            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3770
3771            final FeatureInfo fi = new FeatureInfo();
3772            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3773                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3774            res.add(fi);
3775
3776            return new ParceledListSlice<>(res);
3777        }
3778    }
3779
3780    @Override
3781    public boolean hasSystemFeature(String name, int version) {
3782        synchronized (mPackages) {
3783            final FeatureInfo feat = mAvailableFeatures.get(name);
3784            if (feat == null) {
3785                return false;
3786            } else {
3787                return feat.version >= version;
3788            }
3789        }
3790    }
3791
3792    @Override
3793    public int checkPermission(String permName, String pkgName, int userId) {
3794        if (!sUserManager.exists(userId)) {
3795            return PackageManager.PERMISSION_DENIED;
3796        }
3797
3798        synchronized (mPackages) {
3799            final PackageParser.Package p = mPackages.get(pkgName);
3800            if (p != null && p.mExtras != null) {
3801                final PackageSetting ps = (PackageSetting) p.mExtras;
3802                final PermissionsState permissionsState = ps.getPermissionsState();
3803                if (permissionsState.hasPermission(permName, userId)) {
3804                    return PackageManager.PERMISSION_GRANTED;
3805                }
3806                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3807                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3808                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3809                    return PackageManager.PERMISSION_GRANTED;
3810                }
3811            }
3812        }
3813
3814        return PackageManager.PERMISSION_DENIED;
3815    }
3816
3817    @Override
3818    public int checkUidPermission(String permName, int uid) {
3819        final int userId = UserHandle.getUserId(uid);
3820
3821        if (!sUserManager.exists(userId)) {
3822            return PackageManager.PERMISSION_DENIED;
3823        }
3824
3825        synchronized (mPackages) {
3826            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3827            if (obj != null) {
3828                final SettingBase ps = (SettingBase) obj;
3829                final PermissionsState permissionsState = ps.getPermissionsState();
3830                if (permissionsState.hasPermission(permName, userId)) {
3831                    return PackageManager.PERMISSION_GRANTED;
3832                }
3833                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3834                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3835                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3836                    return PackageManager.PERMISSION_GRANTED;
3837                }
3838            } else {
3839                ArraySet<String> perms = mSystemPermissions.get(uid);
3840                if (perms != null) {
3841                    if (perms.contains(permName)) {
3842                        return PackageManager.PERMISSION_GRANTED;
3843                    }
3844                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3845                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3846                        return PackageManager.PERMISSION_GRANTED;
3847                    }
3848                }
3849            }
3850        }
3851
3852        return PackageManager.PERMISSION_DENIED;
3853    }
3854
3855    @Override
3856    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3857        if (UserHandle.getCallingUserId() != userId) {
3858            mContext.enforceCallingPermission(
3859                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3860                    "isPermissionRevokedByPolicy for user " + userId);
3861        }
3862
3863        if (checkPermission(permission, packageName, userId)
3864                == PackageManager.PERMISSION_GRANTED) {
3865            return false;
3866        }
3867
3868        final long identity = Binder.clearCallingIdentity();
3869        try {
3870            final int flags = getPermissionFlags(permission, packageName, userId);
3871            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3872        } finally {
3873            Binder.restoreCallingIdentity(identity);
3874        }
3875    }
3876
3877    @Override
3878    public String getPermissionControllerPackageName() {
3879        synchronized (mPackages) {
3880            return mRequiredInstallerPackage;
3881        }
3882    }
3883
3884    /**
3885     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3886     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3887     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3888     * @param message the message to log on security exception
3889     */
3890    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3891            boolean checkShell, String message) {
3892        if (userId < 0) {
3893            throw new IllegalArgumentException("Invalid userId " + userId);
3894        }
3895        if (checkShell) {
3896            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3897        }
3898        if (userId == UserHandle.getUserId(callingUid)) return;
3899        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3900            if (requireFullPermission) {
3901                mContext.enforceCallingOrSelfPermission(
3902                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3903            } else {
3904                try {
3905                    mContext.enforceCallingOrSelfPermission(
3906                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3907                } catch (SecurityException se) {
3908                    mContext.enforceCallingOrSelfPermission(
3909                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3910                }
3911            }
3912        }
3913    }
3914
3915    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3916        if (callingUid == Process.SHELL_UID) {
3917            if (userHandle >= 0
3918                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3919                throw new SecurityException("Shell does not have permission to access user "
3920                        + userHandle);
3921            } else if (userHandle < 0) {
3922                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3923                        + Debug.getCallers(3));
3924            }
3925        }
3926    }
3927
3928    private BasePermission findPermissionTreeLP(String permName) {
3929        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3930            if (permName.startsWith(bp.name) &&
3931                    permName.length() > bp.name.length() &&
3932                    permName.charAt(bp.name.length()) == '.') {
3933                return bp;
3934            }
3935        }
3936        return null;
3937    }
3938
3939    private BasePermission checkPermissionTreeLP(String permName) {
3940        if (permName != null) {
3941            BasePermission bp = findPermissionTreeLP(permName);
3942            if (bp != null) {
3943                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3944                    return bp;
3945                }
3946                throw new SecurityException("Calling uid "
3947                        + Binder.getCallingUid()
3948                        + " is not allowed to add to permission tree "
3949                        + bp.name + " owned by uid " + bp.uid);
3950            }
3951        }
3952        throw new SecurityException("No permission tree found for " + permName);
3953    }
3954
3955    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3956        if (s1 == null) {
3957            return s2 == null;
3958        }
3959        if (s2 == null) {
3960            return false;
3961        }
3962        if (s1.getClass() != s2.getClass()) {
3963            return false;
3964        }
3965        return s1.equals(s2);
3966    }
3967
3968    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3969        if (pi1.icon != pi2.icon) return false;
3970        if (pi1.logo != pi2.logo) return false;
3971        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3972        if (!compareStrings(pi1.name, pi2.name)) return false;
3973        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3974        // We'll take care of setting this one.
3975        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3976        // These are not currently stored in settings.
3977        //if (!compareStrings(pi1.group, pi2.group)) return false;
3978        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3979        //if (pi1.labelRes != pi2.labelRes) return false;
3980        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3981        return true;
3982    }
3983
3984    int permissionInfoFootprint(PermissionInfo info) {
3985        int size = info.name.length();
3986        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3987        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3988        return size;
3989    }
3990
3991    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3992        int size = 0;
3993        for (BasePermission perm : mSettings.mPermissions.values()) {
3994            if (perm.uid == tree.uid) {
3995                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3996            }
3997        }
3998        return size;
3999    }
4000
4001    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4002        // We calculate the max size of permissions defined by this uid and throw
4003        // if that plus the size of 'info' would exceed our stated maximum.
4004        if (tree.uid != Process.SYSTEM_UID) {
4005            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4006            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4007                throw new SecurityException("Permission tree size cap exceeded");
4008            }
4009        }
4010    }
4011
4012    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4013        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4014            throw new SecurityException("Label must be specified in permission");
4015        }
4016        BasePermission tree = checkPermissionTreeLP(info.name);
4017        BasePermission bp = mSettings.mPermissions.get(info.name);
4018        boolean added = bp == null;
4019        boolean changed = true;
4020        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4021        if (added) {
4022            enforcePermissionCapLocked(info, tree);
4023            bp = new BasePermission(info.name, tree.sourcePackage,
4024                    BasePermission.TYPE_DYNAMIC);
4025        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4026            throw new SecurityException(
4027                    "Not allowed to modify non-dynamic permission "
4028                    + info.name);
4029        } else {
4030            if (bp.protectionLevel == fixedLevel
4031                    && bp.perm.owner.equals(tree.perm.owner)
4032                    && bp.uid == tree.uid
4033                    && comparePermissionInfos(bp.perm.info, info)) {
4034                changed = false;
4035            }
4036        }
4037        bp.protectionLevel = fixedLevel;
4038        info = new PermissionInfo(info);
4039        info.protectionLevel = fixedLevel;
4040        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4041        bp.perm.info.packageName = tree.perm.info.packageName;
4042        bp.uid = tree.uid;
4043        if (added) {
4044            mSettings.mPermissions.put(info.name, bp);
4045        }
4046        if (changed) {
4047            if (!async) {
4048                mSettings.writeLPr();
4049            } else {
4050                scheduleWriteSettingsLocked();
4051            }
4052        }
4053        return added;
4054    }
4055
4056    @Override
4057    public boolean addPermission(PermissionInfo info) {
4058        synchronized (mPackages) {
4059            return addPermissionLocked(info, false);
4060        }
4061    }
4062
4063    @Override
4064    public boolean addPermissionAsync(PermissionInfo info) {
4065        synchronized (mPackages) {
4066            return addPermissionLocked(info, true);
4067        }
4068    }
4069
4070    @Override
4071    public void removePermission(String name) {
4072        synchronized (mPackages) {
4073            checkPermissionTreeLP(name);
4074            BasePermission bp = mSettings.mPermissions.get(name);
4075            if (bp != null) {
4076                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4077                    throw new SecurityException(
4078                            "Not allowed to modify non-dynamic permission "
4079                            + name);
4080                }
4081                mSettings.mPermissions.remove(name);
4082                mSettings.writeLPr();
4083            }
4084        }
4085    }
4086
4087    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4088            BasePermission bp) {
4089        int index = pkg.requestedPermissions.indexOf(bp.name);
4090        if (index == -1) {
4091            throw new SecurityException("Package " + pkg.packageName
4092                    + " has not requested permission " + bp.name);
4093        }
4094        if (!bp.isRuntime() && !bp.isDevelopment()) {
4095            throw new SecurityException("Permission " + bp.name
4096                    + " is not a changeable permission type");
4097        }
4098    }
4099
4100    @Override
4101    public void grantRuntimePermission(String packageName, String name, final int userId) {
4102        if (!sUserManager.exists(userId)) {
4103            Log.e(TAG, "No such user:" + userId);
4104            return;
4105        }
4106
4107        mContext.enforceCallingOrSelfPermission(
4108                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4109                "grantRuntimePermission");
4110
4111        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4112                true /* requireFullPermission */, true /* checkShell */,
4113                "grantRuntimePermission");
4114
4115        final int uid;
4116        final SettingBase sb;
4117
4118        synchronized (mPackages) {
4119            final PackageParser.Package pkg = mPackages.get(packageName);
4120            if (pkg == null) {
4121                throw new IllegalArgumentException("Unknown package: " + packageName);
4122            }
4123
4124            final BasePermission bp = mSettings.mPermissions.get(name);
4125            if (bp == null) {
4126                throw new IllegalArgumentException("Unknown permission: " + name);
4127            }
4128
4129            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4130
4131            // If a permission review is required for legacy apps we represent
4132            // their permissions as always granted runtime ones since we need
4133            // to keep the review required permission flag per user while an
4134            // install permission's state is shared across all users.
4135            if (Build.PERMISSIONS_REVIEW_REQUIRED
4136                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4137                    && bp.isRuntime()) {
4138                return;
4139            }
4140
4141            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4142            sb = (SettingBase) pkg.mExtras;
4143            if (sb == null) {
4144                throw new IllegalArgumentException("Unknown package: " + packageName);
4145            }
4146
4147            final PermissionsState permissionsState = sb.getPermissionsState();
4148
4149            final int flags = permissionsState.getPermissionFlags(name, userId);
4150            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4151                throw new SecurityException("Cannot grant system fixed permission "
4152                        + name + " for package " + packageName);
4153            }
4154
4155            if (bp.isDevelopment()) {
4156                // Development permissions must be handled specially, since they are not
4157                // normal runtime permissions.  For now they apply to all users.
4158                if (permissionsState.grantInstallPermission(bp) !=
4159                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4160                    scheduleWriteSettingsLocked();
4161                }
4162                return;
4163            }
4164
4165            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4166                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4167                return;
4168            }
4169
4170            final int result = permissionsState.grantRuntimePermission(bp, userId);
4171            switch (result) {
4172                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4173                    return;
4174                }
4175
4176                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4177                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4178                    mHandler.post(new Runnable() {
4179                        @Override
4180                        public void run() {
4181                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4182                        }
4183                    });
4184                }
4185                break;
4186            }
4187
4188            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4189
4190            // Not critical if that is lost - app has to request again.
4191            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4192        }
4193
4194        // Only need to do this if user is initialized. Otherwise it's a new user
4195        // and there are no processes running as the user yet and there's no need
4196        // to make an expensive call to remount processes for the changed permissions.
4197        if (READ_EXTERNAL_STORAGE.equals(name)
4198                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4199            final long token = Binder.clearCallingIdentity();
4200            try {
4201                if (sUserManager.isInitialized(userId)) {
4202                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4203                            MountServiceInternal.class);
4204                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4205                }
4206            } finally {
4207                Binder.restoreCallingIdentity(token);
4208            }
4209        }
4210    }
4211
4212    @Override
4213    public void revokeRuntimePermission(String packageName, String name, int userId) {
4214        if (!sUserManager.exists(userId)) {
4215            Log.e(TAG, "No such user:" + userId);
4216            return;
4217        }
4218
4219        mContext.enforceCallingOrSelfPermission(
4220                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4221                "revokeRuntimePermission");
4222
4223        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4224                true /* requireFullPermission */, true /* checkShell */,
4225                "revokeRuntimePermission");
4226
4227        final int appId;
4228
4229        synchronized (mPackages) {
4230            final PackageParser.Package pkg = mPackages.get(packageName);
4231            if (pkg == null) {
4232                throw new IllegalArgumentException("Unknown package: " + packageName);
4233            }
4234
4235            final BasePermission bp = mSettings.mPermissions.get(name);
4236            if (bp == null) {
4237                throw new IllegalArgumentException("Unknown permission: " + name);
4238            }
4239
4240            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4241
4242            // If a permission review is required for legacy apps we represent
4243            // their permissions as always granted runtime ones since we need
4244            // to keep the review required permission flag per user while an
4245            // install permission's state is shared across all users.
4246            if (Build.PERMISSIONS_REVIEW_REQUIRED
4247                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4248                    && bp.isRuntime()) {
4249                return;
4250            }
4251
4252            SettingBase sb = (SettingBase) pkg.mExtras;
4253            if (sb == null) {
4254                throw new IllegalArgumentException("Unknown package: " + packageName);
4255            }
4256
4257            final PermissionsState permissionsState = sb.getPermissionsState();
4258
4259            final int flags = permissionsState.getPermissionFlags(name, userId);
4260            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4261                throw new SecurityException("Cannot revoke system fixed permission "
4262                        + name + " for package " + packageName);
4263            }
4264
4265            if (bp.isDevelopment()) {
4266                // Development permissions must be handled specially, since they are not
4267                // normal runtime permissions.  For now they apply to all users.
4268                if (permissionsState.revokeInstallPermission(bp) !=
4269                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4270                    scheduleWriteSettingsLocked();
4271                }
4272                return;
4273            }
4274
4275            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4276                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4277                return;
4278            }
4279
4280            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4281
4282            // Critical, after this call app should never have the permission.
4283            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4284
4285            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4286        }
4287
4288        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4289    }
4290
4291    @Override
4292    public void resetRuntimePermissions() {
4293        mContext.enforceCallingOrSelfPermission(
4294                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4295                "revokeRuntimePermission");
4296
4297        int callingUid = Binder.getCallingUid();
4298        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4299            mContext.enforceCallingOrSelfPermission(
4300                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4301                    "resetRuntimePermissions");
4302        }
4303
4304        synchronized (mPackages) {
4305            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4306            for (int userId : UserManagerService.getInstance().getUserIds()) {
4307                final int packageCount = mPackages.size();
4308                for (int i = 0; i < packageCount; i++) {
4309                    PackageParser.Package pkg = mPackages.valueAt(i);
4310                    if (!(pkg.mExtras instanceof PackageSetting)) {
4311                        continue;
4312                    }
4313                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4314                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4315                }
4316            }
4317        }
4318    }
4319
4320    @Override
4321    public int getPermissionFlags(String name, String packageName, int userId) {
4322        if (!sUserManager.exists(userId)) {
4323            return 0;
4324        }
4325
4326        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4327
4328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4329                true /* requireFullPermission */, false /* checkShell */,
4330                "getPermissionFlags");
4331
4332        synchronized (mPackages) {
4333            final PackageParser.Package pkg = mPackages.get(packageName);
4334            if (pkg == null) {
4335                return 0;
4336            }
4337
4338            final BasePermission bp = mSettings.mPermissions.get(name);
4339            if (bp == null) {
4340                return 0;
4341            }
4342
4343            SettingBase sb = (SettingBase) pkg.mExtras;
4344            if (sb == null) {
4345                return 0;
4346            }
4347
4348            PermissionsState permissionsState = sb.getPermissionsState();
4349            return permissionsState.getPermissionFlags(name, userId);
4350        }
4351    }
4352
4353    @Override
4354    public void updatePermissionFlags(String name, String packageName, int flagMask,
4355            int flagValues, int userId) {
4356        if (!sUserManager.exists(userId)) {
4357            return;
4358        }
4359
4360        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4361
4362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4363                true /* requireFullPermission */, true /* checkShell */,
4364                "updatePermissionFlags");
4365
4366        // Only the system can change these flags and nothing else.
4367        if (getCallingUid() != Process.SYSTEM_UID) {
4368            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4369            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4370            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4371            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4372            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4373        }
4374
4375        synchronized (mPackages) {
4376            final PackageParser.Package pkg = mPackages.get(packageName);
4377            if (pkg == null) {
4378                throw new IllegalArgumentException("Unknown package: " + packageName);
4379            }
4380
4381            final BasePermission bp = mSettings.mPermissions.get(name);
4382            if (bp == null) {
4383                throw new IllegalArgumentException("Unknown permission: " + name);
4384            }
4385
4386            SettingBase sb = (SettingBase) pkg.mExtras;
4387            if (sb == null) {
4388                throw new IllegalArgumentException("Unknown package: " + packageName);
4389            }
4390
4391            PermissionsState permissionsState = sb.getPermissionsState();
4392
4393            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4394
4395            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4396                // Install and runtime permissions are stored in different places,
4397                // so figure out what permission changed and persist the change.
4398                if (permissionsState.getInstallPermissionState(name) != null) {
4399                    scheduleWriteSettingsLocked();
4400                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4401                        || hadState) {
4402                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4403                }
4404            }
4405        }
4406    }
4407
4408    /**
4409     * Update the permission flags for all packages and runtime permissions of a user in order
4410     * to allow device or profile owner to remove POLICY_FIXED.
4411     */
4412    @Override
4413    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4414        if (!sUserManager.exists(userId)) {
4415            return;
4416        }
4417
4418        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4419
4420        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4421                true /* requireFullPermission */, true /* checkShell */,
4422                "updatePermissionFlagsForAllApps");
4423
4424        // Only the system can change system fixed flags.
4425        if (getCallingUid() != Process.SYSTEM_UID) {
4426            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4427            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4428        }
4429
4430        synchronized (mPackages) {
4431            boolean changed = false;
4432            final int packageCount = mPackages.size();
4433            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4434                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4435                SettingBase sb = (SettingBase) pkg.mExtras;
4436                if (sb == null) {
4437                    continue;
4438                }
4439                PermissionsState permissionsState = sb.getPermissionsState();
4440                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4441                        userId, flagMask, flagValues);
4442            }
4443            if (changed) {
4444                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4445            }
4446        }
4447    }
4448
4449    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4450        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4451                != PackageManager.PERMISSION_GRANTED
4452            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4453                != PackageManager.PERMISSION_GRANTED) {
4454            throw new SecurityException(message + " requires "
4455                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4456                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4457        }
4458    }
4459
4460    @Override
4461    public boolean shouldShowRequestPermissionRationale(String permissionName,
4462            String packageName, int userId) {
4463        if (UserHandle.getCallingUserId() != userId) {
4464            mContext.enforceCallingPermission(
4465                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4466                    "canShowRequestPermissionRationale for user " + userId);
4467        }
4468
4469        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4470        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4471            return false;
4472        }
4473
4474        if (checkPermission(permissionName, packageName, userId)
4475                == PackageManager.PERMISSION_GRANTED) {
4476            return false;
4477        }
4478
4479        final int flags;
4480
4481        final long identity = Binder.clearCallingIdentity();
4482        try {
4483            flags = getPermissionFlags(permissionName,
4484                    packageName, userId);
4485        } finally {
4486            Binder.restoreCallingIdentity(identity);
4487        }
4488
4489        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4490                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4491                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4492
4493        if ((flags & fixedFlags) != 0) {
4494            return false;
4495        }
4496
4497        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4498    }
4499
4500    @Override
4501    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4502        mContext.enforceCallingOrSelfPermission(
4503                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4504                "addOnPermissionsChangeListener");
4505
4506        synchronized (mPackages) {
4507            mOnPermissionChangeListeners.addListenerLocked(listener);
4508        }
4509    }
4510
4511    @Override
4512    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4513        synchronized (mPackages) {
4514            mOnPermissionChangeListeners.removeListenerLocked(listener);
4515        }
4516    }
4517
4518    @Override
4519    public boolean isProtectedBroadcast(String actionName) {
4520        synchronized (mPackages) {
4521            if (mProtectedBroadcasts.contains(actionName)) {
4522                return true;
4523            } else if (actionName != null) {
4524                // TODO: remove these terrible hacks
4525                if (actionName.startsWith("android.net.netmon.lingerExpired")
4526                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4527                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4528                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4529                    return true;
4530                }
4531            }
4532        }
4533        return false;
4534    }
4535
4536    @Override
4537    public int checkSignatures(String pkg1, String pkg2) {
4538        synchronized (mPackages) {
4539            final PackageParser.Package p1 = mPackages.get(pkg1);
4540            final PackageParser.Package p2 = mPackages.get(pkg2);
4541            if (p1 == null || p1.mExtras == null
4542                    || p2 == null || p2.mExtras == null) {
4543                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4544            }
4545            return compareSignatures(p1.mSignatures, p2.mSignatures);
4546        }
4547    }
4548
4549    @Override
4550    public int checkUidSignatures(int uid1, int uid2) {
4551        // Map to base uids.
4552        uid1 = UserHandle.getAppId(uid1);
4553        uid2 = UserHandle.getAppId(uid2);
4554        // reader
4555        synchronized (mPackages) {
4556            Signature[] s1;
4557            Signature[] s2;
4558            Object obj = mSettings.getUserIdLPr(uid1);
4559            if (obj != null) {
4560                if (obj instanceof SharedUserSetting) {
4561                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4562                } else if (obj instanceof PackageSetting) {
4563                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4564                } else {
4565                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4566                }
4567            } else {
4568                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4569            }
4570            obj = mSettings.getUserIdLPr(uid2);
4571            if (obj != null) {
4572                if (obj instanceof SharedUserSetting) {
4573                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4574                } else if (obj instanceof PackageSetting) {
4575                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4576                } else {
4577                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4578                }
4579            } else {
4580                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4581            }
4582            return compareSignatures(s1, s2);
4583        }
4584    }
4585
4586    /**
4587     * This method should typically only be used when granting or revoking
4588     * permissions, since the app may immediately restart after this call.
4589     * <p>
4590     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4591     * guard your work against the app being relaunched.
4592     */
4593    private void killUid(int appId, int userId, String reason) {
4594        final long identity = Binder.clearCallingIdentity();
4595        try {
4596            IActivityManager am = ActivityManagerNative.getDefault();
4597            if (am != null) {
4598                try {
4599                    am.killUid(appId, userId, reason);
4600                } catch (RemoteException e) {
4601                    /* ignore - same process */
4602                }
4603            }
4604        } finally {
4605            Binder.restoreCallingIdentity(identity);
4606        }
4607    }
4608
4609    /**
4610     * Compares two sets of signatures. Returns:
4611     * <br />
4612     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4613     * <br />
4614     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4615     * <br />
4616     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4617     * <br />
4618     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4619     * <br />
4620     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4621     */
4622    static int compareSignatures(Signature[] s1, Signature[] s2) {
4623        if (s1 == null) {
4624            return s2 == null
4625                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4626                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4627        }
4628
4629        if (s2 == null) {
4630            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4631        }
4632
4633        if (s1.length != s2.length) {
4634            return PackageManager.SIGNATURE_NO_MATCH;
4635        }
4636
4637        // Since both signature sets are of size 1, we can compare without HashSets.
4638        if (s1.length == 1) {
4639            return s1[0].equals(s2[0]) ?
4640                    PackageManager.SIGNATURE_MATCH :
4641                    PackageManager.SIGNATURE_NO_MATCH;
4642        }
4643
4644        ArraySet<Signature> set1 = new ArraySet<Signature>();
4645        for (Signature sig : s1) {
4646            set1.add(sig);
4647        }
4648        ArraySet<Signature> set2 = new ArraySet<Signature>();
4649        for (Signature sig : s2) {
4650            set2.add(sig);
4651        }
4652        // Make sure s2 contains all signatures in s1.
4653        if (set1.equals(set2)) {
4654            return PackageManager.SIGNATURE_MATCH;
4655        }
4656        return PackageManager.SIGNATURE_NO_MATCH;
4657    }
4658
4659    /**
4660     * If the database version for this type of package (internal storage or
4661     * external storage) is less than the version where package signatures
4662     * were updated, return true.
4663     */
4664    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4665        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4666        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4667    }
4668
4669    /**
4670     * Used for backward compatibility to make sure any packages with
4671     * certificate chains get upgraded to the new style. {@code existingSigs}
4672     * will be in the old format (since they were stored on disk from before the
4673     * system upgrade) and {@code scannedSigs} will be in the newer format.
4674     */
4675    private int compareSignaturesCompat(PackageSignatures existingSigs,
4676            PackageParser.Package scannedPkg) {
4677        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4678            return PackageManager.SIGNATURE_NO_MATCH;
4679        }
4680
4681        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4682        for (Signature sig : existingSigs.mSignatures) {
4683            existingSet.add(sig);
4684        }
4685        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4686        for (Signature sig : scannedPkg.mSignatures) {
4687            try {
4688                Signature[] chainSignatures = sig.getChainSignatures();
4689                for (Signature chainSig : chainSignatures) {
4690                    scannedCompatSet.add(chainSig);
4691                }
4692            } catch (CertificateEncodingException e) {
4693                scannedCompatSet.add(sig);
4694            }
4695        }
4696        /*
4697         * Make sure the expanded scanned set contains all signatures in the
4698         * existing one.
4699         */
4700        if (scannedCompatSet.equals(existingSet)) {
4701            // Migrate the old signatures to the new scheme.
4702            existingSigs.assignSignatures(scannedPkg.mSignatures);
4703            // The new KeySets will be re-added later in the scanning process.
4704            synchronized (mPackages) {
4705                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4706            }
4707            return PackageManager.SIGNATURE_MATCH;
4708        }
4709        return PackageManager.SIGNATURE_NO_MATCH;
4710    }
4711
4712    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4713        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4714        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4715    }
4716
4717    private int compareSignaturesRecover(PackageSignatures existingSigs,
4718            PackageParser.Package scannedPkg) {
4719        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4720            return PackageManager.SIGNATURE_NO_MATCH;
4721        }
4722
4723        String msg = null;
4724        try {
4725            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4726                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4727                        + scannedPkg.packageName);
4728                return PackageManager.SIGNATURE_MATCH;
4729            }
4730        } catch (CertificateException e) {
4731            msg = e.getMessage();
4732        }
4733
4734        logCriticalInfo(Log.INFO,
4735                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4736        return PackageManager.SIGNATURE_NO_MATCH;
4737    }
4738
4739    @Override
4740    public List<String> getAllPackages() {
4741        synchronized (mPackages) {
4742            return new ArrayList<String>(mPackages.keySet());
4743        }
4744    }
4745
4746    @Override
4747    public String[] getPackagesForUid(int uid) {
4748        uid = UserHandle.getAppId(uid);
4749        // reader
4750        synchronized (mPackages) {
4751            Object obj = mSettings.getUserIdLPr(uid);
4752            if (obj instanceof SharedUserSetting) {
4753                final SharedUserSetting sus = (SharedUserSetting) obj;
4754                final int N = sus.packages.size();
4755                final String[] res = new String[N];
4756                for (int i = 0; i < N; i++) {
4757                    res[i] = sus.packages.valueAt(i).name;
4758                }
4759                return res;
4760            } else if (obj instanceof PackageSetting) {
4761                final PackageSetting ps = (PackageSetting) obj;
4762                return new String[] { ps.name };
4763            }
4764        }
4765        return null;
4766    }
4767
4768    @Override
4769    public String getNameForUid(int uid) {
4770        // reader
4771        synchronized (mPackages) {
4772            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4773            if (obj instanceof SharedUserSetting) {
4774                final SharedUserSetting sus = (SharedUserSetting) obj;
4775                return sus.name + ":" + sus.userId;
4776            } else if (obj instanceof PackageSetting) {
4777                final PackageSetting ps = (PackageSetting) obj;
4778                return ps.name;
4779            }
4780        }
4781        return null;
4782    }
4783
4784    @Override
4785    public int getUidForSharedUser(String sharedUserName) {
4786        if(sharedUserName == null) {
4787            return -1;
4788        }
4789        // reader
4790        synchronized (mPackages) {
4791            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4792            if (suid == null) {
4793                return -1;
4794            }
4795            return suid.userId;
4796        }
4797    }
4798
4799    @Override
4800    public int getFlagsForUid(int uid) {
4801        synchronized (mPackages) {
4802            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4803            if (obj instanceof SharedUserSetting) {
4804                final SharedUserSetting sus = (SharedUserSetting) obj;
4805                return sus.pkgFlags;
4806            } else if (obj instanceof PackageSetting) {
4807                final PackageSetting ps = (PackageSetting) obj;
4808                return ps.pkgFlags;
4809            }
4810        }
4811        return 0;
4812    }
4813
4814    @Override
4815    public int getPrivateFlagsForUid(int uid) {
4816        synchronized (mPackages) {
4817            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4818            if (obj instanceof SharedUserSetting) {
4819                final SharedUserSetting sus = (SharedUserSetting) obj;
4820                return sus.pkgPrivateFlags;
4821            } else if (obj instanceof PackageSetting) {
4822                final PackageSetting ps = (PackageSetting) obj;
4823                return ps.pkgPrivateFlags;
4824            }
4825        }
4826        return 0;
4827    }
4828
4829    @Override
4830    public boolean isUidPrivileged(int uid) {
4831        uid = UserHandle.getAppId(uid);
4832        // reader
4833        synchronized (mPackages) {
4834            Object obj = mSettings.getUserIdLPr(uid);
4835            if (obj instanceof SharedUserSetting) {
4836                final SharedUserSetting sus = (SharedUserSetting) obj;
4837                final Iterator<PackageSetting> it = sus.packages.iterator();
4838                while (it.hasNext()) {
4839                    if (it.next().isPrivileged()) {
4840                        return true;
4841                    }
4842                }
4843            } else if (obj instanceof PackageSetting) {
4844                final PackageSetting ps = (PackageSetting) obj;
4845                return ps.isPrivileged();
4846            }
4847        }
4848        return false;
4849    }
4850
4851    @Override
4852    public String[] getAppOpPermissionPackages(String permissionName) {
4853        synchronized (mPackages) {
4854            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4855            if (pkgs == null) {
4856                return null;
4857            }
4858            return pkgs.toArray(new String[pkgs.size()]);
4859        }
4860    }
4861
4862    @Override
4863    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4864            int flags, int userId) {
4865        try {
4866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4867
4868            if (!sUserManager.exists(userId)) return null;
4869            flags = updateFlagsForResolve(flags, userId, intent);
4870            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4871                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4872
4873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4874            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4875                    flags, userId);
4876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4877
4878            final ResolveInfo bestChoice =
4879                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4880
4881            if (isEphemeralAllowed(intent, query, userId)) {
4882                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4883                final EphemeralResolveInfo ai =
4884                        getEphemeralResolveInfo(intent, resolvedType, userId);
4885                if (ai != null) {
4886                    if (DEBUG_EPHEMERAL) {
4887                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4888                    }
4889                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4890                    bestChoice.ephemeralResolveInfo = ai;
4891                }
4892                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4893            }
4894            return bestChoice;
4895        } finally {
4896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4897        }
4898    }
4899
4900    @Override
4901    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4902            IntentFilter filter, int match, ComponentName activity) {
4903        final int userId = UserHandle.getCallingUserId();
4904        if (DEBUG_PREFERRED) {
4905            Log.v(TAG, "setLastChosenActivity intent=" + intent
4906                + " resolvedType=" + resolvedType
4907                + " flags=" + flags
4908                + " filter=" + filter
4909                + " match=" + match
4910                + " activity=" + activity);
4911            filter.dump(new PrintStreamPrinter(System.out), "    ");
4912        }
4913        intent.setComponent(null);
4914        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4915                userId);
4916        // Find any earlier preferred or last chosen entries and nuke them
4917        findPreferredActivity(intent, resolvedType,
4918                flags, query, 0, false, true, false, userId);
4919        // Add the new activity as the last chosen for this filter
4920        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4921                "Setting last chosen");
4922    }
4923
4924    @Override
4925    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4926        final int userId = UserHandle.getCallingUserId();
4927        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4928        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4929                userId);
4930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4931                false, false, false, userId);
4932    }
4933
4934
4935    private boolean isEphemeralAllowed(
4936            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4937        // Short circuit and return early if possible.
4938        if (DISABLE_EPHEMERAL_APPS) {
4939            return false;
4940        }
4941        final int callingUser = UserHandle.getCallingUserId();
4942        if (callingUser != UserHandle.USER_SYSTEM) {
4943            return false;
4944        }
4945        if (mEphemeralResolverConnection == null) {
4946            return false;
4947        }
4948        if (intent.getComponent() != null) {
4949            return false;
4950        }
4951        if (intent.getPackage() != null) {
4952            return false;
4953        }
4954        final boolean isWebUri = hasWebURI(intent);
4955        if (!isWebUri) {
4956            return false;
4957        }
4958        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4959        synchronized (mPackages) {
4960            final int count = resolvedActivites.size();
4961            for (int n = 0; n < count; n++) {
4962                ResolveInfo info = resolvedActivites.get(n);
4963                String packageName = info.activityInfo.packageName;
4964                PackageSetting ps = mSettings.mPackages.get(packageName);
4965                if (ps != null) {
4966                    // Try to get the status from User settings first
4967                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4968                    int status = (int) (packedStatus >> 32);
4969                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4970                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4971                        if (DEBUG_EPHEMERAL) {
4972                            Slog.v(TAG, "DENY ephemeral apps;"
4973                                + " pkg: " + packageName + ", status: " + status);
4974                        }
4975                        return false;
4976                    }
4977                }
4978            }
4979        }
4980        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4981        return true;
4982    }
4983
4984    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4985            int userId) {
4986        MessageDigest digest = null;
4987        try {
4988            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4989        } catch (NoSuchAlgorithmException e) {
4990            // If we can't create a digest, ignore ephemeral apps.
4991            return null;
4992        }
4993
4994        final byte[] hostBytes = intent.getData().getHost().getBytes();
4995        final byte[] digestBytes = digest.digest(hostBytes);
4996        int shaPrefix =
4997                digestBytes[0] << 24
4998                | digestBytes[1] << 16
4999                | digestBytes[2] << 8
5000                | digestBytes[3] << 0;
5001        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5002                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5003        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5004            // No hash prefix match; there are no ephemeral apps for this domain.
5005            return null;
5006        }
5007        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5008            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5009            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5010                continue;
5011            }
5012            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5013            // No filters; this should never happen.
5014            if (filters.isEmpty()) {
5015                continue;
5016            }
5017            // We have a domain match; resolve the filters to see if anything matches.
5018            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5019            for (int j = filters.size() - 1; j >= 0; --j) {
5020                final EphemeralResolveIntentInfo intentInfo =
5021                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5022                ephemeralResolver.addFilter(intentInfo);
5023            }
5024            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5025                    intent, resolvedType, false /*defaultOnly*/, userId);
5026            if (!matchedResolveInfoList.isEmpty()) {
5027                return matchedResolveInfoList.get(0);
5028            }
5029        }
5030        // Hash or filter mis-match; no ephemeral apps for this domain.
5031        return null;
5032    }
5033
5034    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5035            int flags, List<ResolveInfo> query, int userId) {
5036        if (query != null) {
5037            final int N = query.size();
5038            if (N == 1) {
5039                return query.get(0);
5040            } else if (N > 1) {
5041                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5042                // If there is more than one activity with the same priority,
5043                // then let the user decide between them.
5044                ResolveInfo r0 = query.get(0);
5045                ResolveInfo r1 = query.get(1);
5046                if (DEBUG_INTENT_MATCHING || debug) {
5047                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5048                            + r1.activityInfo.name + "=" + r1.priority);
5049                }
5050                // If the first activity has a higher priority, or a different
5051                // default, then it is always desirable to pick it.
5052                if (r0.priority != r1.priority
5053                        || r0.preferredOrder != r1.preferredOrder
5054                        || r0.isDefault != r1.isDefault) {
5055                    return query.get(0);
5056                }
5057                // If we have saved a preference for a preferred activity for
5058                // this Intent, use that.
5059                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5060                        flags, query, r0.priority, true, false, debug, userId);
5061                if (ri != null) {
5062                    return ri;
5063                }
5064                ri = new ResolveInfo(mResolveInfo);
5065                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5066                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5067                // If all of the options come from the same package, show the application's
5068                // label and icon instead of the generic resolver's.
5069                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5070                // and then throw away the ResolveInfo itself, meaning that the caller loses
5071                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5072                // a fallback for this case; we only set the target package's resources on
5073                // the ResolveInfo, not the ActivityInfo.
5074                final String intentPackage = intent.getPackage();
5075                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5076                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5077                    ri.resolvePackageName = intentPackage;
5078                    if (userNeedsBadging(userId)) {
5079                        ri.noResourceId = true;
5080                    } else {
5081                        ri.icon = appi.icon;
5082                    }
5083                    ri.iconResourceId = appi.icon;
5084                    ri.labelRes = appi.labelRes;
5085                }
5086                ri.activityInfo.applicationInfo = new ApplicationInfo(
5087                        ri.activityInfo.applicationInfo);
5088                if (userId != 0) {
5089                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5090                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5091                }
5092                // Make sure that the resolver is displayable in car mode
5093                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5094                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5095                return ri;
5096            }
5097        }
5098        return null;
5099    }
5100
5101    /**
5102     * Return true if the given list is not empty and all of its contents have
5103     * an activityInfo with the given package name.
5104     */
5105    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5106        if (ArrayUtils.isEmpty(list)) {
5107            return false;
5108        }
5109        for (int i = 0, N = list.size(); i < N; i++) {
5110            final ResolveInfo ri = list.get(i);
5111            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5112            if (ai == null || !packageName.equals(ai.packageName)) {
5113                return false;
5114            }
5115        }
5116        return true;
5117    }
5118
5119    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5120            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5121        final int N = query.size();
5122        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5123                .get(userId);
5124        // Get the list of persistent preferred activities that handle the intent
5125        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5126        List<PersistentPreferredActivity> pprefs = ppir != null
5127                ? ppir.queryIntent(intent, resolvedType,
5128                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5129                : null;
5130        if (pprefs != null && pprefs.size() > 0) {
5131            final int M = pprefs.size();
5132            for (int i=0; i<M; i++) {
5133                final PersistentPreferredActivity ppa = pprefs.get(i);
5134                if (DEBUG_PREFERRED || debug) {
5135                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5136                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5137                            + "\n  component=" + ppa.mComponent);
5138                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5139                }
5140                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5141                        flags | MATCH_DISABLED_COMPONENTS, userId);
5142                if (DEBUG_PREFERRED || debug) {
5143                    Slog.v(TAG, "Found persistent preferred activity:");
5144                    if (ai != null) {
5145                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5146                    } else {
5147                        Slog.v(TAG, "  null");
5148                    }
5149                }
5150                if (ai == null) {
5151                    // This previously registered persistent preferred activity
5152                    // component is no longer known. Ignore it and do NOT remove it.
5153                    continue;
5154                }
5155                for (int j=0; j<N; j++) {
5156                    final ResolveInfo ri = query.get(j);
5157                    if (!ri.activityInfo.applicationInfo.packageName
5158                            .equals(ai.applicationInfo.packageName)) {
5159                        continue;
5160                    }
5161                    if (!ri.activityInfo.name.equals(ai.name)) {
5162                        continue;
5163                    }
5164                    //  Found a persistent preference that can handle the intent.
5165                    if (DEBUG_PREFERRED || debug) {
5166                        Slog.v(TAG, "Returning persistent preferred activity: " +
5167                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5168                    }
5169                    return ri;
5170                }
5171            }
5172        }
5173        return null;
5174    }
5175
5176    // TODO: handle preferred activities missing while user has amnesia
5177    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5178            List<ResolveInfo> query, int priority, boolean always,
5179            boolean removeMatches, boolean debug, int userId) {
5180        if (!sUserManager.exists(userId)) return null;
5181        flags = updateFlagsForResolve(flags, userId, intent);
5182        // writer
5183        synchronized (mPackages) {
5184            if (intent.getSelector() != null) {
5185                intent = intent.getSelector();
5186            }
5187            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5188
5189            // Try to find a matching persistent preferred activity.
5190            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5191                    debug, userId);
5192
5193            // If a persistent preferred activity matched, use it.
5194            if (pri != null) {
5195                return pri;
5196            }
5197
5198            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5199            // Get the list of preferred activities that handle the intent
5200            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5201            List<PreferredActivity> prefs = pir != null
5202                    ? pir.queryIntent(intent, resolvedType,
5203                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5204                    : null;
5205            if (prefs != null && prefs.size() > 0) {
5206                boolean changed = false;
5207                try {
5208                    // First figure out how good the original match set is.
5209                    // We will only allow preferred activities that came
5210                    // from the same match quality.
5211                    int match = 0;
5212
5213                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5214
5215                    final int N = query.size();
5216                    for (int j=0; j<N; j++) {
5217                        final ResolveInfo ri = query.get(j);
5218                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5219                                + ": 0x" + Integer.toHexString(match));
5220                        if (ri.match > match) {
5221                            match = ri.match;
5222                        }
5223                    }
5224
5225                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5226                            + Integer.toHexString(match));
5227
5228                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5229                    final int M = prefs.size();
5230                    for (int i=0; i<M; i++) {
5231                        final PreferredActivity pa = prefs.get(i);
5232                        if (DEBUG_PREFERRED || debug) {
5233                            Slog.v(TAG, "Checking PreferredActivity ds="
5234                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5235                                    + "\n  component=" + pa.mPref.mComponent);
5236                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5237                        }
5238                        if (pa.mPref.mMatch != match) {
5239                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5240                                    + Integer.toHexString(pa.mPref.mMatch));
5241                            continue;
5242                        }
5243                        // If it's not an "always" type preferred activity and that's what we're
5244                        // looking for, skip it.
5245                        if (always && !pa.mPref.mAlways) {
5246                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5247                            continue;
5248                        }
5249                        final ActivityInfo ai = getActivityInfo(
5250                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5251                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5252                                userId);
5253                        if (DEBUG_PREFERRED || debug) {
5254                            Slog.v(TAG, "Found preferred activity:");
5255                            if (ai != null) {
5256                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5257                            } else {
5258                                Slog.v(TAG, "  null");
5259                            }
5260                        }
5261                        if (ai == null) {
5262                            // This previously registered preferred activity
5263                            // component is no longer known.  Most likely an update
5264                            // to the app was installed and in the new version this
5265                            // component no longer exists.  Clean it up by removing
5266                            // it from the preferred activities list, and skip it.
5267                            Slog.w(TAG, "Removing dangling preferred activity: "
5268                                    + pa.mPref.mComponent);
5269                            pir.removeFilter(pa);
5270                            changed = true;
5271                            continue;
5272                        }
5273                        for (int j=0; j<N; j++) {
5274                            final ResolveInfo ri = query.get(j);
5275                            if (!ri.activityInfo.applicationInfo.packageName
5276                                    .equals(ai.applicationInfo.packageName)) {
5277                                continue;
5278                            }
5279                            if (!ri.activityInfo.name.equals(ai.name)) {
5280                                continue;
5281                            }
5282
5283                            if (removeMatches) {
5284                                pir.removeFilter(pa);
5285                                changed = true;
5286                                if (DEBUG_PREFERRED) {
5287                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5288                                }
5289                                break;
5290                            }
5291
5292                            // Okay we found a previously set preferred or last chosen app.
5293                            // If the result set is different from when this
5294                            // was created, we need to clear it and re-ask the
5295                            // user their preference, if we're looking for an "always" type entry.
5296                            if (always && !pa.mPref.sameSet(query)) {
5297                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5298                                        + intent + " type " + resolvedType);
5299                                if (DEBUG_PREFERRED) {
5300                                    Slog.v(TAG, "Removing preferred activity since set changed "
5301                                            + pa.mPref.mComponent);
5302                                }
5303                                pir.removeFilter(pa);
5304                                // Re-add the filter as a "last chosen" entry (!always)
5305                                PreferredActivity lastChosen = new PreferredActivity(
5306                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5307                                pir.addFilter(lastChosen);
5308                                changed = true;
5309                                return null;
5310                            }
5311
5312                            // Yay! Either the set matched or we're looking for the last chosen
5313                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5314                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5315                            return ri;
5316                        }
5317                    }
5318                } finally {
5319                    if (changed) {
5320                        if (DEBUG_PREFERRED) {
5321                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5322                        }
5323                        scheduleWritePackageRestrictionsLocked(userId);
5324                    }
5325                }
5326            }
5327        }
5328        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5329        return null;
5330    }
5331
5332    /*
5333     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5334     */
5335    @Override
5336    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5337            int targetUserId) {
5338        mContext.enforceCallingOrSelfPermission(
5339                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5340        List<CrossProfileIntentFilter> matches =
5341                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5342        if (matches != null) {
5343            int size = matches.size();
5344            for (int i = 0; i < size; i++) {
5345                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5346            }
5347        }
5348        if (hasWebURI(intent)) {
5349            // cross-profile app linking works only towards the parent.
5350            final UserInfo parent = getProfileParent(sourceUserId);
5351            synchronized(mPackages) {
5352                int flags = updateFlagsForResolve(0, parent.id, intent);
5353                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5354                        intent, resolvedType, flags, sourceUserId, parent.id);
5355                return xpDomainInfo != null;
5356            }
5357        }
5358        return false;
5359    }
5360
5361    private UserInfo getProfileParent(int userId) {
5362        final long identity = Binder.clearCallingIdentity();
5363        try {
5364            return sUserManager.getProfileParent(userId);
5365        } finally {
5366            Binder.restoreCallingIdentity(identity);
5367        }
5368    }
5369
5370    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5371            String resolvedType, int userId) {
5372        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5373        if (resolver != null) {
5374            return resolver.queryIntent(intent, resolvedType, false, userId);
5375        }
5376        return null;
5377    }
5378
5379    @Override
5380    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5381            String resolvedType, int flags, int userId) {
5382        try {
5383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5384
5385            return new ParceledListSlice<>(
5386                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5387        } finally {
5388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5389        }
5390    }
5391
5392    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5393            String resolvedType, int flags, int userId) {
5394        if (!sUserManager.exists(userId)) return Collections.emptyList();
5395        flags = updateFlagsForResolve(flags, userId, intent);
5396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5397                false /* requireFullPermission */, false /* checkShell */,
5398                "query intent activities");
5399        ComponentName comp = intent.getComponent();
5400        if (comp == null) {
5401            if (intent.getSelector() != null) {
5402                intent = intent.getSelector();
5403                comp = intent.getComponent();
5404            }
5405        }
5406
5407        if (comp != null) {
5408            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5409            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5410            if (ai != null) {
5411                final ResolveInfo ri = new ResolveInfo();
5412                ri.activityInfo = ai;
5413                list.add(ri);
5414            }
5415            return list;
5416        }
5417
5418        // reader
5419        synchronized (mPackages) {
5420            final String pkgName = intent.getPackage();
5421            if (pkgName == null) {
5422                List<CrossProfileIntentFilter> matchingFilters =
5423                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5424                // Check for results that need to skip the current profile.
5425                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5426                        resolvedType, flags, userId);
5427                if (xpResolveInfo != null) {
5428                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5429                    result.add(xpResolveInfo);
5430                    return filterIfNotSystemUser(result, userId);
5431                }
5432
5433                // Check for results in the current profile.
5434                List<ResolveInfo> result = mActivities.queryIntent(
5435                        intent, resolvedType, flags, userId);
5436                result = filterIfNotSystemUser(result, userId);
5437
5438                // Check for cross profile results.
5439                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5440                xpResolveInfo = queryCrossProfileIntents(
5441                        matchingFilters, intent, resolvedType, flags, userId,
5442                        hasNonNegativePriorityResult);
5443                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5444                    boolean isVisibleToUser = filterIfNotSystemUser(
5445                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5446                    if (isVisibleToUser) {
5447                        result.add(xpResolveInfo);
5448                        Collections.sort(result, mResolvePrioritySorter);
5449                    }
5450                }
5451                if (hasWebURI(intent)) {
5452                    CrossProfileDomainInfo xpDomainInfo = null;
5453                    final UserInfo parent = getProfileParent(userId);
5454                    if (parent != null) {
5455                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5456                                flags, userId, parent.id);
5457                    }
5458                    if (xpDomainInfo != null) {
5459                        if (xpResolveInfo != null) {
5460                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5461                            // in the result.
5462                            result.remove(xpResolveInfo);
5463                        }
5464                        if (result.size() == 0) {
5465                            result.add(xpDomainInfo.resolveInfo);
5466                            return result;
5467                        }
5468                    } else if (result.size() <= 1) {
5469                        return result;
5470                    }
5471                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5472                            xpDomainInfo, userId);
5473                    Collections.sort(result, mResolvePrioritySorter);
5474                }
5475                return result;
5476            }
5477            final PackageParser.Package pkg = mPackages.get(pkgName);
5478            if (pkg != null) {
5479                return filterIfNotSystemUser(
5480                        mActivities.queryIntentForPackage(
5481                                intent, resolvedType, flags, pkg.activities, userId),
5482                        userId);
5483            }
5484            return new ArrayList<ResolveInfo>();
5485        }
5486    }
5487
5488    private static class CrossProfileDomainInfo {
5489        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5490        ResolveInfo resolveInfo;
5491        /* Best domain verification status of the activities found in the other profile */
5492        int bestDomainVerificationStatus;
5493    }
5494
5495    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5496            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5497        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5498                sourceUserId)) {
5499            return null;
5500        }
5501        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5502                resolvedType, flags, parentUserId);
5503
5504        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5505            return null;
5506        }
5507        CrossProfileDomainInfo result = null;
5508        int size = resultTargetUser.size();
5509        for (int i = 0; i < size; i++) {
5510            ResolveInfo riTargetUser = resultTargetUser.get(i);
5511            // Intent filter verification is only for filters that specify a host. So don't return
5512            // those that handle all web uris.
5513            if (riTargetUser.handleAllWebDataURI) {
5514                continue;
5515            }
5516            String packageName = riTargetUser.activityInfo.packageName;
5517            PackageSetting ps = mSettings.mPackages.get(packageName);
5518            if (ps == null) {
5519                continue;
5520            }
5521            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5522            int status = (int)(verificationState >> 32);
5523            if (result == null) {
5524                result = new CrossProfileDomainInfo();
5525                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5526                        sourceUserId, parentUserId);
5527                result.bestDomainVerificationStatus = status;
5528            } else {
5529                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5530                        result.bestDomainVerificationStatus);
5531            }
5532        }
5533        // Don't consider matches with status NEVER across profiles.
5534        if (result != null && result.bestDomainVerificationStatus
5535                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5536            return null;
5537        }
5538        return result;
5539    }
5540
5541    /**
5542     * Verification statuses are ordered from the worse to the best, except for
5543     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5544     */
5545    private int bestDomainVerificationStatus(int status1, int status2) {
5546        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5547            return status2;
5548        }
5549        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5550            return status1;
5551        }
5552        return (int) MathUtils.max(status1, status2);
5553    }
5554
5555    private boolean isUserEnabled(int userId) {
5556        long callingId = Binder.clearCallingIdentity();
5557        try {
5558            UserInfo userInfo = sUserManager.getUserInfo(userId);
5559            return userInfo != null && userInfo.isEnabled();
5560        } finally {
5561            Binder.restoreCallingIdentity(callingId);
5562        }
5563    }
5564
5565    /**
5566     * Filter out activities with systemUserOnly flag set, when current user is not System.
5567     *
5568     * @return filtered list
5569     */
5570    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5571        if (userId == UserHandle.USER_SYSTEM) {
5572            return resolveInfos;
5573        }
5574        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5575            ResolveInfo info = resolveInfos.get(i);
5576            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5577                resolveInfos.remove(i);
5578            }
5579        }
5580        return resolveInfos;
5581    }
5582
5583    /**
5584     * @param resolveInfos list of resolve infos in descending priority order
5585     * @return if the list contains a resolve info with non-negative priority
5586     */
5587    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5588        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5589    }
5590
5591    private static boolean hasWebURI(Intent intent) {
5592        if (intent.getData() == null) {
5593            return false;
5594        }
5595        final String scheme = intent.getScheme();
5596        if (TextUtils.isEmpty(scheme)) {
5597            return false;
5598        }
5599        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5600    }
5601
5602    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5603            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5604            int userId) {
5605        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5606
5607        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5608            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5609                    candidates.size());
5610        }
5611
5612        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5613        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5614        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5615        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5616        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5617        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5618
5619        synchronized (mPackages) {
5620            final int count = candidates.size();
5621            // First, try to use linked apps. Partition the candidates into four lists:
5622            // one for the final results, one for the "do not use ever", one for "undefined status"
5623            // and finally one for "browser app type".
5624            for (int n=0; n<count; n++) {
5625                ResolveInfo info = candidates.get(n);
5626                String packageName = info.activityInfo.packageName;
5627                PackageSetting ps = mSettings.mPackages.get(packageName);
5628                if (ps != null) {
5629                    // Add to the special match all list (Browser use case)
5630                    if (info.handleAllWebDataURI) {
5631                        matchAllList.add(info);
5632                        continue;
5633                    }
5634                    // Try to get the status from User settings first
5635                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5636                    int status = (int)(packedStatus >> 32);
5637                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5638                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5639                        if (DEBUG_DOMAIN_VERIFICATION) {
5640                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5641                                    + " : linkgen=" + linkGeneration);
5642                        }
5643                        // Use link-enabled generation as preferredOrder, i.e.
5644                        // prefer newly-enabled over earlier-enabled.
5645                        info.preferredOrder = linkGeneration;
5646                        alwaysList.add(info);
5647                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5648                        if (DEBUG_DOMAIN_VERIFICATION) {
5649                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5650                        }
5651                        neverList.add(info);
5652                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5653                        if (DEBUG_DOMAIN_VERIFICATION) {
5654                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5655                        }
5656                        alwaysAskList.add(info);
5657                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5658                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5659                        if (DEBUG_DOMAIN_VERIFICATION) {
5660                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5661                        }
5662                        undefinedList.add(info);
5663                    }
5664                }
5665            }
5666
5667            // We'll want to include browser possibilities in a few cases
5668            boolean includeBrowser = false;
5669
5670            // First try to add the "always" resolution(s) for the current user, if any
5671            if (alwaysList.size() > 0) {
5672                result.addAll(alwaysList);
5673            } else {
5674                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5675                result.addAll(undefinedList);
5676                // Maybe add one for the other profile.
5677                if (xpDomainInfo != null && (
5678                        xpDomainInfo.bestDomainVerificationStatus
5679                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5680                    result.add(xpDomainInfo.resolveInfo);
5681                }
5682                includeBrowser = true;
5683            }
5684
5685            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5686            // If there were 'always' entries their preferred order has been set, so we also
5687            // back that off to make the alternatives equivalent
5688            if (alwaysAskList.size() > 0) {
5689                for (ResolveInfo i : result) {
5690                    i.preferredOrder = 0;
5691                }
5692                result.addAll(alwaysAskList);
5693                includeBrowser = true;
5694            }
5695
5696            if (includeBrowser) {
5697                // Also add browsers (all of them or only the default one)
5698                if (DEBUG_DOMAIN_VERIFICATION) {
5699                    Slog.v(TAG, "   ...including browsers in candidate set");
5700                }
5701                if ((matchFlags & MATCH_ALL) != 0) {
5702                    result.addAll(matchAllList);
5703                } else {
5704                    // Browser/generic handling case.  If there's a default browser, go straight
5705                    // to that (but only if there is no other higher-priority match).
5706                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5707                    int maxMatchPrio = 0;
5708                    ResolveInfo defaultBrowserMatch = null;
5709                    final int numCandidates = matchAllList.size();
5710                    for (int n = 0; n < numCandidates; n++) {
5711                        ResolveInfo info = matchAllList.get(n);
5712                        // track the highest overall match priority...
5713                        if (info.priority > maxMatchPrio) {
5714                            maxMatchPrio = info.priority;
5715                        }
5716                        // ...and the highest-priority default browser match
5717                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5718                            if (defaultBrowserMatch == null
5719                                    || (defaultBrowserMatch.priority < info.priority)) {
5720                                if (debug) {
5721                                    Slog.v(TAG, "Considering default browser match " + info);
5722                                }
5723                                defaultBrowserMatch = info;
5724                            }
5725                        }
5726                    }
5727                    if (defaultBrowserMatch != null
5728                            && defaultBrowserMatch.priority >= maxMatchPrio
5729                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5730                    {
5731                        if (debug) {
5732                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5733                        }
5734                        result.add(defaultBrowserMatch);
5735                    } else {
5736                        result.addAll(matchAllList);
5737                    }
5738                }
5739
5740                // If there is nothing selected, add all candidates and remove the ones that the user
5741                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5742                if (result.size() == 0) {
5743                    result.addAll(candidates);
5744                    result.removeAll(neverList);
5745                }
5746            }
5747        }
5748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5749            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5750                    result.size());
5751            for (ResolveInfo info : result) {
5752                Slog.v(TAG, "  + " + info.activityInfo);
5753            }
5754        }
5755        return result;
5756    }
5757
5758    // Returns a packed value as a long:
5759    //
5760    // high 'int'-sized word: link status: undefined/ask/never/always.
5761    // low 'int'-sized word: relative priority among 'always' results.
5762    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5763        long result = ps.getDomainVerificationStatusForUser(userId);
5764        // if none available, get the master status
5765        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5766            if (ps.getIntentFilterVerificationInfo() != null) {
5767                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5768            }
5769        }
5770        return result;
5771    }
5772
5773    private ResolveInfo querySkipCurrentProfileIntents(
5774            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775            int flags, int sourceUserId) {
5776        if (matchingFilters != null) {
5777            int size = matchingFilters.size();
5778            for (int i = 0; i < size; i ++) {
5779                CrossProfileIntentFilter filter = matchingFilters.get(i);
5780                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5781                    // Checking if there are activities in the target user that can handle the
5782                    // intent.
5783                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5784                            resolvedType, flags, sourceUserId);
5785                    if (resolveInfo != null) {
5786                        return resolveInfo;
5787                    }
5788                }
5789            }
5790        }
5791        return null;
5792    }
5793
5794    // Return matching ResolveInfo in target user if any.
5795    private ResolveInfo queryCrossProfileIntents(
5796            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5797            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5798        if (matchingFilters != null) {
5799            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5800            // match the same intent. For performance reasons, it is better not to
5801            // run queryIntent twice for the same userId
5802            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5803            int size = matchingFilters.size();
5804            for (int i = 0; i < size; i++) {
5805                CrossProfileIntentFilter filter = matchingFilters.get(i);
5806                int targetUserId = filter.getTargetUserId();
5807                boolean skipCurrentProfile =
5808                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5809                boolean skipCurrentProfileIfNoMatchFound =
5810                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5811                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5812                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5813                    // Checking if there are activities in the target user that can handle the
5814                    // intent.
5815                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5816                            resolvedType, flags, sourceUserId);
5817                    if (resolveInfo != null) return resolveInfo;
5818                    alreadyTriedUserIds.put(targetUserId, true);
5819                }
5820            }
5821        }
5822        return null;
5823    }
5824
5825    /**
5826     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5827     * will forward the intent to the filter's target user.
5828     * Otherwise, returns null.
5829     */
5830    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5831            String resolvedType, int flags, int sourceUserId) {
5832        int targetUserId = filter.getTargetUserId();
5833        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5834                resolvedType, flags, targetUserId);
5835        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5836            // If all the matches in the target profile are suspended, return null.
5837            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5838                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5839                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5840                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5841                            targetUserId);
5842                }
5843            }
5844        }
5845        return null;
5846    }
5847
5848    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5849            int sourceUserId, int targetUserId) {
5850        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5851        long ident = Binder.clearCallingIdentity();
5852        boolean targetIsProfile;
5853        try {
5854            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5855        } finally {
5856            Binder.restoreCallingIdentity(ident);
5857        }
5858        String className;
5859        if (targetIsProfile) {
5860            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5861        } else {
5862            className = FORWARD_INTENT_TO_PARENT;
5863        }
5864        ComponentName forwardingActivityComponentName = new ComponentName(
5865                mAndroidApplication.packageName, className);
5866        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5867                sourceUserId);
5868        if (!targetIsProfile) {
5869            forwardingActivityInfo.showUserIcon = targetUserId;
5870            forwardingResolveInfo.noResourceId = true;
5871        }
5872        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5873        forwardingResolveInfo.priority = 0;
5874        forwardingResolveInfo.preferredOrder = 0;
5875        forwardingResolveInfo.match = 0;
5876        forwardingResolveInfo.isDefault = true;
5877        forwardingResolveInfo.filter = filter;
5878        forwardingResolveInfo.targetUserId = targetUserId;
5879        return forwardingResolveInfo;
5880    }
5881
5882    @Override
5883    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5884            Intent[] specifics, String[] specificTypes, Intent intent,
5885            String resolvedType, int flags, int userId) {
5886        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5887                specificTypes, intent, resolvedType, flags, userId));
5888    }
5889
5890    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5891            Intent[] specifics, String[] specificTypes, Intent intent,
5892            String resolvedType, int flags, int userId) {
5893        if (!sUserManager.exists(userId)) return Collections.emptyList();
5894        flags = updateFlagsForResolve(flags, userId, intent);
5895        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5896                false /* requireFullPermission */, false /* checkShell */,
5897                "query intent activity options");
5898        final String resultsAction = intent.getAction();
5899
5900        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5901                | PackageManager.GET_RESOLVED_FILTER, userId);
5902
5903        if (DEBUG_INTENT_MATCHING) {
5904            Log.v(TAG, "Query " + intent + ": " + results);
5905        }
5906
5907        int specificsPos = 0;
5908        int N;
5909
5910        // todo: note that the algorithm used here is O(N^2).  This
5911        // isn't a problem in our current environment, but if we start running
5912        // into situations where we have more than 5 or 10 matches then this
5913        // should probably be changed to something smarter...
5914
5915        // First we go through and resolve each of the specific items
5916        // that were supplied, taking care of removing any corresponding
5917        // duplicate items in the generic resolve list.
5918        if (specifics != null) {
5919            for (int i=0; i<specifics.length; i++) {
5920                final Intent sintent = specifics[i];
5921                if (sintent == null) {
5922                    continue;
5923                }
5924
5925                if (DEBUG_INTENT_MATCHING) {
5926                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5927                }
5928
5929                String action = sintent.getAction();
5930                if (resultsAction != null && resultsAction.equals(action)) {
5931                    // If this action was explicitly requested, then don't
5932                    // remove things that have it.
5933                    action = null;
5934                }
5935
5936                ResolveInfo ri = null;
5937                ActivityInfo ai = null;
5938
5939                ComponentName comp = sintent.getComponent();
5940                if (comp == null) {
5941                    ri = resolveIntent(
5942                        sintent,
5943                        specificTypes != null ? specificTypes[i] : null,
5944                            flags, userId);
5945                    if (ri == null) {
5946                        continue;
5947                    }
5948                    if (ri == mResolveInfo) {
5949                        // ACK!  Must do something better with this.
5950                    }
5951                    ai = ri.activityInfo;
5952                    comp = new ComponentName(ai.applicationInfo.packageName,
5953                            ai.name);
5954                } else {
5955                    ai = getActivityInfo(comp, flags, userId);
5956                    if (ai == null) {
5957                        continue;
5958                    }
5959                }
5960
5961                // Look for any generic query activities that are duplicates
5962                // of this specific one, and remove them from the results.
5963                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5964                N = results.size();
5965                int j;
5966                for (j=specificsPos; j<N; j++) {
5967                    ResolveInfo sri = results.get(j);
5968                    if ((sri.activityInfo.name.equals(comp.getClassName())
5969                            && sri.activityInfo.applicationInfo.packageName.equals(
5970                                    comp.getPackageName()))
5971                        || (action != null && sri.filter.matchAction(action))) {
5972                        results.remove(j);
5973                        if (DEBUG_INTENT_MATCHING) Log.v(
5974                            TAG, "Removing duplicate item from " + j
5975                            + " due to specific " + specificsPos);
5976                        if (ri == null) {
5977                            ri = sri;
5978                        }
5979                        j--;
5980                        N--;
5981                    }
5982                }
5983
5984                // Add this specific item to its proper place.
5985                if (ri == null) {
5986                    ri = new ResolveInfo();
5987                    ri.activityInfo = ai;
5988                }
5989                results.add(specificsPos, ri);
5990                ri.specificIndex = i;
5991                specificsPos++;
5992            }
5993        }
5994
5995        // Now we go through the remaining generic results and remove any
5996        // duplicate actions that are found here.
5997        N = results.size();
5998        for (int i=specificsPos; i<N-1; i++) {
5999            final ResolveInfo rii = results.get(i);
6000            if (rii.filter == null) {
6001                continue;
6002            }
6003
6004            // Iterate over all of the actions of this result's intent
6005            // filter...  typically this should be just one.
6006            final Iterator<String> it = rii.filter.actionsIterator();
6007            if (it == null) {
6008                continue;
6009            }
6010            while (it.hasNext()) {
6011                final String action = it.next();
6012                if (resultsAction != null && resultsAction.equals(action)) {
6013                    // If this action was explicitly requested, then don't
6014                    // remove things that have it.
6015                    continue;
6016                }
6017                for (int j=i+1; j<N; j++) {
6018                    final ResolveInfo rij = results.get(j);
6019                    if (rij.filter != null && rij.filter.hasAction(action)) {
6020                        results.remove(j);
6021                        if (DEBUG_INTENT_MATCHING) Log.v(
6022                            TAG, "Removing duplicate item from " + j
6023                            + " due to action " + action + " at " + i);
6024                        j--;
6025                        N--;
6026                    }
6027                }
6028            }
6029
6030            // If the caller didn't request filter information, drop it now
6031            // so we don't have to marshall/unmarshall it.
6032            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6033                rii.filter = null;
6034            }
6035        }
6036
6037        // Filter out the caller activity if so requested.
6038        if (caller != null) {
6039            N = results.size();
6040            for (int i=0; i<N; i++) {
6041                ActivityInfo ainfo = results.get(i).activityInfo;
6042                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6043                        && caller.getClassName().equals(ainfo.name)) {
6044                    results.remove(i);
6045                    break;
6046                }
6047            }
6048        }
6049
6050        // If the caller didn't request filter information,
6051        // drop them now so we don't have to
6052        // marshall/unmarshall it.
6053        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6054            N = results.size();
6055            for (int i=0; i<N; i++) {
6056                results.get(i).filter = null;
6057            }
6058        }
6059
6060        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6061        return results;
6062    }
6063
6064    @Override
6065    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        return new ParceledListSlice<>(
6068                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6069    }
6070
6071    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6072            String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return Collections.emptyList();
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        ComponentName comp = intent.getComponent();
6076        if (comp == null) {
6077            if (intent.getSelector() != null) {
6078                intent = intent.getSelector();
6079                comp = intent.getComponent();
6080            }
6081        }
6082        if (comp != null) {
6083            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6084            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6085            if (ai != null) {
6086                ResolveInfo ri = new ResolveInfo();
6087                ri.activityInfo = ai;
6088                list.add(ri);
6089            }
6090            return list;
6091        }
6092
6093        // reader
6094        synchronized (mPackages) {
6095            String pkgName = intent.getPackage();
6096            if (pkgName == null) {
6097                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6098            }
6099            final PackageParser.Package pkg = mPackages.get(pkgName);
6100            if (pkg != null) {
6101                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6102                        userId);
6103            }
6104            return Collections.emptyList();
6105        }
6106    }
6107
6108    @Override
6109    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return null;
6111        flags = updateFlagsForResolve(flags, userId, intent);
6112        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6113        if (query != null) {
6114            if (query.size() >= 1) {
6115                // If there is more than one service with the same priority,
6116                // just arbitrarily pick the first one.
6117                return query.get(0);
6118            }
6119        }
6120        return null;
6121    }
6122
6123    @Override
6124    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        return new ParceledListSlice<>(
6127                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6128    }
6129
6130    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6131            String resolvedType, int flags, int userId) {
6132        if (!sUserManager.exists(userId)) return Collections.emptyList();
6133        flags = updateFlagsForResolve(flags, userId, intent);
6134        ComponentName comp = intent.getComponent();
6135        if (comp == null) {
6136            if (intent.getSelector() != null) {
6137                intent = intent.getSelector();
6138                comp = intent.getComponent();
6139            }
6140        }
6141        if (comp != null) {
6142            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6143            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6144            if (si != null) {
6145                final ResolveInfo ri = new ResolveInfo();
6146                ri.serviceInfo = si;
6147                list.add(ri);
6148            }
6149            return list;
6150        }
6151
6152        // reader
6153        synchronized (mPackages) {
6154            String pkgName = intent.getPackage();
6155            if (pkgName == null) {
6156                return mServices.queryIntent(intent, resolvedType, flags, userId);
6157            }
6158            final PackageParser.Package pkg = mPackages.get(pkgName);
6159            if (pkg != null) {
6160                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6161                        userId);
6162            }
6163            return Collections.emptyList();
6164        }
6165    }
6166
6167    @Override
6168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6169            String resolvedType, int flags, int userId) {
6170        return new ParceledListSlice<>(
6171                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6172    }
6173
6174    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6175            Intent intent, String resolvedType, int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return Collections.emptyList();
6177        flags = updateFlagsForResolve(flags, userId, intent);
6178        ComponentName comp = intent.getComponent();
6179        if (comp == null) {
6180            if (intent.getSelector() != null) {
6181                intent = intent.getSelector();
6182                comp = intent.getComponent();
6183            }
6184        }
6185        if (comp != null) {
6186            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6187            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6188            if (pi != null) {
6189                final ResolveInfo ri = new ResolveInfo();
6190                ri.providerInfo = pi;
6191                list.add(ri);
6192            }
6193            return list;
6194        }
6195
6196        // reader
6197        synchronized (mPackages) {
6198            String pkgName = intent.getPackage();
6199            if (pkgName == null) {
6200                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6201            }
6202            final PackageParser.Package pkg = mPackages.get(pkgName);
6203            if (pkg != null) {
6204                return mProviders.queryIntentForPackage(
6205                        intent, resolvedType, flags, pkg.providers, userId);
6206            }
6207            return Collections.emptyList();
6208        }
6209    }
6210
6211    @Override
6212    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6213        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6214        flags = updateFlagsForPackage(flags, userId, null);
6215        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6217                true /* requireFullPermission */, false /* checkShell */,
6218                "get installed packages");
6219
6220        // writer
6221        synchronized (mPackages) {
6222            ArrayList<PackageInfo> list;
6223            if (listUninstalled) {
6224                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6225                for (PackageSetting ps : mSettings.mPackages.values()) {
6226                    final PackageInfo pi;
6227                    if (ps.pkg != null) {
6228                        pi = generatePackageInfo(ps, flags, userId);
6229                    } else {
6230                        pi = generatePackageInfo(ps, flags, userId);
6231                    }
6232                    if (pi != null) {
6233                        list.add(pi);
6234                    }
6235                }
6236            } else {
6237                list = new ArrayList<PackageInfo>(mPackages.size());
6238                for (PackageParser.Package p : mPackages.values()) {
6239                    final PackageInfo pi =
6240                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6241                    if (pi != null) {
6242                        list.add(pi);
6243                    }
6244                }
6245            }
6246
6247            return new ParceledListSlice<PackageInfo>(list);
6248        }
6249    }
6250
6251    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6252            String[] permissions, boolean[] tmp, int flags, int userId) {
6253        int numMatch = 0;
6254        final PermissionsState permissionsState = ps.getPermissionsState();
6255        for (int i=0; i<permissions.length; i++) {
6256            final String permission = permissions[i];
6257            if (permissionsState.hasPermission(permission, userId)) {
6258                tmp[i] = true;
6259                numMatch++;
6260            } else {
6261                tmp[i] = false;
6262            }
6263        }
6264        if (numMatch == 0) {
6265            return;
6266        }
6267        final PackageInfo pi;
6268        if (ps.pkg != null) {
6269            pi = generatePackageInfo(ps, flags, userId);
6270        } else {
6271            pi = generatePackageInfo(ps, flags, userId);
6272        }
6273        // The above might return null in cases of uninstalled apps or install-state
6274        // skew across users/profiles.
6275        if (pi != null) {
6276            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6277                if (numMatch == permissions.length) {
6278                    pi.requestedPermissions = permissions;
6279                } else {
6280                    pi.requestedPermissions = new String[numMatch];
6281                    numMatch = 0;
6282                    for (int i=0; i<permissions.length; i++) {
6283                        if (tmp[i]) {
6284                            pi.requestedPermissions[numMatch] = permissions[i];
6285                            numMatch++;
6286                        }
6287                    }
6288                }
6289            }
6290            list.add(pi);
6291        }
6292    }
6293
6294    @Override
6295    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6296            String[] permissions, int flags, int userId) {
6297        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6298        flags = updateFlagsForPackage(flags, userId, permissions);
6299        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6300
6301        // writer
6302        synchronized (mPackages) {
6303            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6304            boolean[] tmpBools = new boolean[permissions.length];
6305            if (listUninstalled) {
6306                for (PackageSetting ps : mSettings.mPackages.values()) {
6307                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6308                }
6309            } else {
6310                for (PackageParser.Package pkg : mPackages.values()) {
6311                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6312                    if (ps != null) {
6313                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6314                                userId);
6315                    }
6316                }
6317            }
6318
6319            return new ParceledListSlice<PackageInfo>(list);
6320        }
6321    }
6322
6323    @Override
6324    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6325        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6326        flags = updateFlagsForApplication(flags, userId, null);
6327        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6328
6329        // writer
6330        synchronized (mPackages) {
6331            ArrayList<ApplicationInfo> list;
6332            if (listUninstalled) {
6333                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6334                for (PackageSetting ps : mSettings.mPackages.values()) {
6335                    ApplicationInfo ai;
6336                    if (ps.pkg != null) {
6337                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6338                                ps.readUserState(userId), userId);
6339                    } else {
6340                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6341                    }
6342                    if (ai != null) {
6343                        list.add(ai);
6344                    }
6345                }
6346            } else {
6347                list = new ArrayList<ApplicationInfo>(mPackages.size());
6348                for (PackageParser.Package p : mPackages.values()) {
6349                    if (p.mExtras != null) {
6350                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6351                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6352                        if (ai != null) {
6353                            list.add(ai);
6354                        }
6355                    }
6356                }
6357            }
6358
6359            return new ParceledListSlice<ApplicationInfo>(list);
6360        }
6361    }
6362
6363    @Override
6364    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6365        if (DISABLE_EPHEMERAL_APPS) {
6366            return null;
6367        }
6368
6369        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6370                "getEphemeralApplications");
6371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6372                true /* requireFullPermission */, false /* checkShell */,
6373                "getEphemeralApplications");
6374        synchronized (mPackages) {
6375            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6376                    .getEphemeralApplicationsLPw(userId);
6377            if (ephemeralApps != null) {
6378                return new ParceledListSlice<>(ephemeralApps);
6379            }
6380        }
6381        return null;
6382    }
6383
6384    @Override
6385    public boolean isEphemeralApplication(String packageName, int userId) {
6386        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6387                true /* requireFullPermission */, false /* checkShell */,
6388                "isEphemeral");
6389        if (DISABLE_EPHEMERAL_APPS) {
6390            return false;
6391        }
6392
6393        if (!isCallerSameApp(packageName)) {
6394            return false;
6395        }
6396        synchronized (mPackages) {
6397            PackageParser.Package pkg = mPackages.get(packageName);
6398            if (pkg != null) {
6399                return pkg.applicationInfo.isEphemeralApp();
6400            }
6401        }
6402        return false;
6403    }
6404
6405    @Override
6406    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6407        if (DISABLE_EPHEMERAL_APPS) {
6408            return null;
6409        }
6410
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, false /* checkShell */,
6413                "getCookie");
6414        if (!isCallerSameApp(packageName)) {
6415            return null;
6416        }
6417        synchronized (mPackages) {
6418            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6419                    packageName, userId);
6420        }
6421    }
6422
6423    @Override
6424    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6425        if (DISABLE_EPHEMERAL_APPS) {
6426            return true;
6427        }
6428
6429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6430                true /* requireFullPermission */, true /* checkShell */,
6431                "setCookie");
6432        if (!isCallerSameApp(packageName)) {
6433            return false;
6434        }
6435        synchronized (mPackages) {
6436            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6437                    packageName, cookie, userId);
6438        }
6439    }
6440
6441    @Override
6442    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6443        if (DISABLE_EPHEMERAL_APPS) {
6444            return null;
6445        }
6446
6447        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6448                "getEphemeralApplicationIcon");
6449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6450                true /* requireFullPermission */, false /* checkShell */,
6451                "getEphemeralApplicationIcon");
6452        synchronized (mPackages) {
6453            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6454                    packageName, userId);
6455        }
6456    }
6457
6458    private boolean isCallerSameApp(String packageName) {
6459        PackageParser.Package pkg = mPackages.get(packageName);
6460        return pkg != null
6461                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6462    }
6463
6464    @Override
6465    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6466        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6467    }
6468
6469    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6470        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6471
6472        // reader
6473        synchronized (mPackages) {
6474            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6475            final int userId = UserHandle.getCallingUserId();
6476            while (i.hasNext()) {
6477                final PackageParser.Package p = i.next();
6478                if (p.applicationInfo == null) continue;
6479
6480                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6481                        && !p.applicationInfo.isDirectBootAware();
6482                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6483                        && p.applicationInfo.isDirectBootAware();
6484
6485                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6486                        && (!mSafeMode || isSystemApp(p))
6487                        && (matchesUnaware || matchesAware)) {
6488                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6489                    if (ps != null) {
6490                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6491                                ps.readUserState(userId), userId);
6492                        if (ai != null) {
6493                            finalList.add(ai);
6494                        }
6495                    }
6496                }
6497            }
6498        }
6499
6500        return finalList;
6501    }
6502
6503    @Override
6504    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6505        if (!sUserManager.exists(userId)) return null;
6506        flags = updateFlagsForComponent(flags, userId, name);
6507        // reader
6508        synchronized (mPackages) {
6509            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6510            PackageSetting ps = provider != null
6511                    ? mSettings.mPackages.get(provider.owner.packageName)
6512                    : null;
6513            return ps != null
6514                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6515                    ? PackageParser.generateProviderInfo(provider, flags,
6516                            ps.readUserState(userId), userId)
6517                    : null;
6518        }
6519    }
6520
6521    /**
6522     * @deprecated
6523     */
6524    @Deprecated
6525    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6526        // reader
6527        synchronized (mPackages) {
6528            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6529                    .entrySet().iterator();
6530            final int userId = UserHandle.getCallingUserId();
6531            while (i.hasNext()) {
6532                Map.Entry<String, PackageParser.Provider> entry = i.next();
6533                PackageParser.Provider p = entry.getValue();
6534                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6535
6536                if (ps != null && p.syncable
6537                        && (!mSafeMode || (p.info.applicationInfo.flags
6538                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6539                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6540                            ps.readUserState(userId), userId);
6541                    if (info != null) {
6542                        outNames.add(entry.getKey());
6543                        outInfo.add(info);
6544                    }
6545                }
6546            }
6547        }
6548    }
6549
6550    @Override
6551    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6552            int uid, int flags) {
6553        final int userId = processName != null ? UserHandle.getUserId(uid)
6554                : UserHandle.getCallingUserId();
6555        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6556        flags = updateFlagsForComponent(flags, userId, processName);
6557
6558        ArrayList<ProviderInfo> finalList = null;
6559        // reader
6560        synchronized (mPackages) {
6561            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6562            while (i.hasNext()) {
6563                final PackageParser.Provider p = i.next();
6564                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6565                if (ps != null && p.info.authority != null
6566                        && (processName == null
6567                                || (p.info.processName.equals(processName)
6568                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6569                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6570                    if (finalList == null) {
6571                        finalList = new ArrayList<ProviderInfo>(3);
6572                    }
6573                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6574                            ps.readUserState(userId), userId);
6575                    if (info != null) {
6576                        finalList.add(info);
6577                    }
6578                }
6579            }
6580        }
6581
6582        if (finalList != null) {
6583            Collections.sort(finalList, mProviderInitOrderSorter);
6584            return new ParceledListSlice<ProviderInfo>(finalList);
6585        }
6586
6587        return ParceledListSlice.emptyList();
6588    }
6589
6590    @Override
6591    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6592        // reader
6593        synchronized (mPackages) {
6594            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6595            return PackageParser.generateInstrumentationInfo(i, flags);
6596        }
6597    }
6598
6599    @Override
6600    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6601            String targetPackage, int flags) {
6602        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6603    }
6604
6605    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6606            int flags) {
6607        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6608
6609        // reader
6610        synchronized (mPackages) {
6611            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6612            while (i.hasNext()) {
6613                final PackageParser.Instrumentation p = i.next();
6614                if (targetPackage == null
6615                        || targetPackage.equals(p.info.targetPackage)) {
6616                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6617                            flags);
6618                    if (ii != null) {
6619                        finalList.add(ii);
6620                    }
6621                }
6622            }
6623        }
6624
6625        return finalList;
6626    }
6627
6628    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6629        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6630        if (overlays == null) {
6631            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6632            return;
6633        }
6634        for (PackageParser.Package opkg : overlays.values()) {
6635            // Not much to do if idmap fails: we already logged the error
6636            // and we certainly don't want to abort installation of pkg simply
6637            // because an overlay didn't fit properly. For these reasons,
6638            // ignore the return value of createIdmapForPackagePairLI.
6639            createIdmapForPackagePairLI(pkg, opkg);
6640        }
6641    }
6642
6643    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6644            PackageParser.Package opkg) {
6645        if (!opkg.mTrustedOverlay) {
6646            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6647                    opkg.baseCodePath + ": overlay not trusted");
6648            return false;
6649        }
6650        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6651        if (overlaySet == null) {
6652            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6653                    opkg.baseCodePath + " but target package has no known overlays");
6654            return false;
6655        }
6656        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6657        // TODO: generate idmap for split APKs
6658        try {
6659            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6660        } catch (InstallerException e) {
6661            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6662                    + opkg.baseCodePath);
6663            return false;
6664        }
6665        PackageParser.Package[] overlayArray =
6666            overlaySet.values().toArray(new PackageParser.Package[0]);
6667        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6668            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6669                return p1.mOverlayPriority - p2.mOverlayPriority;
6670            }
6671        };
6672        Arrays.sort(overlayArray, cmp);
6673
6674        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6675        int i = 0;
6676        for (PackageParser.Package p : overlayArray) {
6677            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6678        }
6679        return true;
6680    }
6681
6682    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6684        try {
6685            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6692        final File[] files = dir.listFiles();
6693        if (ArrayUtils.isEmpty(files)) {
6694            Log.d(TAG, "No files in app dir " + dir);
6695            return;
6696        }
6697
6698        if (DEBUG_PACKAGE_SCANNING) {
6699            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6700                    + " flags=0x" + Integer.toHexString(parseFlags));
6701        }
6702
6703        for (File file : files) {
6704            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6705                    && !PackageInstallerService.isStageName(file.getName());
6706            if (!isPackage) {
6707                // Ignore entries which are not packages
6708                continue;
6709            }
6710            try {
6711                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6712                        scanFlags, currentTime, null);
6713            } catch (PackageManagerException e) {
6714                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6715
6716                // Delete invalid userdata apps
6717                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6718                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6719                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6720                    removeCodePathLI(file);
6721                }
6722            }
6723        }
6724    }
6725
6726    private static File getSettingsProblemFile() {
6727        File dataDir = Environment.getDataDirectory();
6728        File systemDir = new File(dataDir, "system");
6729        File fname = new File(systemDir, "uiderrors.txt");
6730        return fname;
6731    }
6732
6733    static void reportSettingsProblem(int priority, String msg) {
6734        logCriticalInfo(priority, msg);
6735    }
6736
6737    static void logCriticalInfo(int priority, String msg) {
6738        Slog.println(priority, TAG, msg);
6739        EventLogTags.writePmCriticalInfo(msg);
6740        try {
6741            File fname = getSettingsProblemFile();
6742            FileOutputStream out = new FileOutputStream(fname, true);
6743            PrintWriter pw = new FastPrintWriter(out);
6744            SimpleDateFormat formatter = new SimpleDateFormat();
6745            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6746            pw.println(dateString + ": " + msg);
6747            pw.close();
6748            FileUtils.setPermissions(
6749                    fname.toString(),
6750                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6751                    -1, -1);
6752        } catch (java.io.IOException e) {
6753        }
6754    }
6755
6756    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6757            final int policyFlags) throws PackageManagerException {
6758        if (ps != null
6759                && ps.codePath.equals(srcFile)
6760                && ps.timeStamp == srcFile.lastModified()
6761                && !isCompatSignatureUpdateNeeded(pkg)
6762                && !isRecoverSignatureUpdateNeeded(pkg)) {
6763            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6764            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6765            ArraySet<PublicKey> signingKs;
6766            synchronized (mPackages) {
6767                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6768            }
6769            if (ps.signatures.mSignatures != null
6770                    && ps.signatures.mSignatures.length != 0
6771                    && signingKs != null) {
6772                // Optimization: reuse the existing cached certificates
6773                // if the package appears to be unchanged.
6774                pkg.mSignatures = ps.signatures.mSignatures;
6775                pkg.mSigningKeys = signingKs;
6776                return;
6777            }
6778
6779            Slog.w(TAG, "PackageSetting for " + ps.name
6780                    + " is missing signatures.  Collecting certs again to recover them.");
6781        } else {
6782            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6783        }
6784
6785        try {
6786            PackageParser.collectCertificates(pkg, policyFlags);
6787        } catch (PackageParserException e) {
6788            throw PackageManagerException.from(e);
6789        }
6790    }
6791
6792    /**
6793     *  Traces a package scan.
6794     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6795     */
6796    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6797            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6798        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6799        try {
6800            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6801        } finally {
6802            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6803        }
6804    }
6805
6806    /**
6807     *  Scans a package and returns the newly parsed package.
6808     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6809     */
6810    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6811            long currentTime, UserHandle user) throws PackageManagerException {
6812        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6813        PackageParser pp = new PackageParser();
6814        pp.setSeparateProcesses(mSeparateProcesses);
6815        pp.setOnlyCoreApps(mOnlyCore);
6816        pp.setDisplayMetrics(mMetrics);
6817
6818        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6819            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6820        }
6821
6822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6823        final PackageParser.Package pkg;
6824        try {
6825            pkg = pp.parsePackage(scanFile, parseFlags);
6826        } catch (PackageParserException e) {
6827            throw PackageManagerException.from(e);
6828        } finally {
6829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6830        }
6831
6832        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6833    }
6834
6835    /**
6836     *  Scans a package and returns the newly parsed package.
6837     *  @throws PackageManagerException on a parse error.
6838     */
6839    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6840            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6841            throws PackageManagerException {
6842        // If the package has children and this is the first dive in the function
6843        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6844        // packages (parent and children) would be successfully scanned before the
6845        // actual scan since scanning mutates internal state and we want to atomically
6846        // install the package and its children.
6847        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6848            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6849                scanFlags |= SCAN_CHECK_ONLY;
6850            }
6851        } else {
6852            scanFlags &= ~SCAN_CHECK_ONLY;
6853        }
6854
6855        // Scan the parent
6856        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6857                scanFlags, currentTime, user);
6858
6859        // Scan the children
6860        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6861        for (int i = 0; i < childCount; i++) {
6862            PackageParser.Package childPackage = pkg.childPackages.get(i);
6863            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6864                    currentTime, user);
6865        }
6866
6867
6868        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6869            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6870        }
6871
6872        return scannedPkg;
6873    }
6874
6875    /**
6876     *  Scans a package and returns the newly parsed package.
6877     *  @throws PackageManagerException on a parse error.
6878     */
6879    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6880            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6881            throws PackageManagerException {
6882        PackageSetting ps = null;
6883        PackageSetting updatedPkg;
6884        // reader
6885        synchronized (mPackages) {
6886            // Look to see if we already know about this package.
6887            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6888            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6889                // This package has been renamed to its original name.  Let's
6890                // use that.
6891                ps = mSettings.peekPackageLPr(oldName);
6892            }
6893            // If there was no original package, see one for the real package name.
6894            if (ps == null) {
6895                ps = mSettings.peekPackageLPr(pkg.packageName);
6896            }
6897            // Check to see if this package could be hiding/updating a system
6898            // package.  Must look for it either under the original or real
6899            // package name depending on our state.
6900            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6901            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6902
6903            // If this is a package we don't know about on the system partition, we
6904            // may need to remove disabled child packages on the system partition
6905            // or may need to not add child packages if the parent apk is updated
6906            // on the data partition and no longer defines this child package.
6907            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6908                // If this is a parent package for an updated system app and this system
6909                // app got an OTA update which no longer defines some of the child packages
6910                // we have to prune them from the disabled system packages.
6911                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6912                if (disabledPs != null) {
6913                    final int scannedChildCount = (pkg.childPackages != null)
6914                            ? pkg.childPackages.size() : 0;
6915                    final int disabledChildCount = disabledPs.childPackageNames != null
6916                            ? disabledPs.childPackageNames.size() : 0;
6917                    for (int i = 0; i < disabledChildCount; i++) {
6918                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6919                        boolean disabledPackageAvailable = false;
6920                        for (int j = 0; j < scannedChildCount; j++) {
6921                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6922                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6923                                disabledPackageAvailable = true;
6924                                break;
6925                            }
6926                         }
6927                         if (!disabledPackageAvailable) {
6928                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6929                         }
6930                    }
6931                }
6932            }
6933        }
6934
6935        boolean updatedPkgBetter = false;
6936        // First check if this is a system package that may involve an update
6937        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6938            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6939            // it needs to drop FLAG_PRIVILEGED.
6940            if (locationIsPrivileged(scanFile)) {
6941                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6942            } else {
6943                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6944            }
6945
6946            if (ps != null && !ps.codePath.equals(scanFile)) {
6947                // The path has changed from what was last scanned...  check the
6948                // version of the new path against what we have stored to determine
6949                // what to do.
6950                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6951                if (pkg.mVersionCode <= ps.versionCode) {
6952                    // The system package has been updated and the code path does not match
6953                    // Ignore entry. Skip it.
6954                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6955                            + " ignored: updated version " + ps.versionCode
6956                            + " better than this " + pkg.mVersionCode);
6957                    if (!updatedPkg.codePath.equals(scanFile)) {
6958                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6959                                + ps.name + " changing from " + updatedPkg.codePathString
6960                                + " to " + scanFile);
6961                        updatedPkg.codePath = scanFile;
6962                        updatedPkg.codePathString = scanFile.toString();
6963                        updatedPkg.resourcePath = scanFile;
6964                        updatedPkg.resourcePathString = scanFile.toString();
6965                    }
6966                    updatedPkg.pkg = pkg;
6967                    updatedPkg.versionCode = pkg.mVersionCode;
6968
6969                    // Update the disabled system child packages to point to the package too.
6970                    final int childCount = updatedPkg.childPackageNames != null
6971                            ? updatedPkg.childPackageNames.size() : 0;
6972                    for (int i = 0; i < childCount; i++) {
6973                        String childPackageName = updatedPkg.childPackageNames.get(i);
6974                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6975                                childPackageName);
6976                        if (updatedChildPkg != null) {
6977                            updatedChildPkg.pkg = pkg;
6978                            updatedChildPkg.versionCode = pkg.mVersionCode;
6979                        }
6980                    }
6981
6982                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6983                            + scanFile + " ignored: updated version " + ps.versionCode
6984                            + " better than this " + pkg.mVersionCode);
6985                } else {
6986                    // The current app on the system partition is better than
6987                    // what we have updated to on the data partition; switch
6988                    // back to the system partition version.
6989                    // At this point, its safely assumed that package installation for
6990                    // apps in system partition will go through. If not there won't be a working
6991                    // version of the app
6992                    // writer
6993                    synchronized (mPackages) {
6994                        // Just remove the loaded entries from package lists.
6995                        mPackages.remove(ps.name);
6996                    }
6997
6998                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6999                            + " reverting from " + ps.codePathString
7000                            + ": new version " + pkg.mVersionCode
7001                            + " better than installed " + ps.versionCode);
7002
7003                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7004                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7005                    synchronized (mInstallLock) {
7006                        args.cleanUpResourcesLI();
7007                    }
7008                    synchronized (mPackages) {
7009                        mSettings.enableSystemPackageLPw(ps.name);
7010                    }
7011                    updatedPkgBetter = true;
7012                }
7013            }
7014        }
7015
7016        if (updatedPkg != null) {
7017            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7018            // initially
7019            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7020
7021            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7022            // flag set initially
7023            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7024                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7025            }
7026        }
7027
7028        // Verify certificates against what was last scanned
7029        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7030
7031        /*
7032         * A new system app appeared, but we already had a non-system one of the
7033         * same name installed earlier.
7034         */
7035        boolean shouldHideSystemApp = false;
7036        if (updatedPkg == null && ps != null
7037                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7038            /*
7039             * Check to make sure the signatures match first. If they don't,
7040             * wipe the installed application and its data.
7041             */
7042            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7043                    != PackageManager.SIGNATURE_MATCH) {
7044                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7045                        + " signatures don't match existing userdata copy; removing");
7046                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7047                        "scanPackageInternalLI")) {
7048                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7049                }
7050                ps = null;
7051            } else {
7052                /*
7053                 * If the newly-added system app is an older version than the
7054                 * already installed version, hide it. It will be scanned later
7055                 * and re-added like an update.
7056                 */
7057                if (pkg.mVersionCode <= ps.versionCode) {
7058                    shouldHideSystemApp = true;
7059                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7060                            + " but new version " + pkg.mVersionCode + " better than installed "
7061                            + ps.versionCode + "; hiding system");
7062                } else {
7063                    /*
7064                     * The newly found system app is a newer version that the
7065                     * one previously installed. Simply remove the
7066                     * already-installed application and replace it with our own
7067                     * while keeping the application data.
7068                     */
7069                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7070                            + " reverting from " + ps.codePathString + ": new version "
7071                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7072                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7073                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7074                    synchronized (mInstallLock) {
7075                        args.cleanUpResourcesLI();
7076                    }
7077                }
7078            }
7079        }
7080
7081        // The apk is forward locked (not public) if its code and resources
7082        // are kept in different files. (except for app in either system or
7083        // vendor path).
7084        // TODO grab this value from PackageSettings
7085        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7086            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7087                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7088            }
7089        }
7090
7091        // TODO: extend to support forward-locked splits
7092        String resourcePath = null;
7093        String baseResourcePath = null;
7094        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7095            if (ps != null && ps.resourcePathString != null) {
7096                resourcePath = ps.resourcePathString;
7097                baseResourcePath = ps.resourcePathString;
7098            } else {
7099                // Should not happen at all. Just log an error.
7100                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7101            }
7102        } else {
7103            resourcePath = pkg.codePath;
7104            baseResourcePath = pkg.baseCodePath;
7105        }
7106
7107        // Set application objects path explicitly.
7108        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7109        pkg.setApplicationInfoCodePath(pkg.codePath);
7110        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7111        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7112        pkg.setApplicationInfoResourcePath(resourcePath);
7113        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7114        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7115
7116        // Note that we invoke the following method only if we are about to unpack an application
7117        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7118                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7119
7120        /*
7121         * If the system app should be overridden by a previously installed
7122         * data, hide the system app now and let the /data/app scan pick it up
7123         * again.
7124         */
7125        if (shouldHideSystemApp) {
7126            synchronized (mPackages) {
7127                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7128            }
7129        }
7130
7131        return scannedPkg;
7132    }
7133
7134    private static String fixProcessName(String defProcessName,
7135            String processName, int uid) {
7136        if (processName == null) {
7137            return defProcessName;
7138        }
7139        return processName;
7140    }
7141
7142    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7143            throws PackageManagerException {
7144        if (pkgSetting.signatures.mSignatures != null) {
7145            // Already existing package. Make sure signatures match
7146            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7147                    == PackageManager.SIGNATURE_MATCH;
7148            if (!match) {
7149                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7150                        == PackageManager.SIGNATURE_MATCH;
7151            }
7152            if (!match) {
7153                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7154                        == PackageManager.SIGNATURE_MATCH;
7155            }
7156            if (!match) {
7157                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7158                        + pkg.packageName + " signatures do not match the "
7159                        + "previously installed version; ignoring!");
7160            }
7161        }
7162
7163        // Check for shared user signatures
7164        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7165            // Already existing package. Make sure signatures match
7166            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7167                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7168            if (!match) {
7169                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7170                        == PackageManager.SIGNATURE_MATCH;
7171            }
7172            if (!match) {
7173                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7174                        == PackageManager.SIGNATURE_MATCH;
7175            }
7176            if (!match) {
7177                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7178                        "Package " + pkg.packageName
7179                        + " has no signatures that match those in shared user "
7180                        + pkgSetting.sharedUser.name + "; ignoring!");
7181            }
7182        }
7183    }
7184
7185    /**
7186     * Enforces that only the system UID or root's UID can call a method exposed
7187     * via Binder.
7188     *
7189     * @param message used as message if SecurityException is thrown
7190     * @throws SecurityException if the caller is not system or root
7191     */
7192    private static final void enforceSystemOrRoot(String message) {
7193        final int uid = Binder.getCallingUid();
7194        if (uid != Process.SYSTEM_UID && uid != 0) {
7195            throw new SecurityException(message);
7196        }
7197    }
7198
7199    @Override
7200    public void performFstrimIfNeeded() {
7201        enforceSystemOrRoot("Only the system can request fstrim");
7202
7203        // Before everything else, see whether we need to fstrim.
7204        try {
7205            IMountService ms = PackageHelper.getMountService();
7206            if (ms != null) {
7207                final boolean isUpgrade = isUpgrade();
7208                boolean doTrim = isUpgrade;
7209                if (doTrim) {
7210                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7211                } else {
7212                    final long interval = android.provider.Settings.Global.getLong(
7213                            mContext.getContentResolver(),
7214                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7215                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7216                    if (interval > 0) {
7217                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7218                        if (timeSinceLast > interval) {
7219                            doTrim = true;
7220                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7221                                    + "; running immediately");
7222                        }
7223                    }
7224                }
7225                if (doTrim) {
7226                    if (!isFirstBoot()) {
7227                        try {
7228                            ActivityManagerNative.getDefault().showBootMessage(
7229                                    mContext.getResources().getString(
7230                                            R.string.android_upgrading_fstrim), true);
7231                        } catch (RemoteException e) {
7232                        }
7233                    }
7234                    ms.runMaintenance();
7235                }
7236            } else {
7237                Slog.e(TAG, "Mount service unavailable!");
7238            }
7239        } catch (RemoteException e) {
7240            // Can't happen; MountService is local
7241        }
7242    }
7243
7244    @Override
7245    public void updatePackagesIfNeeded() {
7246        enforceSystemOrRoot("Only the system can request package update");
7247
7248        // We need to re-extract after an OTA.
7249        boolean causeUpgrade = isUpgrade();
7250
7251        // First boot or factory reset.
7252        // Note: we also handle devices that are upgrading to N right now as if it is their
7253        //       first boot, as they do not have profile data.
7254        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7255
7256        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7257        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7258
7259        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7260            return;
7261        }
7262
7263        List<PackageParser.Package> pkgs;
7264        synchronized (mPackages) {
7265            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7266        }
7267
7268        final long startTime = System.nanoTime();
7269        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7271
7272        final int elapsedTimeSeconds =
7273                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7274
7275        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7276        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7277        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7278        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7279        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7280    }
7281
7282    /**
7283     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7284     * containing statistics about the invocation. The array consists of three elements,
7285     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7286     * and {@code numberOfPackagesFailed}.
7287     */
7288    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7289            String compilerFilter) {
7290
7291        int numberOfPackagesVisited = 0;
7292        int numberOfPackagesOptimized = 0;
7293        int numberOfPackagesSkipped = 0;
7294        int numberOfPackagesFailed = 0;
7295        final int numberOfPackagesToDexopt = pkgs.size();
7296
7297        for (PackageParser.Package pkg : pkgs) {
7298            numberOfPackagesVisited++;
7299
7300            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7301                if (DEBUG_DEXOPT) {
7302                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7303                }
7304                numberOfPackagesSkipped++;
7305                continue;
7306            }
7307
7308            if (DEBUG_DEXOPT) {
7309                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7310                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7311            }
7312
7313            if (showDialog) {
7314                try {
7315                    ActivityManagerNative.getDefault().showBootMessage(
7316                            mContext.getResources().getString(R.string.android_upgrading_apk,
7317                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7318                } catch (RemoteException e) {
7319                }
7320            }
7321
7322            // checkProfiles is false to avoid merging profiles during boot which
7323            // might interfere with background compilation (b/28612421).
7324            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7325            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7326            // trade-off worth doing to save boot time work.
7327            int dexOptStatus = performDexOptTraced(pkg.packageName,
7328                    false /* checkProfiles */,
7329                    compilerFilter,
7330                    false /* force */);
7331            switch (dexOptStatus) {
7332                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7333                    numberOfPackagesOptimized++;
7334                    break;
7335                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7336                    numberOfPackagesSkipped++;
7337                    break;
7338                case PackageDexOptimizer.DEX_OPT_FAILED:
7339                    numberOfPackagesFailed++;
7340                    break;
7341                default:
7342                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7343                    break;
7344            }
7345        }
7346
7347        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7348                numberOfPackagesFailed };
7349    }
7350
7351    @Override
7352    public void notifyPackageUse(String packageName, int reason) {
7353        synchronized (mPackages) {
7354            PackageParser.Package p = mPackages.get(packageName);
7355            if (p == null) {
7356                return;
7357            }
7358            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7359        }
7360    }
7361
7362    // TODO: this is not used nor needed. Delete it.
7363    @Override
7364    public boolean performDexOptIfNeeded(String packageName) {
7365        int dexOptStatus = performDexOptTraced(packageName,
7366                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7367        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7368    }
7369
7370    @Override
7371    public boolean performDexOpt(String packageName,
7372            boolean checkProfiles, int compileReason, boolean force) {
7373        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7374                getCompilerFilterForReason(compileReason), force);
7375        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7376    }
7377
7378    @Override
7379    public boolean performDexOptMode(String packageName,
7380            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7381        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7382                targetCompilerFilter, force);
7383        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7384    }
7385
7386    private int performDexOptTraced(String packageName,
7387                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7389        try {
7390            return performDexOptInternal(packageName, checkProfiles,
7391                    targetCompilerFilter, force);
7392        } finally {
7393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394        }
7395    }
7396
7397    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7398    // if the package can now be considered up to date for the given filter.
7399    private int performDexOptInternal(String packageName,
7400                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7401        PackageParser.Package p;
7402        synchronized (mPackages) {
7403            p = mPackages.get(packageName);
7404            if (p == null) {
7405                // Package could not be found. Report failure.
7406                return PackageDexOptimizer.DEX_OPT_FAILED;
7407            }
7408            mPackageUsage.write(false);
7409        }
7410        long callingId = Binder.clearCallingIdentity();
7411        try {
7412            synchronized (mInstallLock) {
7413                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7414                        targetCompilerFilter, force);
7415            }
7416        } finally {
7417            Binder.restoreCallingIdentity(callingId);
7418        }
7419    }
7420
7421    public ArraySet<String> getOptimizablePackages() {
7422        ArraySet<String> pkgs = new ArraySet<String>();
7423        synchronized (mPackages) {
7424            for (PackageParser.Package p : mPackages.values()) {
7425                if (PackageDexOptimizer.canOptimizePackage(p)) {
7426                    pkgs.add(p.packageName);
7427                }
7428            }
7429        }
7430        return pkgs;
7431    }
7432
7433    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7434            boolean checkProfiles, String targetCompilerFilter,
7435            boolean force) {
7436        // Select the dex optimizer based on the force parameter.
7437        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7438        //       allocate an object here.
7439        PackageDexOptimizer pdo = force
7440                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7441                : mPackageDexOptimizer;
7442
7443        // Optimize all dependencies first. Note: we ignore the return value and march on
7444        // on errors.
7445        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7446        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7447        if (!deps.isEmpty()) {
7448            for (PackageParser.Package depPackage : deps) {
7449                // TODO: Analyze and investigate if we (should) profile libraries.
7450                // Currently this will do a full compilation of the library by default.
7451                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7452                        false /* checkProfiles */,
7453                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7454            }
7455        }
7456        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7457                targetCompilerFilter);
7458    }
7459
7460    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7461        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7462            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7463            Set<String> collectedNames = new HashSet<>();
7464            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7465
7466            retValue.remove(p);
7467
7468            return retValue;
7469        } else {
7470            return Collections.emptyList();
7471        }
7472    }
7473
7474    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7475            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7476        if (!collectedNames.contains(p.packageName)) {
7477            collectedNames.add(p.packageName);
7478            collected.add(p);
7479
7480            if (p.usesLibraries != null) {
7481                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7482            }
7483            if (p.usesOptionalLibraries != null) {
7484                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7485                        collectedNames);
7486            }
7487        }
7488    }
7489
7490    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7491            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7492        for (String libName : libs) {
7493            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7494            if (libPkg != null) {
7495                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7496            }
7497        }
7498    }
7499
7500    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7501        synchronized (mPackages) {
7502            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7503            if (lib != null && lib.apk != null) {
7504                return mPackages.get(lib.apk);
7505            }
7506        }
7507        return null;
7508    }
7509
7510    public void shutdown() {
7511        mPackageUsage.write(true);
7512    }
7513
7514    @Override
7515    public void dumpProfiles(String packageName) {
7516        PackageParser.Package pkg;
7517        synchronized (mPackages) {
7518            pkg = mPackages.get(packageName);
7519            if (pkg == null) {
7520                throw new IllegalArgumentException("Unknown package: " + packageName);
7521            }
7522        }
7523        /* Only the shell, root, or the app user should be able to dump profiles. */
7524        int callingUid = Binder.getCallingUid();
7525        if (callingUid != Process.SHELL_UID &&
7526            callingUid != Process.ROOT_UID &&
7527            callingUid != pkg.applicationInfo.uid) {
7528            throw new SecurityException("dumpProfiles");
7529        }
7530
7531        synchronized (mInstallLock) {
7532            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7533            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7534            try {
7535                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7536                String gid = Integer.toString(sharedGid);
7537                String codePaths = TextUtils.join(";", allCodePaths);
7538                mInstaller.dumpProfiles(gid, packageName, codePaths);
7539            } catch (InstallerException e) {
7540                Slog.w(TAG, "Failed to dump profiles", e);
7541            }
7542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7543        }
7544    }
7545
7546    @Override
7547    public void forceDexOpt(String packageName) {
7548        enforceSystemOrRoot("forceDexOpt");
7549
7550        PackageParser.Package pkg;
7551        synchronized (mPackages) {
7552            pkg = mPackages.get(packageName);
7553            if (pkg == null) {
7554                throw new IllegalArgumentException("Unknown package: " + packageName);
7555            }
7556        }
7557
7558        synchronized (mInstallLock) {
7559            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7560
7561            // Whoever is calling forceDexOpt wants a fully compiled package.
7562            // Don't use profiles since that may cause compilation to be skipped.
7563            final int res = performDexOptInternalWithDependenciesLI(pkg,
7564                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7565                    true /* force */);
7566
7567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7568            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7569                throw new IllegalStateException("Failed to dexopt: " + res);
7570            }
7571        }
7572    }
7573
7574    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7575        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7576            Slog.w(TAG, "Unable to update from " + oldPkg.name
7577                    + " to " + newPkg.packageName
7578                    + ": old package not in system partition");
7579            return false;
7580        } else if (mPackages.get(oldPkg.name) != null) {
7581            Slog.w(TAG, "Unable to update from " + oldPkg.name
7582                    + " to " + newPkg.packageName
7583                    + ": old package still exists");
7584            return false;
7585        }
7586        return true;
7587    }
7588
7589    void removeCodePathLI(File codePath) {
7590        if (codePath.isDirectory()) {
7591            try {
7592                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7593            } catch (InstallerException e) {
7594                Slog.w(TAG, "Failed to remove code path", e);
7595            }
7596        } else {
7597            codePath.delete();
7598        }
7599    }
7600
7601    private int[] resolveUserIds(int userId) {
7602        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7603    }
7604
7605    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7606        if (pkg == null) {
7607            Slog.wtf(TAG, "Package was null!", new Throwable());
7608            return;
7609        }
7610        clearAppDataLeafLIF(pkg, userId, flags);
7611        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7612        for (int i = 0; i < childCount; i++) {
7613            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7614        }
7615    }
7616
7617    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7618        final PackageSetting ps;
7619        synchronized (mPackages) {
7620            ps = mSettings.mPackages.get(pkg.packageName);
7621        }
7622        for (int realUserId : resolveUserIds(userId)) {
7623            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7624            try {
7625                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7626                        ceDataInode);
7627            } catch (InstallerException e) {
7628                Slog.w(TAG, String.valueOf(e));
7629            }
7630        }
7631    }
7632
7633    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7634        if (pkg == null) {
7635            Slog.wtf(TAG, "Package was null!", new Throwable());
7636            return;
7637        }
7638        destroyAppDataLeafLIF(pkg, userId, flags);
7639        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7640        for (int i = 0; i < childCount; i++) {
7641            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7642        }
7643    }
7644
7645    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7646        final PackageSetting ps;
7647        synchronized (mPackages) {
7648            ps = mSettings.mPackages.get(pkg.packageName);
7649        }
7650        for (int realUserId : resolveUserIds(userId)) {
7651            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7652            try {
7653                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7654                        ceDataInode);
7655            } catch (InstallerException e) {
7656                Slog.w(TAG, String.valueOf(e));
7657            }
7658        }
7659    }
7660
7661    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7662        if (pkg == null) {
7663            Slog.wtf(TAG, "Package was null!", new Throwable());
7664            return;
7665        }
7666        destroyAppProfilesLeafLIF(pkg);
7667        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7668        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7669        for (int i = 0; i < childCount; i++) {
7670            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7671            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7672                    true /* removeBaseMarker */);
7673        }
7674    }
7675
7676    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7677            boolean removeBaseMarker) {
7678        if (pkg.isForwardLocked()) {
7679            return;
7680        }
7681
7682        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7683            try {
7684                path = PackageManagerServiceUtils.realpath(new File(path));
7685            } catch (IOException e) {
7686                // TODO: Should we return early here ?
7687                Slog.w(TAG, "Failed to get canonical path", e);
7688                continue;
7689            }
7690
7691            final String useMarker = path.replace('/', '@');
7692            for (int realUserId : resolveUserIds(userId)) {
7693                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7694                if (removeBaseMarker) {
7695                    File foreignUseMark = new File(profileDir, useMarker);
7696                    if (foreignUseMark.exists()) {
7697                        if (!foreignUseMark.delete()) {
7698                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7699                                    + pkg.packageName);
7700                        }
7701                    }
7702                }
7703
7704                File[] markers = profileDir.listFiles();
7705                if (markers != null) {
7706                    final String searchString = "@" + pkg.packageName + "@";
7707                    // We also delete all markers that contain the package name we're
7708                    // uninstalling. These are associated with secondary dex-files belonging
7709                    // to the package. Reconstructing the path of these dex files is messy
7710                    // in general.
7711                    for (File marker : markers) {
7712                        if (marker.getName().indexOf(searchString) > 0) {
7713                            if (!marker.delete()) {
7714                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7715                                    + pkg.packageName);
7716                            }
7717                        }
7718                    }
7719                }
7720            }
7721        }
7722    }
7723
7724    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7725        try {
7726            mInstaller.destroyAppProfiles(pkg.packageName);
7727        } catch (InstallerException e) {
7728            Slog.w(TAG, String.valueOf(e));
7729        }
7730    }
7731
7732    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7733        if (pkg == null) {
7734            Slog.wtf(TAG, "Package was null!", new Throwable());
7735            return;
7736        }
7737        clearAppProfilesLeafLIF(pkg);
7738        // We don't remove the base foreign use marker when clearing profiles because
7739        // we will rename it when the app is updated. Unlike the actual profile contents,
7740        // the foreign use marker is good across installs.
7741        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7742        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7743        for (int i = 0; i < childCount; i++) {
7744            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7745        }
7746    }
7747
7748    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7749        try {
7750            mInstaller.clearAppProfiles(pkg.packageName);
7751        } catch (InstallerException e) {
7752            Slog.w(TAG, String.valueOf(e));
7753        }
7754    }
7755
7756    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7757            long lastUpdateTime) {
7758        // Set parent install/update time
7759        PackageSetting ps = (PackageSetting) pkg.mExtras;
7760        if (ps != null) {
7761            ps.firstInstallTime = firstInstallTime;
7762            ps.lastUpdateTime = lastUpdateTime;
7763        }
7764        // Set children install/update time
7765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7766        for (int i = 0; i < childCount; i++) {
7767            PackageParser.Package childPkg = pkg.childPackages.get(i);
7768            ps = (PackageSetting) childPkg.mExtras;
7769            if (ps != null) {
7770                ps.firstInstallTime = firstInstallTime;
7771                ps.lastUpdateTime = lastUpdateTime;
7772            }
7773        }
7774    }
7775
7776    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7777            PackageParser.Package changingLib) {
7778        if (file.path != null) {
7779            usesLibraryFiles.add(file.path);
7780            return;
7781        }
7782        PackageParser.Package p = mPackages.get(file.apk);
7783        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7784            // If we are doing this while in the middle of updating a library apk,
7785            // then we need to make sure to use that new apk for determining the
7786            // dependencies here.  (We haven't yet finished committing the new apk
7787            // to the package manager state.)
7788            if (p == null || p.packageName.equals(changingLib.packageName)) {
7789                p = changingLib;
7790            }
7791        }
7792        if (p != null) {
7793            usesLibraryFiles.addAll(p.getAllCodePaths());
7794        }
7795    }
7796
7797    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7798            PackageParser.Package changingLib) throws PackageManagerException {
7799        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7800            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7801            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7802            for (int i=0; i<N; i++) {
7803                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7804                if (file == null) {
7805                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7806                            "Package " + pkg.packageName + " requires unavailable shared library "
7807                            + pkg.usesLibraries.get(i) + "; failing!");
7808                }
7809                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7810            }
7811            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7812            for (int i=0; i<N; i++) {
7813                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7814                if (file == null) {
7815                    Slog.w(TAG, "Package " + pkg.packageName
7816                            + " desires unavailable shared library "
7817                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7818                } else {
7819                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7820                }
7821            }
7822            N = usesLibraryFiles.size();
7823            if (N > 0) {
7824                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7825            } else {
7826                pkg.usesLibraryFiles = null;
7827            }
7828        }
7829    }
7830
7831    private static boolean hasString(List<String> list, List<String> which) {
7832        if (list == null) {
7833            return false;
7834        }
7835        for (int i=list.size()-1; i>=0; i--) {
7836            for (int j=which.size()-1; j>=0; j--) {
7837                if (which.get(j).equals(list.get(i))) {
7838                    return true;
7839                }
7840            }
7841        }
7842        return false;
7843    }
7844
7845    private void updateAllSharedLibrariesLPw() {
7846        for (PackageParser.Package pkg : mPackages.values()) {
7847            try {
7848                updateSharedLibrariesLPw(pkg, null);
7849            } catch (PackageManagerException e) {
7850                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7851            }
7852        }
7853    }
7854
7855    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7856            PackageParser.Package changingPkg) {
7857        ArrayList<PackageParser.Package> res = null;
7858        for (PackageParser.Package pkg : mPackages.values()) {
7859            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7860                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7861                if (res == null) {
7862                    res = new ArrayList<PackageParser.Package>();
7863                }
7864                res.add(pkg);
7865                try {
7866                    updateSharedLibrariesLPw(pkg, changingPkg);
7867                } catch (PackageManagerException e) {
7868                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7869                }
7870            }
7871        }
7872        return res;
7873    }
7874
7875    /**
7876     * Derive the value of the {@code cpuAbiOverride} based on the provided
7877     * value and an optional stored value from the package settings.
7878     */
7879    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7880        String cpuAbiOverride = null;
7881
7882        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7883            cpuAbiOverride = null;
7884        } else if (abiOverride != null) {
7885            cpuAbiOverride = abiOverride;
7886        } else if (settings != null) {
7887            cpuAbiOverride = settings.cpuAbiOverrideString;
7888        }
7889
7890        return cpuAbiOverride;
7891    }
7892
7893    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7894            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7895                    throws PackageManagerException {
7896        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7897        // If the package has children and this is the first dive in the function
7898        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7899        // whether all packages (parent and children) would be successfully scanned
7900        // before the actual scan since scanning mutates internal state and we want
7901        // to atomically install the package and its children.
7902        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7903            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7904                scanFlags |= SCAN_CHECK_ONLY;
7905            }
7906        } else {
7907            scanFlags &= ~SCAN_CHECK_ONLY;
7908        }
7909
7910        final PackageParser.Package scannedPkg;
7911        try {
7912            // Scan the parent
7913            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7914            // Scan the children
7915            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7916            for (int i = 0; i < childCount; i++) {
7917                PackageParser.Package childPkg = pkg.childPackages.get(i);
7918                scanPackageLI(childPkg, policyFlags,
7919                        scanFlags, currentTime, user);
7920            }
7921        } finally {
7922            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7923        }
7924
7925        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7926            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7927        }
7928
7929        return scannedPkg;
7930    }
7931
7932    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7933            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7934        boolean success = false;
7935        try {
7936            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7937                    currentTime, user);
7938            success = true;
7939            return res;
7940        } finally {
7941            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7942                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7943                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7944                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7945                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7946            }
7947        }
7948    }
7949
7950    /**
7951     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7952     */
7953    private static boolean apkHasCode(String fileName) {
7954        StrictJarFile jarFile = null;
7955        try {
7956            jarFile = new StrictJarFile(fileName,
7957                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7958            return jarFile.findEntry("classes.dex") != null;
7959        } catch (IOException ignore) {
7960        } finally {
7961            try {
7962                jarFile.close();
7963            } catch (IOException ignore) {}
7964        }
7965        return false;
7966    }
7967
7968    /**
7969     * Enforces code policy for the package. This ensures that if an APK has
7970     * declared hasCode="true" in its manifest that the APK actually contains
7971     * code.
7972     *
7973     * @throws PackageManagerException If bytecode could not be found when it should exist
7974     */
7975    private static void enforceCodePolicy(PackageParser.Package pkg)
7976            throws PackageManagerException {
7977        final boolean shouldHaveCode =
7978                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7979        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7980            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7981                    "Package " + pkg.baseCodePath + " code is missing");
7982        }
7983
7984        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7985            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7986                final boolean splitShouldHaveCode =
7987                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7988                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7989                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7990                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7991                }
7992            }
7993        }
7994    }
7995
7996    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7997            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7998            throws PackageManagerException {
7999        final File scanFile = new File(pkg.codePath);
8000        if (pkg.applicationInfo.getCodePath() == null ||
8001                pkg.applicationInfo.getResourcePath() == null) {
8002            // Bail out. The resource and code paths haven't been set.
8003            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8004                    "Code and resource paths haven't been set correctly");
8005        }
8006
8007        // Apply policy
8008        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8009            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8010            if (pkg.applicationInfo.isDirectBootAware()) {
8011                // we're direct boot aware; set for all components
8012                for (PackageParser.Service s : pkg.services) {
8013                    s.info.encryptionAware = s.info.directBootAware = true;
8014                }
8015                for (PackageParser.Provider p : pkg.providers) {
8016                    p.info.encryptionAware = p.info.directBootAware = true;
8017                }
8018                for (PackageParser.Activity a : pkg.activities) {
8019                    a.info.encryptionAware = a.info.directBootAware = true;
8020                }
8021                for (PackageParser.Activity r : pkg.receivers) {
8022                    r.info.encryptionAware = r.info.directBootAware = true;
8023                }
8024            }
8025        } else {
8026            // Only allow system apps to be flagged as core apps.
8027            pkg.coreApp = false;
8028            // clear flags not applicable to regular apps
8029            pkg.applicationInfo.privateFlags &=
8030                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8031            pkg.applicationInfo.privateFlags &=
8032                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8033        }
8034        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8035
8036        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8037            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8038        }
8039
8040        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8041            enforceCodePolicy(pkg);
8042        }
8043
8044        if (mCustomResolverComponentName != null &&
8045                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8046            setUpCustomResolverActivity(pkg);
8047        }
8048
8049        if (pkg.packageName.equals("android")) {
8050            synchronized (mPackages) {
8051                if (mAndroidApplication != null) {
8052                    Slog.w(TAG, "*************************************************");
8053                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8054                    Slog.w(TAG, " file=" + scanFile);
8055                    Slog.w(TAG, "*************************************************");
8056                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8057                            "Core android package being redefined.  Skipping.");
8058                }
8059
8060                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8061                    // Set up information for our fall-back user intent resolution activity.
8062                    mPlatformPackage = pkg;
8063                    pkg.mVersionCode = mSdkVersion;
8064                    mAndroidApplication = pkg.applicationInfo;
8065
8066                    if (!mResolverReplaced) {
8067                        mResolveActivity.applicationInfo = mAndroidApplication;
8068                        mResolveActivity.name = ResolverActivity.class.getName();
8069                        mResolveActivity.packageName = mAndroidApplication.packageName;
8070                        mResolveActivity.processName = "system:ui";
8071                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8072                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8073                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8074                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8075                        mResolveActivity.exported = true;
8076                        mResolveActivity.enabled = true;
8077                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8078                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8079                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8080                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8081                                | ActivityInfo.CONFIG_ORIENTATION
8082                                | ActivityInfo.CONFIG_KEYBOARD
8083                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8084                        mResolveInfo.activityInfo = mResolveActivity;
8085                        mResolveInfo.priority = 0;
8086                        mResolveInfo.preferredOrder = 0;
8087                        mResolveInfo.match = 0;
8088                        mResolveComponentName = new ComponentName(
8089                                mAndroidApplication.packageName, mResolveActivity.name);
8090                    }
8091                }
8092            }
8093        }
8094
8095        if (DEBUG_PACKAGE_SCANNING) {
8096            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8097                Log.d(TAG, "Scanning package " + pkg.packageName);
8098        }
8099
8100        synchronized (mPackages) {
8101            if (mPackages.containsKey(pkg.packageName)
8102                    || mSharedLibraries.containsKey(pkg.packageName)) {
8103                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8104                        "Application package " + pkg.packageName
8105                                + " already installed.  Skipping duplicate.");
8106            }
8107
8108            // If we're only installing presumed-existing packages, require that the
8109            // scanned APK is both already known and at the path previously established
8110            // for it.  Previously unknown packages we pick up normally, but if we have an
8111            // a priori expectation about this package's install presence, enforce it.
8112            // With a singular exception for new system packages. When an OTA contains
8113            // a new system package, we allow the codepath to change from a system location
8114            // to the user-installed location. If we don't allow this change, any newer,
8115            // user-installed version of the application will be ignored.
8116            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8117                if (mExpectingBetter.containsKey(pkg.packageName)) {
8118                    logCriticalInfo(Log.WARN,
8119                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8120                } else {
8121                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8122                    if (known != null) {
8123                        if (DEBUG_PACKAGE_SCANNING) {
8124                            Log.d(TAG, "Examining " + pkg.codePath
8125                                    + " and requiring known paths " + known.codePathString
8126                                    + " & " + known.resourcePathString);
8127                        }
8128                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8129                                || !pkg.applicationInfo.getResourcePath().equals(
8130                                known.resourcePathString)) {
8131                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8132                                    "Application package " + pkg.packageName
8133                                            + " found at " + pkg.applicationInfo.getCodePath()
8134                                            + " but expected at " + known.codePathString
8135                                            + "; ignoring.");
8136                        }
8137                    }
8138                }
8139            }
8140        }
8141
8142        // Initialize package source and resource directories
8143        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8144        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8145
8146        SharedUserSetting suid = null;
8147        PackageSetting pkgSetting = null;
8148
8149        if (!isSystemApp(pkg)) {
8150            // Only system apps can use these features.
8151            pkg.mOriginalPackages = null;
8152            pkg.mRealPackage = null;
8153            pkg.mAdoptPermissions = null;
8154        }
8155
8156        // Getting the package setting may have a side-effect, so if we
8157        // are only checking if scan would succeed, stash a copy of the
8158        // old setting to restore at the end.
8159        PackageSetting nonMutatedPs = null;
8160
8161        // writer
8162        synchronized (mPackages) {
8163            if (pkg.mSharedUserId != null) {
8164                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8165                if (suid == null) {
8166                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8167                            "Creating application package " + pkg.packageName
8168                            + " for shared user failed");
8169                }
8170                if (DEBUG_PACKAGE_SCANNING) {
8171                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8172                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8173                                + "): packages=" + suid.packages);
8174                }
8175            }
8176
8177            // Check if we are renaming from an original package name.
8178            PackageSetting origPackage = null;
8179            String realName = null;
8180            if (pkg.mOriginalPackages != null) {
8181                // This package may need to be renamed to a previously
8182                // installed name.  Let's check on that...
8183                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8184                if (pkg.mOriginalPackages.contains(renamed)) {
8185                    // This package had originally been installed as the
8186                    // original name, and we have already taken care of
8187                    // transitioning to the new one.  Just update the new
8188                    // one to continue using the old name.
8189                    realName = pkg.mRealPackage;
8190                    if (!pkg.packageName.equals(renamed)) {
8191                        // Callers into this function may have already taken
8192                        // care of renaming the package; only do it here if
8193                        // it is not already done.
8194                        pkg.setPackageName(renamed);
8195                    }
8196
8197                } else {
8198                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8199                        if ((origPackage = mSettings.peekPackageLPr(
8200                                pkg.mOriginalPackages.get(i))) != null) {
8201                            // We do have the package already installed under its
8202                            // original name...  should we use it?
8203                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8204                                // New package is not compatible with original.
8205                                origPackage = null;
8206                                continue;
8207                            } else if (origPackage.sharedUser != null) {
8208                                // Make sure uid is compatible between packages.
8209                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8210                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8211                                            + " to " + pkg.packageName + ": old uid "
8212                                            + origPackage.sharedUser.name
8213                                            + " differs from " + pkg.mSharedUserId);
8214                                    origPackage = null;
8215                                    continue;
8216                                }
8217                                // TODO: Add case when shared user id is added [b/28144775]
8218                            } else {
8219                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8220                                        + pkg.packageName + " to old name " + origPackage.name);
8221                            }
8222                            break;
8223                        }
8224                    }
8225                }
8226            }
8227
8228            if (mTransferedPackages.contains(pkg.packageName)) {
8229                Slog.w(TAG, "Package " + pkg.packageName
8230                        + " was transferred to another, but its .apk remains");
8231            }
8232
8233            // See comments in nonMutatedPs declaration
8234            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8235                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8236                if (foundPs != null) {
8237                    nonMutatedPs = new PackageSetting(foundPs);
8238                }
8239            }
8240
8241            // Just create the setting, don't add it yet. For already existing packages
8242            // the PkgSetting exists already and doesn't have to be created.
8243            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8244                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8245                    pkg.applicationInfo.primaryCpuAbi,
8246                    pkg.applicationInfo.secondaryCpuAbi,
8247                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8248                    user, false);
8249            if (pkgSetting == null) {
8250                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8251                        "Creating application package " + pkg.packageName + " failed");
8252            }
8253
8254            if (pkgSetting.origPackage != null) {
8255                // If we are first transitioning from an original package,
8256                // fix up the new package's name now.  We need to do this after
8257                // looking up the package under its new name, so getPackageLP
8258                // can take care of fiddling things correctly.
8259                pkg.setPackageName(origPackage.name);
8260
8261                // File a report about this.
8262                String msg = "New package " + pkgSetting.realName
8263                        + " renamed to replace old package " + pkgSetting.name;
8264                reportSettingsProblem(Log.WARN, msg);
8265
8266                // Make a note of it.
8267                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8268                    mTransferedPackages.add(origPackage.name);
8269                }
8270
8271                // No longer need to retain this.
8272                pkgSetting.origPackage = null;
8273            }
8274
8275            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8276                // Make a note of it.
8277                mTransferedPackages.add(pkg.packageName);
8278            }
8279
8280            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8281                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8282            }
8283
8284            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8285                // Check all shared libraries and map to their actual file path.
8286                // We only do this here for apps not on a system dir, because those
8287                // are the only ones that can fail an install due to this.  We
8288                // will take care of the system apps by updating all of their
8289                // library paths after the scan is done.
8290                updateSharedLibrariesLPw(pkg, null);
8291            }
8292
8293            if (mFoundPolicyFile) {
8294                SELinuxMMAC.assignSeinfoValue(pkg);
8295            }
8296
8297            pkg.applicationInfo.uid = pkgSetting.appId;
8298            pkg.mExtras = pkgSetting;
8299            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8300                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8301                    // We just determined the app is signed correctly, so bring
8302                    // over the latest parsed certs.
8303                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8304                } else {
8305                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8306                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8307                                "Package " + pkg.packageName + " upgrade keys do not match the "
8308                                + "previously installed version");
8309                    } else {
8310                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8311                        String msg = "System package " + pkg.packageName
8312                            + " signature changed; retaining data.";
8313                        reportSettingsProblem(Log.WARN, msg);
8314                    }
8315                }
8316            } else {
8317                try {
8318                    verifySignaturesLP(pkgSetting, pkg);
8319                    // We just determined the app is signed correctly, so bring
8320                    // over the latest parsed certs.
8321                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8322                } catch (PackageManagerException e) {
8323                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8324                        throw e;
8325                    }
8326                    // The signature has changed, but this package is in the system
8327                    // image...  let's recover!
8328                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8329                    // However...  if this package is part of a shared user, but it
8330                    // doesn't match the signature of the shared user, let's fail.
8331                    // What this means is that you can't change the signatures
8332                    // associated with an overall shared user, which doesn't seem all
8333                    // that unreasonable.
8334                    if (pkgSetting.sharedUser != null) {
8335                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8336                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8337                            throw new PackageManagerException(
8338                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8339                                            "Signature mismatch for shared user: "
8340                                            + pkgSetting.sharedUser);
8341                        }
8342                    }
8343                    // File a report about this.
8344                    String msg = "System package " + pkg.packageName
8345                        + " signature changed; retaining data.";
8346                    reportSettingsProblem(Log.WARN, msg);
8347                }
8348            }
8349            // Verify that this new package doesn't have any content providers
8350            // that conflict with existing packages.  Only do this if the
8351            // package isn't already installed, since we don't want to break
8352            // things that are installed.
8353            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8354                final int N = pkg.providers.size();
8355                int i;
8356                for (i=0; i<N; i++) {
8357                    PackageParser.Provider p = pkg.providers.get(i);
8358                    if (p.info.authority != null) {
8359                        String names[] = p.info.authority.split(";");
8360                        for (int j = 0; j < names.length; j++) {
8361                            if (mProvidersByAuthority.containsKey(names[j])) {
8362                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8363                                final String otherPackageName =
8364                                        ((other != null && other.getComponentName() != null) ?
8365                                                other.getComponentName().getPackageName() : "?");
8366                                throw new PackageManagerException(
8367                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8368                                                "Can't install because provider name " + names[j]
8369                                                + " (in package " + pkg.applicationInfo.packageName
8370                                                + ") is already used by " + otherPackageName);
8371                            }
8372                        }
8373                    }
8374                }
8375            }
8376
8377            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8378                // This package wants to adopt ownership of permissions from
8379                // another package.
8380                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8381                    final String origName = pkg.mAdoptPermissions.get(i);
8382                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8383                    if (orig != null) {
8384                        if (verifyPackageUpdateLPr(orig, pkg)) {
8385                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8386                                    + pkg.packageName);
8387                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8388                        }
8389                    }
8390                }
8391            }
8392        }
8393
8394        final String pkgName = pkg.packageName;
8395
8396        final long scanFileTime = scanFile.lastModified();
8397        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8398        pkg.applicationInfo.processName = fixProcessName(
8399                pkg.applicationInfo.packageName,
8400                pkg.applicationInfo.processName,
8401                pkg.applicationInfo.uid);
8402
8403        if (pkg != mPlatformPackage) {
8404            // Get all of our default paths setup
8405            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8406        }
8407
8408        final String path = scanFile.getPath();
8409        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8410
8411        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8412            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8413
8414            // Some system apps still use directory structure for native libraries
8415            // in which case we might end up not detecting abi solely based on apk
8416            // structure. Try to detect abi based on directory structure.
8417            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8418                    pkg.applicationInfo.primaryCpuAbi == null) {
8419                setBundledAppAbisAndRoots(pkg, pkgSetting);
8420                setNativeLibraryPaths(pkg);
8421            }
8422
8423        } else {
8424            if ((scanFlags & SCAN_MOVE) != 0) {
8425                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8426                // but we already have this packages package info in the PackageSetting. We just
8427                // use that and derive the native library path based on the new codepath.
8428                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8429                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8430            }
8431
8432            // Set native library paths again. For moves, the path will be updated based on the
8433            // ABIs we've determined above. For non-moves, the path will be updated based on the
8434            // ABIs we determined during compilation, but the path will depend on the final
8435            // package path (after the rename away from the stage path).
8436            setNativeLibraryPaths(pkg);
8437        }
8438
8439        // This is a special case for the "system" package, where the ABI is
8440        // dictated by the zygote configuration (and init.rc). We should keep track
8441        // of this ABI so that we can deal with "normal" applications that run under
8442        // the same UID correctly.
8443        if (mPlatformPackage == pkg) {
8444            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8445                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8446        }
8447
8448        // If there's a mismatch between the abi-override in the package setting
8449        // and the abiOverride specified for the install. Warn about this because we
8450        // would've already compiled the app without taking the package setting into
8451        // account.
8452        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8453            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8454                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8455                        " for package " + pkg.packageName);
8456            }
8457        }
8458
8459        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8460        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8461        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8462
8463        // Copy the derived override back to the parsed package, so that we can
8464        // update the package settings accordingly.
8465        pkg.cpuAbiOverride = cpuAbiOverride;
8466
8467        if (DEBUG_ABI_SELECTION) {
8468            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8469                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8470                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8471        }
8472
8473        // Push the derived path down into PackageSettings so we know what to
8474        // clean up at uninstall time.
8475        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8476
8477        if (DEBUG_ABI_SELECTION) {
8478            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8479                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8480                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8481        }
8482
8483        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8484            // We don't do this here during boot because we can do it all
8485            // at once after scanning all existing packages.
8486            //
8487            // We also do this *before* we perform dexopt on this package, so that
8488            // we can avoid redundant dexopts, and also to make sure we've got the
8489            // code and package path correct.
8490            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8491                    pkg, true /* boot complete */);
8492        }
8493
8494        if (mFactoryTest && pkg.requestedPermissions.contains(
8495                android.Manifest.permission.FACTORY_TEST)) {
8496            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8497        }
8498
8499        ArrayList<PackageParser.Package> clientLibPkgs = null;
8500
8501        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8502            if (nonMutatedPs != null) {
8503                synchronized (mPackages) {
8504                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8505                }
8506            }
8507            return pkg;
8508        }
8509
8510        // Only privileged apps and updated privileged apps can add child packages.
8511        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8512            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8513                throw new PackageManagerException("Only privileged apps and updated "
8514                        + "privileged apps can add child packages. Ignoring package "
8515                        + pkg.packageName);
8516            }
8517            final int childCount = pkg.childPackages.size();
8518            for (int i = 0; i < childCount; i++) {
8519                PackageParser.Package childPkg = pkg.childPackages.get(i);
8520                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8521                        childPkg.packageName)) {
8522                    throw new PackageManagerException("Cannot override a child package of "
8523                            + "another disabled system app. Ignoring package " + pkg.packageName);
8524                }
8525            }
8526        }
8527
8528        // writer
8529        synchronized (mPackages) {
8530            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8531                // Only system apps can add new shared libraries.
8532                if (pkg.libraryNames != null) {
8533                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8534                        String name = pkg.libraryNames.get(i);
8535                        boolean allowed = false;
8536                        if (pkg.isUpdatedSystemApp()) {
8537                            // New library entries can only be added through the
8538                            // system image.  This is important to get rid of a lot
8539                            // of nasty edge cases: for example if we allowed a non-
8540                            // system update of the app to add a library, then uninstalling
8541                            // the update would make the library go away, and assumptions
8542                            // we made such as through app install filtering would now
8543                            // have allowed apps on the device which aren't compatible
8544                            // with it.  Better to just have the restriction here, be
8545                            // conservative, and create many fewer cases that can negatively
8546                            // impact the user experience.
8547                            final PackageSetting sysPs = mSettings
8548                                    .getDisabledSystemPkgLPr(pkg.packageName);
8549                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8550                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8551                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8552                                        allowed = true;
8553                                        break;
8554                                    }
8555                                }
8556                            }
8557                        } else {
8558                            allowed = true;
8559                        }
8560                        if (allowed) {
8561                            if (!mSharedLibraries.containsKey(name)) {
8562                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8563                            } else if (!name.equals(pkg.packageName)) {
8564                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8565                                        + name + " already exists; skipping");
8566                            }
8567                        } else {
8568                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8569                                    + name + " that is not declared on system image; skipping");
8570                        }
8571                    }
8572                    if ((scanFlags & SCAN_BOOTING) == 0) {
8573                        // If we are not booting, we need to update any applications
8574                        // that are clients of our shared library.  If we are booting,
8575                        // this will all be done once the scan is complete.
8576                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8577                    }
8578                }
8579            }
8580        }
8581
8582        if ((scanFlags & SCAN_BOOTING) != 0) {
8583            // No apps can run during boot scan, so they don't need to be frozen
8584        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8585            // Caller asked to not kill app, so it's probably not frozen
8586        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8587            // Caller asked us to ignore frozen check for some reason; they
8588            // probably didn't know the package name
8589        } else {
8590            // We're doing major surgery on this package, so it better be frozen
8591            // right now to keep it from launching
8592            checkPackageFrozen(pkgName);
8593        }
8594
8595        // Also need to kill any apps that are dependent on the library.
8596        if (clientLibPkgs != null) {
8597            for (int i=0; i<clientLibPkgs.size(); i++) {
8598                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8599                killApplication(clientPkg.applicationInfo.packageName,
8600                        clientPkg.applicationInfo.uid, "update lib");
8601            }
8602        }
8603
8604        // Make sure we're not adding any bogus keyset info
8605        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8606        ksms.assertScannedPackageValid(pkg);
8607
8608        // writer
8609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8610
8611        boolean createIdmapFailed = false;
8612        synchronized (mPackages) {
8613            // We don't expect installation to fail beyond this point
8614
8615            if (pkgSetting.pkg != null) {
8616                // Note that |user| might be null during the initial boot scan. If a codePath
8617                // for an app has changed during a boot scan, it's due to an app update that's
8618                // part of the system partition and marker changes must be applied to all users.
8619                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8620                    (user != null) ? user : UserHandle.ALL);
8621            }
8622
8623            // Add the new setting to mSettings
8624            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8625            // Add the new setting to mPackages
8626            mPackages.put(pkg.applicationInfo.packageName, pkg);
8627            // Make sure we don't accidentally delete its data.
8628            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8629            while (iter.hasNext()) {
8630                PackageCleanItem item = iter.next();
8631                if (pkgName.equals(item.packageName)) {
8632                    iter.remove();
8633                }
8634            }
8635
8636            // Take care of first install / last update times.
8637            if (currentTime != 0) {
8638                if (pkgSetting.firstInstallTime == 0) {
8639                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8640                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8641                    pkgSetting.lastUpdateTime = currentTime;
8642                }
8643            } else if (pkgSetting.firstInstallTime == 0) {
8644                // We need *something*.  Take time time stamp of the file.
8645                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8646            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8647                if (scanFileTime != pkgSetting.timeStamp) {
8648                    // A package on the system image has changed; consider this
8649                    // to be an update.
8650                    pkgSetting.lastUpdateTime = scanFileTime;
8651                }
8652            }
8653
8654            // Add the package's KeySets to the global KeySetManagerService
8655            ksms.addScannedPackageLPw(pkg);
8656
8657            int N = pkg.providers.size();
8658            StringBuilder r = null;
8659            int i;
8660            for (i=0; i<N; i++) {
8661                PackageParser.Provider p = pkg.providers.get(i);
8662                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8663                        p.info.processName, pkg.applicationInfo.uid);
8664                mProviders.addProvider(p);
8665                p.syncable = p.info.isSyncable;
8666                if (p.info.authority != null) {
8667                    String names[] = p.info.authority.split(";");
8668                    p.info.authority = null;
8669                    for (int j = 0; j < names.length; j++) {
8670                        if (j == 1 && p.syncable) {
8671                            // We only want the first authority for a provider to possibly be
8672                            // syncable, so if we already added this provider using a different
8673                            // authority clear the syncable flag. We copy the provider before
8674                            // changing it because the mProviders object contains a reference
8675                            // to a provider that we don't want to change.
8676                            // Only do this for the second authority since the resulting provider
8677                            // object can be the same for all future authorities for this provider.
8678                            p = new PackageParser.Provider(p);
8679                            p.syncable = false;
8680                        }
8681                        if (!mProvidersByAuthority.containsKey(names[j])) {
8682                            mProvidersByAuthority.put(names[j], p);
8683                            if (p.info.authority == null) {
8684                                p.info.authority = names[j];
8685                            } else {
8686                                p.info.authority = p.info.authority + ";" + names[j];
8687                            }
8688                            if (DEBUG_PACKAGE_SCANNING) {
8689                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8690                                    Log.d(TAG, "Registered content provider: " + names[j]
8691                                            + ", className = " + p.info.name + ", isSyncable = "
8692                                            + p.info.isSyncable);
8693                            }
8694                        } else {
8695                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8696                            Slog.w(TAG, "Skipping provider name " + names[j] +
8697                                    " (in package " + pkg.applicationInfo.packageName +
8698                                    "): name already used by "
8699                                    + ((other != null && other.getComponentName() != null)
8700                                            ? other.getComponentName().getPackageName() : "?"));
8701                        }
8702                    }
8703                }
8704                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8705                    if (r == null) {
8706                        r = new StringBuilder(256);
8707                    } else {
8708                        r.append(' ');
8709                    }
8710                    r.append(p.info.name);
8711                }
8712            }
8713            if (r != null) {
8714                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8715            }
8716
8717            N = pkg.services.size();
8718            r = null;
8719            for (i=0; i<N; i++) {
8720                PackageParser.Service s = pkg.services.get(i);
8721                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8722                        s.info.processName, pkg.applicationInfo.uid);
8723                mServices.addService(s);
8724                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8725                    if (r == null) {
8726                        r = new StringBuilder(256);
8727                    } else {
8728                        r.append(' ');
8729                    }
8730                    r.append(s.info.name);
8731                }
8732            }
8733            if (r != null) {
8734                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8735            }
8736
8737            N = pkg.receivers.size();
8738            r = null;
8739            for (i=0; i<N; i++) {
8740                PackageParser.Activity a = pkg.receivers.get(i);
8741                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8742                        a.info.processName, pkg.applicationInfo.uid);
8743                mReceivers.addActivity(a, "receiver");
8744                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8745                    if (r == null) {
8746                        r = new StringBuilder(256);
8747                    } else {
8748                        r.append(' ');
8749                    }
8750                    r.append(a.info.name);
8751                }
8752            }
8753            if (r != null) {
8754                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8755            }
8756
8757            N = pkg.activities.size();
8758            r = null;
8759            for (i=0; i<N; i++) {
8760                PackageParser.Activity a = pkg.activities.get(i);
8761                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8762                        a.info.processName, pkg.applicationInfo.uid);
8763                mActivities.addActivity(a, "activity");
8764                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8765                    if (r == null) {
8766                        r = new StringBuilder(256);
8767                    } else {
8768                        r.append(' ');
8769                    }
8770                    r.append(a.info.name);
8771                }
8772            }
8773            if (r != null) {
8774                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8775            }
8776
8777            N = pkg.permissionGroups.size();
8778            r = null;
8779            for (i=0; i<N; i++) {
8780                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8781                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8782                if (cur == null) {
8783                    mPermissionGroups.put(pg.info.name, pg);
8784                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8785                        if (r == null) {
8786                            r = new StringBuilder(256);
8787                        } else {
8788                            r.append(' ');
8789                        }
8790                        r.append(pg.info.name);
8791                    }
8792                } else {
8793                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8794                            + pg.info.packageName + " ignored: original from "
8795                            + cur.info.packageName);
8796                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8797                        if (r == null) {
8798                            r = new StringBuilder(256);
8799                        } else {
8800                            r.append(' ');
8801                        }
8802                        r.append("DUP:");
8803                        r.append(pg.info.name);
8804                    }
8805                }
8806            }
8807            if (r != null) {
8808                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8809            }
8810
8811            N = pkg.permissions.size();
8812            r = null;
8813            for (i=0; i<N; i++) {
8814                PackageParser.Permission p = pkg.permissions.get(i);
8815
8816                // Assume by default that we did not install this permission into the system.
8817                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8818
8819                // Now that permission groups have a special meaning, we ignore permission
8820                // groups for legacy apps to prevent unexpected behavior. In particular,
8821                // permissions for one app being granted to someone just becase they happen
8822                // to be in a group defined by another app (before this had no implications).
8823                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8824                    p.group = mPermissionGroups.get(p.info.group);
8825                    // Warn for a permission in an unknown group.
8826                    if (p.info.group != null && p.group == null) {
8827                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8828                                + p.info.packageName + " in an unknown group " + p.info.group);
8829                    }
8830                }
8831
8832                ArrayMap<String, BasePermission> permissionMap =
8833                        p.tree ? mSettings.mPermissionTrees
8834                                : mSettings.mPermissions;
8835                BasePermission bp = permissionMap.get(p.info.name);
8836
8837                // Allow system apps to redefine non-system permissions
8838                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8839                    final boolean currentOwnerIsSystem = (bp.perm != null
8840                            && isSystemApp(bp.perm.owner));
8841                    if (isSystemApp(p.owner)) {
8842                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8843                            // It's a built-in permission and no owner, take ownership now
8844                            bp.packageSetting = pkgSetting;
8845                            bp.perm = p;
8846                            bp.uid = pkg.applicationInfo.uid;
8847                            bp.sourcePackage = p.info.packageName;
8848                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8849                        } else if (!currentOwnerIsSystem) {
8850                            String msg = "New decl " + p.owner + " of permission  "
8851                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8852                            reportSettingsProblem(Log.WARN, msg);
8853                            bp = null;
8854                        }
8855                    }
8856                }
8857
8858                if (bp == null) {
8859                    bp = new BasePermission(p.info.name, p.info.packageName,
8860                            BasePermission.TYPE_NORMAL);
8861                    permissionMap.put(p.info.name, bp);
8862                }
8863
8864                if (bp.perm == null) {
8865                    if (bp.sourcePackage == null
8866                            || bp.sourcePackage.equals(p.info.packageName)) {
8867                        BasePermission tree = findPermissionTreeLP(p.info.name);
8868                        if (tree == null
8869                                || tree.sourcePackage.equals(p.info.packageName)) {
8870                            bp.packageSetting = pkgSetting;
8871                            bp.perm = p;
8872                            bp.uid = pkg.applicationInfo.uid;
8873                            bp.sourcePackage = p.info.packageName;
8874                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8875                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8876                                if (r == null) {
8877                                    r = new StringBuilder(256);
8878                                } else {
8879                                    r.append(' ');
8880                                }
8881                                r.append(p.info.name);
8882                            }
8883                        } else {
8884                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8885                                    + p.info.packageName + " ignored: base tree "
8886                                    + tree.name + " is from package "
8887                                    + tree.sourcePackage);
8888                        }
8889                    } else {
8890                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8891                                + p.info.packageName + " ignored: original from "
8892                                + bp.sourcePackage);
8893                    }
8894                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8895                    if (r == null) {
8896                        r = new StringBuilder(256);
8897                    } else {
8898                        r.append(' ');
8899                    }
8900                    r.append("DUP:");
8901                    r.append(p.info.name);
8902                }
8903                if (bp.perm == p) {
8904                    bp.protectionLevel = p.info.protectionLevel;
8905                }
8906            }
8907
8908            if (r != null) {
8909                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8910            }
8911
8912            N = pkg.instrumentation.size();
8913            r = null;
8914            for (i=0; i<N; i++) {
8915                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8916                a.info.packageName = pkg.applicationInfo.packageName;
8917                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8918                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8919                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8920                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8921                a.info.dataDir = pkg.applicationInfo.dataDir;
8922                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8923                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8924
8925                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8926                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8927                mInstrumentation.put(a.getComponentName(), a);
8928                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8929                    if (r == null) {
8930                        r = new StringBuilder(256);
8931                    } else {
8932                        r.append(' ');
8933                    }
8934                    r.append(a.info.name);
8935                }
8936            }
8937            if (r != null) {
8938                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8939            }
8940
8941            if (pkg.protectedBroadcasts != null) {
8942                N = pkg.protectedBroadcasts.size();
8943                for (i=0; i<N; i++) {
8944                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8945                }
8946            }
8947
8948            pkgSetting.setTimeStamp(scanFileTime);
8949
8950            // Create idmap files for pairs of (packages, overlay packages).
8951            // Note: "android", ie framework-res.apk, is handled by native layers.
8952            if (pkg.mOverlayTarget != null) {
8953                // This is an overlay package.
8954                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8955                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8956                        mOverlays.put(pkg.mOverlayTarget,
8957                                new ArrayMap<String, PackageParser.Package>());
8958                    }
8959                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8960                    map.put(pkg.packageName, pkg);
8961                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8962                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8963                        createIdmapFailed = true;
8964                    }
8965                }
8966            } else if (mOverlays.containsKey(pkg.packageName) &&
8967                    !pkg.packageName.equals("android")) {
8968                // This is a regular package, with one or more known overlay packages.
8969                createIdmapsForPackageLI(pkg);
8970            }
8971        }
8972
8973        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8974
8975        if (createIdmapFailed) {
8976            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8977                    "scanPackageLI failed to createIdmap");
8978        }
8979        return pkg;
8980    }
8981
8982    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8983            PackageParser.Package update, UserHandle user) {
8984        if (existing.applicationInfo == null || update.applicationInfo == null) {
8985            // This isn't due to an app installation.
8986            return;
8987        }
8988
8989        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8990        final File newCodePath = new File(update.applicationInfo.getCodePath());
8991
8992        // The codePath hasn't changed, so there's nothing for us to do.
8993        if (Objects.equals(oldCodePath, newCodePath)) {
8994            return;
8995        }
8996
8997        File canonicalNewCodePath;
8998        try {
8999            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9000        } catch (IOException e) {
9001            Slog.w(TAG, "Failed to get canonical path.", e);
9002            return;
9003        }
9004
9005        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9006        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9007        // that the last component of the path (i.e, the name) doesn't need canonicalization
9008        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9009        // but may change in the future. Hopefully this function won't exist at that point.
9010        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9011                oldCodePath.getName());
9012
9013        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9014        // with "@".
9015        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9016        if (!oldMarkerPrefix.endsWith("@")) {
9017            oldMarkerPrefix += "@";
9018        }
9019        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9020        if (!newMarkerPrefix.endsWith("@")) {
9021            newMarkerPrefix += "@";
9022        }
9023
9024        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9025        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9026        for (String updatedPath : updatedPaths) {
9027            String updatedPathName = new File(updatedPath).getName();
9028            markerSuffixes.add(updatedPathName.replace('/', '@'));
9029        }
9030
9031        for (int userId : resolveUserIds(user.getIdentifier())) {
9032            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9033
9034            for (String markerSuffix : markerSuffixes) {
9035                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9036                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9037                if (oldForeignUseMark.exists()) {
9038                    try {
9039                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9040                                newForeignUseMark.getAbsolutePath());
9041                    } catch (ErrnoException e) {
9042                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9043                        oldForeignUseMark.delete();
9044                    }
9045                }
9046            }
9047        }
9048    }
9049
9050    /**
9051     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9052     * is derived purely on the basis of the contents of {@code scanFile} and
9053     * {@code cpuAbiOverride}.
9054     *
9055     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9056     */
9057    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9058                                 String cpuAbiOverride, boolean extractLibs)
9059            throws PackageManagerException {
9060        // TODO: We can probably be smarter about this stuff. For installed apps,
9061        // we can calculate this information at install time once and for all. For
9062        // system apps, we can probably assume that this information doesn't change
9063        // after the first boot scan. As things stand, we do lots of unnecessary work.
9064
9065        // Give ourselves some initial paths; we'll come back for another
9066        // pass once we've determined ABI below.
9067        setNativeLibraryPaths(pkg);
9068
9069        // We would never need to extract libs for forward-locked and external packages,
9070        // since the container service will do it for us. We shouldn't attempt to
9071        // extract libs from system app when it was not updated.
9072        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9073                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9074            extractLibs = false;
9075        }
9076
9077        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9078        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9079
9080        NativeLibraryHelper.Handle handle = null;
9081        try {
9082            handle = NativeLibraryHelper.Handle.create(pkg);
9083            // TODO(multiArch): This can be null for apps that didn't go through the
9084            // usual installation process. We can calculate it again, like we
9085            // do during install time.
9086            //
9087            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9088            // unnecessary.
9089            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9090
9091            // Null out the abis so that they can be recalculated.
9092            pkg.applicationInfo.primaryCpuAbi = null;
9093            pkg.applicationInfo.secondaryCpuAbi = null;
9094            if (isMultiArch(pkg.applicationInfo)) {
9095                // Warn if we've set an abiOverride for multi-lib packages..
9096                // By definition, we need to copy both 32 and 64 bit libraries for
9097                // such packages.
9098                if (pkg.cpuAbiOverride != null
9099                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9100                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9101                }
9102
9103                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9104                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9105                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9106                    if (extractLibs) {
9107                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9108                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9109                                useIsaSpecificSubdirs);
9110                    } else {
9111                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9112                    }
9113                }
9114
9115                maybeThrowExceptionForMultiArchCopy(
9116                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9117
9118                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9119                    if (extractLibs) {
9120                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9121                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9122                                useIsaSpecificSubdirs);
9123                    } else {
9124                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9125                    }
9126                }
9127
9128                maybeThrowExceptionForMultiArchCopy(
9129                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9130
9131                if (abi64 >= 0) {
9132                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9133                }
9134
9135                if (abi32 >= 0) {
9136                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9137                    if (abi64 >= 0) {
9138                        if (pkg.use32bitAbi) {
9139                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9140                            pkg.applicationInfo.primaryCpuAbi = abi;
9141                        } else {
9142                            pkg.applicationInfo.secondaryCpuAbi = abi;
9143                        }
9144                    } else {
9145                        pkg.applicationInfo.primaryCpuAbi = abi;
9146                    }
9147                }
9148
9149            } else {
9150                String[] abiList = (cpuAbiOverride != null) ?
9151                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9152
9153                // Enable gross and lame hacks for apps that are built with old
9154                // SDK tools. We must scan their APKs for renderscript bitcode and
9155                // not launch them if it's present. Don't bother checking on devices
9156                // that don't have 64 bit support.
9157                boolean needsRenderScriptOverride = false;
9158                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9159                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9160                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9161                    needsRenderScriptOverride = true;
9162                }
9163
9164                final int copyRet;
9165                if (extractLibs) {
9166                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9167                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9168                } else {
9169                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9170                }
9171
9172                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9173                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9174                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9175                }
9176
9177                if (copyRet >= 0) {
9178                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9179                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9180                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9181                } else if (needsRenderScriptOverride) {
9182                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9183                }
9184            }
9185        } catch (IOException ioe) {
9186            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9187        } finally {
9188            IoUtils.closeQuietly(handle);
9189        }
9190
9191        // Now that we've calculated the ABIs and determined if it's an internal app,
9192        // we will go ahead and populate the nativeLibraryPath.
9193        setNativeLibraryPaths(pkg);
9194    }
9195
9196    /**
9197     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9198     * i.e, so that all packages can be run inside a single process if required.
9199     *
9200     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9201     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9202     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9203     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9204     * updating a package that belongs to a shared user.
9205     *
9206     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9207     * adds unnecessary complexity.
9208     */
9209    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9210            PackageParser.Package scannedPackage, boolean bootComplete) {
9211        String requiredInstructionSet = null;
9212        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9213            requiredInstructionSet = VMRuntime.getInstructionSet(
9214                     scannedPackage.applicationInfo.primaryCpuAbi);
9215        }
9216
9217        PackageSetting requirer = null;
9218        for (PackageSetting ps : packagesForUser) {
9219            // If packagesForUser contains scannedPackage, we skip it. This will happen
9220            // when scannedPackage is an update of an existing package. Without this check,
9221            // we will never be able to change the ABI of any package belonging to a shared
9222            // user, even if it's compatible with other packages.
9223            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9224                if (ps.primaryCpuAbiString == null) {
9225                    continue;
9226                }
9227
9228                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9229                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9230                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9231                    // this but there's not much we can do.
9232                    String errorMessage = "Instruction set mismatch, "
9233                            + ((requirer == null) ? "[caller]" : requirer)
9234                            + " requires " + requiredInstructionSet + " whereas " + ps
9235                            + " requires " + instructionSet;
9236                    Slog.w(TAG, errorMessage);
9237                }
9238
9239                if (requiredInstructionSet == null) {
9240                    requiredInstructionSet = instructionSet;
9241                    requirer = ps;
9242                }
9243            }
9244        }
9245
9246        if (requiredInstructionSet != null) {
9247            String adjustedAbi;
9248            if (requirer != null) {
9249                // requirer != null implies that either scannedPackage was null or that scannedPackage
9250                // did not require an ABI, in which case we have to adjust scannedPackage to match
9251                // the ABI of the set (which is the same as requirer's ABI)
9252                adjustedAbi = requirer.primaryCpuAbiString;
9253                if (scannedPackage != null) {
9254                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9255                }
9256            } else {
9257                // requirer == null implies that we're updating all ABIs in the set to
9258                // match scannedPackage.
9259                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9260            }
9261
9262            for (PackageSetting ps : packagesForUser) {
9263                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9264                    if (ps.primaryCpuAbiString != null) {
9265                        continue;
9266                    }
9267
9268                    ps.primaryCpuAbiString = adjustedAbi;
9269                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9270                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9271                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9272                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9273                                + " (requirer="
9274                                + (requirer == null ? "null" : requirer.pkg.packageName)
9275                                + ", scannedPackage="
9276                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9277                                + ")");
9278                        try {
9279                            mInstaller.rmdex(ps.codePathString,
9280                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9281                        } catch (InstallerException ignored) {
9282                        }
9283                    }
9284                }
9285            }
9286        }
9287    }
9288
9289    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9290        synchronized (mPackages) {
9291            mResolverReplaced = true;
9292            // Set up information for custom user intent resolution activity.
9293            mResolveActivity.applicationInfo = pkg.applicationInfo;
9294            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9295            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9296            mResolveActivity.processName = pkg.applicationInfo.packageName;
9297            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9298            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9299                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9300            mResolveActivity.theme = 0;
9301            mResolveActivity.exported = true;
9302            mResolveActivity.enabled = true;
9303            mResolveInfo.activityInfo = mResolveActivity;
9304            mResolveInfo.priority = 0;
9305            mResolveInfo.preferredOrder = 0;
9306            mResolveInfo.match = 0;
9307            mResolveComponentName = mCustomResolverComponentName;
9308            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9309                    mResolveComponentName);
9310        }
9311    }
9312
9313    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9314        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9315
9316        // Set up information for ephemeral installer activity
9317        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9318        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9319        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9320        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9321        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9322        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9323                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9324        mEphemeralInstallerActivity.theme = 0;
9325        mEphemeralInstallerActivity.exported = true;
9326        mEphemeralInstallerActivity.enabled = true;
9327        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9328        mEphemeralInstallerInfo.priority = 0;
9329        mEphemeralInstallerInfo.preferredOrder = 0;
9330        mEphemeralInstallerInfo.match = 0;
9331
9332        if (DEBUG_EPHEMERAL) {
9333            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9334        }
9335    }
9336
9337    private static String calculateBundledApkRoot(final String codePathString) {
9338        final File codePath = new File(codePathString);
9339        final File codeRoot;
9340        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9341            codeRoot = Environment.getRootDirectory();
9342        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9343            codeRoot = Environment.getOemDirectory();
9344        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9345            codeRoot = Environment.getVendorDirectory();
9346        } else {
9347            // Unrecognized code path; take its top real segment as the apk root:
9348            // e.g. /something/app/blah.apk => /something
9349            try {
9350                File f = codePath.getCanonicalFile();
9351                File parent = f.getParentFile();    // non-null because codePath is a file
9352                File tmp;
9353                while ((tmp = parent.getParentFile()) != null) {
9354                    f = parent;
9355                    parent = tmp;
9356                }
9357                codeRoot = f;
9358                Slog.w(TAG, "Unrecognized code path "
9359                        + codePath + " - using " + codeRoot);
9360            } catch (IOException e) {
9361                // Can't canonicalize the code path -- shenanigans?
9362                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9363                return Environment.getRootDirectory().getPath();
9364            }
9365        }
9366        return codeRoot.getPath();
9367    }
9368
9369    /**
9370     * Derive and set the location of native libraries for the given package,
9371     * which varies depending on where and how the package was installed.
9372     */
9373    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9374        final ApplicationInfo info = pkg.applicationInfo;
9375        final String codePath = pkg.codePath;
9376        final File codeFile = new File(codePath);
9377        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9378        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9379
9380        info.nativeLibraryRootDir = null;
9381        info.nativeLibraryRootRequiresIsa = false;
9382        info.nativeLibraryDir = null;
9383        info.secondaryNativeLibraryDir = null;
9384
9385        if (isApkFile(codeFile)) {
9386            // Monolithic install
9387            if (bundledApp) {
9388                // If "/system/lib64/apkname" exists, assume that is the per-package
9389                // native library directory to use; otherwise use "/system/lib/apkname".
9390                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9391                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9392                        getPrimaryInstructionSet(info));
9393
9394                // This is a bundled system app so choose the path based on the ABI.
9395                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9396                // is just the default path.
9397                final String apkName = deriveCodePathName(codePath);
9398                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9399                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9400                        apkName).getAbsolutePath();
9401
9402                if (info.secondaryCpuAbi != null) {
9403                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9404                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9405                            secondaryLibDir, apkName).getAbsolutePath();
9406                }
9407            } else if (asecApp) {
9408                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9409                        .getAbsolutePath();
9410            } else {
9411                final String apkName = deriveCodePathName(codePath);
9412                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9413                        .getAbsolutePath();
9414            }
9415
9416            info.nativeLibraryRootRequiresIsa = false;
9417            info.nativeLibraryDir = info.nativeLibraryRootDir;
9418        } else {
9419            // Cluster install
9420            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9421            info.nativeLibraryRootRequiresIsa = true;
9422
9423            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9424                    getPrimaryInstructionSet(info)).getAbsolutePath();
9425
9426            if (info.secondaryCpuAbi != null) {
9427                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9428                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9429            }
9430        }
9431    }
9432
9433    /**
9434     * Calculate the abis and roots for a bundled app. These can uniquely
9435     * be determined from the contents of the system partition, i.e whether
9436     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9437     * of this information, and instead assume that the system was built
9438     * sensibly.
9439     */
9440    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9441                                           PackageSetting pkgSetting) {
9442        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9443
9444        // If "/system/lib64/apkname" exists, assume that is the per-package
9445        // native library directory to use; otherwise use "/system/lib/apkname".
9446        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9447        setBundledAppAbi(pkg, apkRoot, apkName);
9448        // pkgSetting might be null during rescan following uninstall of updates
9449        // to a bundled app, so accommodate that possibility.  The settings in
9450        // that case will be established later from the parsed package.
9451        //
9452        // If the settings aren't null, sync them up with what we've just derived.
9453        // note that apkRoot isn't stored in the package settings.
9454        if (pkgSetting != null) {
9455            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9456            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9457        }
9458    }
9459
9460    /**
9461     * Deduces the ABI of a bundled app and sets the relevant fields on the
9462     * parsed pkg object.
9463     *
9464     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9465     *        under which system libraries are installed.
9466     * @param apkName the name of the installed package.
9467     */
9468    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9469        final File codeFile = new File(pkg.codePath);
9470
9471        final boolean has64BitLibs;
9472        final boolean has32BitLibs;
9473        if (isApkFile(codeFile)) {
9474            // Monolithic install
9475            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9476            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9477        } else {
9478            // Cluster install
9479            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9480            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9481                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9482                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9483                has64BitLibs = (new File(rootDir, isa)).exists();
9484            } else {
9485                has64BitLibs = false;
9486            }
9487            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9488                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9489                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9490                has32BitLibs = (new File(rootDir, isa)).exists();
9491            } else {
9492                has32BitLibs = false;
9493            }
9494        }
9495
9496        if (has64BitLibs && !has32BitLibs) {
9497            // The package has 64 bit libs, but not 32 bit libs. Its primary
9498            // ABI should be 64 bit. We can safely assume here that the bundled
9499            // native libraries correspond to the most preferred ABI in the list.
9500
9501            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9502            pkg.applicationInfo.secondaryCpuAbi = null;
9503        } else if (has32BitLibs && !has64BitLibs) {
9504            // The package has 32 bit libs but not 64 bit libs. Its primary
9505            // ABI should be 32 bit.
9506
9507            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9508            pkg.applicationInfo.secondaryCpuAbi = null;
9509        } else if (has32BitLibs && has64BitLibs) {
9510            // The application has both 64 and 32 bit bundled libraries. We check
9511            // here that the app declares multiArch support, and warn if it doesn't.
9512            //
9513            // We will be lenient here and record both ABIs. The primary will be the
9514            // ABI that's higher on the list, i.e, a device that's configured to prefer
9515            // 64 bit apps will see a 64 bit primary ABI,
9516
9517            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9518                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9519            }
9520
9521            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9522                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9523                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9524            } else {
9525                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9526                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9527            }
9528        } else {
9529            pkg.applicationInfo.primaryCpuAbi = null;
9530            pkg.applicationInfo.secondaryCpuAbi = null;
9531        }
9532    }
9533
9534    private void killApplication(String pkgName, int appId, String reason) {
9535        // Request the ActivityManager to kill the process(only for existing packages)
9536        // so that we do not end up in a confused state while the user is still using the older
9537        // version of the application while the new one gets installed.
9538        final long token = Binder.clearCallingIdentity();
9539        try {
9540            IActivityManager am = ActivityManagerNative.getDefault();
9541            if (am != null) {
9542                try {
9543                    am.killApplicationWithAppId(pkgName, appId, reason);
9544                } catch (RemoteException e) {
9545                }
9546            }
9547        } finally {
9548            Binder.restoreCallingIdentity(token);
9549        }
9550    }
9551
9552    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9553        // Remove the parent package setting
9554        PackageSetting ps = (PackageSetting) pkg.mExtras;
9555        if (ps != null) {
9556            removePackageLI(ps, chatty);
9557        }
9558        // Remove the child package setting
9559        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9560        for (int i = 0; i < childCount; i++) {
9561            PackageParser.Package childPkg = pkg.childPackages.get(i);
9562            ps = (PackageSetting) childPkg.mExtras;
9563            if (ps != null) {
9564                removePackageLI(ps, chatty);
9565            }
9566        }
9567    }
9568
9569    void removePackageLI(PackageSetting ps, boolean chatty) {
9570        if (DEBUG_INSTALL) {
9571            if (chatty)
9572                Log.d(TAG, "Removing package " + ps.name);
9573        }
9574
9575        // writer
9576        synchronized (mPackages) {
9577            mPackages.remove(ps.name);
9578            final PackageParser.Package pkg = ps.pkg;
9579            if (pkg != null) {
9580                cleanPackageDataStructuresLILPw(pkg, chatty);
9581            }
9582        }
9583    }
9584
9585    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9586        if (DEBUG_INSTALL) {
9587            if (chatty)
9588                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9589        }
9590
9591        // writer
9592        synchronized (mPackages) {
9593            // Remove the parent package
9594            mPackages.remove(pkg.applicationInfo.packageName);
9595            cleanPackageDataStructuresLILPw(pkg, chatty);
9596
9597            // Remove the child packages
9598            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9599            for (int i = 0; i < childCount; i++) {
9600                PackageParser.Package childPkg = pkg.childPackages.get(i);
9601                mPackages.remove(childPkg.applicationInfo.packageName);
9602                cleanPackageDataStructuresLILPw(childPkg, chatty);
9603            }
9604        }
9605    }
9606
9607    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9608        int N = pkg.providers.size();
9609        StringBuilder r = null;
9610        int i;
9611        for (i=0; i<N; i++) {
9612            PackageParser.Provider p = pkg.providers.get(i);
9613            mProviders.removeProvider(p);
9614            if (p.info.authority == null) {
9615
9616                /* There was another ContentProvider with this authority when
9617                 * this app was installed so this authority is null,
9618                 * Ignore it as we don't have to unregister the provider.
9619                 */
9620                continue;
9621            }
9622            String names[] = p.info.authority.split(";");
9623            for (int j = 0; j < names.length; j++) {
9624                if (mProvidersByAuthority.get(names[j]) == p) {
9625                    mProvidersByAuthority.remove(names[j]);
9626                    if (DEBUG_REMOVE) {
9627                        if (chatty)
9628                            Log.d(TAG, "Unregistered content provider: " + names[j]
9629                                    + ", className = " + p.info.name + ", isSyncable = "
9630                                    + p.info.isSyncable);
9631                    }
9632                }
9633            }
9634            if (DEBUG_REMOVE && chatty) {
9635                if (r == null) {
9636                    r = new StringBuilder(256);
9637                } else {
9638                    r.append(' ');
9639                }
9640                r.append(p.info.name);
9641            }
9642        }
9643        if (r != null) {
9644            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9645        }
9646
9647        N = pkg.services.size();
9648        r = null;
9649        for (i=0; i<N; i++) {
9650            PackageParser.Service s = pkg.services.get(i);
9651            mServices.removeService(s);
9652            if (chatty) {
9653                if (r == null) {
9654                    r = new StringBuilder(256);
9655                } else {
9656                    r.append(' ');
9657                }
9658                r.append(s.info.name);
9659            }
9660        }
9661        if (r != null) {
9662            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9663        }
9664
9665        N = pkg.receivers.size();
9666        r = null;
9667        for (i=0; i<N; i++) {
9668            PackageParser.Activity a = pkg.receivers.get(i);
9669            mReceivers.removeActivity(a, "receiver");
9670            if (DEBUG_REMOVE && chatty) {
9671                if (r == null) {
9672                    r = new StringBuilder(256);
9673                } else {
9674                    r.append(' ');
9675                }
9676                r.append(a.info.name);
9677            }
9678        }
9679        if (r != null) {
9680            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9681        }
9682
9683        N = pkg.activities.size();
9684        r = null;
9685        for (i=0; i<N; i++) {
9686            PackageParser.Activity a = pkg.activities.get(i);
9687            mActivities.removeActivity(a, "activity");
9688            if (DEBUG_REMOVE && chatty) {
9689                if (r == null) {
9690                    r = new StringBuilder(256);
9691                } else {
9692                    r.append(' ');
9693                }
9694                r.append(a.info.name);
9695            }
9696        }
9697        if (r != null) {
9698            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9699        }
9700
9701        N = pkg.permissions.size();
9702        r = null;
9703        for (i=0; i<N; i++) {
9704            PackageParser.Permission p = pkg.permissions.get(i);
9705            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9706            if (bp == null) {
9707                bp = mSettings.mPermissionTrees.get(p.info.name);
9708            }
9709            if (bp != null && bp.perm == p) {
9710                bp.perm = null;
9711                if (DEBUG_REMOVE && chatty) {
9712                    if (r == null) {
9713                        r = new StringBuilder(256);
9714                    } else {
9715                        r.append(' ');
9716                    }
9717                    r.append(p.info.name);
9718                }
9719            }
9720            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9721                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9722                if (appOpPkgs != null) {
9723                    appOpPkgs.remove(pkg.packageName);
9724                }
9725            }
9726        }
9727        if (r != null) {
9728            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9729        }
9730
9731        N = pkg.requestedPermissions.size();
9732        r = null;
9733        for (i=0; i<N; i++) {
9734            String perm = pkg.requestedPermissions.get(i);
9735            BasePermission bp = mSettings.mPermissions.get(perm);
9736            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9737                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9738                if (appOpPkgs != null) {
9739                    appOpPkgs.remove(pkg.packageName);
9740                    if (appOpPkgs.isEmpty()) {
9741                        mAppOpPermissionPackages.remove(perm);
9742                    }
9743                }
9744            }
9745        }
9746        if (r != null) {
9747            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9748        }
9749
9750        N = pkg.instrumentation.size();
9751        r = null;
9752        for (i=0; i<N; i++) {
9753            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9754            mInstrumentation.remove(a.getComponentName());
9755            if (DEBUG_REMOVE && chatty) {
9756                if (r == null) {
9757                    r = new StringBuilder(256);
9758                } else {
9759                    r.append(' ');
9760                }
9761                r.append(a.info.name);
9762            }
9763        }
9764        if (r != null) {
9765            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9766        }
9767
9768        r = null;
9769        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9770            // Only system apps can hold shared libraries.
9771            if (pkg.libraryNames != null) {
9772                for (i=0; i<pkg.libraryNames.size(); i++) {
9773                    String name = pkg.libraryNames.get(i);
9774                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9775                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9776                        mSharedLibraries.remove(name);
9777                        if (DEBUG_REMOVE && chatty) {
9778                            if (r == null) {
9779                                r = new StringBuilder(256);
9780                            } else {
9781                                r.append(' ');
9782                            }
9783                            r.append(name);
9784                        }
9785                    }
9786                }
9787            }
9788        }
9789        if (r != null) {
9790            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9791        }
9792    }
9793
9794    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9795        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9796            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9797                return true;
9798            }
9799        }
9800        return false;
9801    }
9802
9803    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9804    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9805    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9806
9807    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9808        // Update the parent permissions
9809        updatePermissionsLPw(pkg.packageName, pkg, flags);
9810        // Update the child permissions
9811        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9812        for (int i = 0; i < childCount; i++) {
9813            PackageParser.Package childPkg = pkg.childPackages.get(i);
9814            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9815        }
9816    }
9817
9818    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9819            int flags) {
9820        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9821        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9822    }
9823
9824    private void updatePermissionsLPw(String changingPkg,
9825            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9826        // Make sure there are no dangling permission trees.
9827        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9828        while (it.hasNext()) {
9829            final BasePermission bp = it.next();
9830            if (bp.packageSetting == null) {
9831                // We may not yet have parsed the package, so just see if
9832                // we still know about its settings.
9833                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9834            }
9835            if (bp.packageSetting == null) {
9836                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9837                        + " from package " + bp.sourcePackage);
9838                it.remove();
9839            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9840                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9841                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9842                            + " from package " + bp.sourcePackage);
9843                    flags |= UPDATE_PERMISSIONS_ALL;
9844                    it.remove();
9845                }
9846            }
9847        }
9848
9849        // Make sure all dynamic permissions have been assigned to a package,
9850        // and make sure there are no dangling permissions.
9851        it = mSettings.mPermissions.values().iterator();
9852        while (it.hasNext()) {
9853            final BasePermission bp = it.next();
9854            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9855                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9856                        + bp.name + " pkg=" + bp.sourcePackage
9857                        + " info=" + bp.pendingInfo);
9858                if (bp.packageSetting == null && bp.pendingInfo != null) {
9859                    final BasePermission tree = findPermissionTreeLP(bp.name);
9860                    if (tree != null && tree.perm != null) {
9861                        bp.packageSetting = tree.packageSetting;
9862                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9863                                new PermissionInfo(bp.pendingInfo));
9864                        bp.perm.info.packageName = tree.perm.info.packageName;
9865                        bp.perm.info.name = bp.name;
9866                        bp.uid = tree.uid;
9867                    }
9868                }
9869            }
9870            if (bp.packageSetting == null) {
9871                // We may not yet have parsed the package, so just see if
9872                // we still know about its settings.
9873                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9874            }
9875            if (bp.packageSetting == null) {
9876                Slog.w(TAG, "Removing dangling permission: " + bp.name
9877                        + " from package " + bp.sourcePackage);
9878                it.remove();
9879            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9880                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9881                    Slog.i(TAG, "Removing old permission: " + bp.name
9882                            + " from package " + bp.sourcePackage);
9883                    flags |= UPDATE_PERMISSIONS_ALL;
9884                    it.remove();
9885                }
9886            }
9887        }
9888
9889        // Now update the permissions for all packages, in particular
9890        // replace the granted permissions of the system packages.
9891        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9892            for (PackageParser.Package pkg : mPackages.values()) {
9893                if (pkg != pkgInfo) {
9894                    // Only replace for packages on requested volume
9895                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9896                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9897                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9898                    grantPermissionsLPw(pkg, replace, changingPkg);
9899                }
9900            }
9901        }
9902
9903        if (pkgInfo != null) {
9904            // Only replace for packages on requested volume
9905            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9906            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9907                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9908            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9909        }
9910    }
9911
9912    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9913            String packageOfInterest) {
9914        // IMPORTANT: There are two types of permissions: install and runtime.
9915        // Install time permissions are granted when the app is installed to
9916        // all device users and users added in the future. Runtime permissions
9917        // are granted at runtime explicitly to specific users. Normal and signature
9918        // protected permissions are install time permissions. Dangerous permissions
9919        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9920        // otherwise they are runtime permissions. This function does not manage
9921        // runtime permissions except for the case an app targeting Lollipop MR1
9922        // being upgraded to target a newer SDK, in which case dangerous permissions
9923        // are transformed from install time to runtime ones.
9924
9925        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9926        if (ps == null) {
9927            return;
9928        }
9929
9930        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9931
9932        PermissionsState permissionsState = ps.getPermissionsState();
9933        PermissionsState origPermissions = permissionsState;
9934
9935        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9936
9937        boolean runtimePermissionsRevoked = false;
9938        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9939
9940        boolean changedInstallPermission = false;
9941
9942        if (replace) {
9943            ps.installPermissionsFixed = false;
9944            if (!ps.isSharedUser()) {
9945                origPermissions = new PermissionsState(permissionsState);
9946                permissionsState.reset();
9947            } else {
9948                // We need to know only about runtime permission changes since the
9949                // calling code always writes the install permissions state but
9950                // the runtime ones are written only if changed. The only cases of
9951                // changed runtime permissions here are promotion of an install to
9952                // runtime and revocation of a runtime from a shared user.
9953                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9954                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9955                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9956                    runtimePermissionsRevoked = true;
9957                }
9958            }
9959        }
9960
9961        permissionsState.setGlobalGids(mGlobalGids);
9962
9963        final int N = pkg.requestedPermissions.size();
9964        for (int i=0; i<N; i++) {
9965            final String name = pkg.requestedPermissions.get(i);
9966            final BasePermission bp = mSettings.mPermissions.get(name);
9967
9968            if (DEBUG_INSTALL) {
9969                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9970            }
9971
9972            if (bp == null || bp.packageSetting == null) {
9973                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9974                    Slog.w(TAG, "Unknown permission " + name
9975                            + " in package " + pkg.packageName);
9976                }
9977                continue;
9978            }
9979
9980            final String perm = bp.name;
9981            boolean allowedSig = false;
9982            int grant = GRANT_DENIED;
9983
9984            // Keep track of app op permissions.
9985            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9986                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9987                if (pkgs == null) {
9988                    pkgs = new ArraySet<>();
9989                    mAppOpPermissionPackages.put(bp.name, pkgs);
9990                }
9991                pkgs.add(pkg.packageName);
9992            }
9993
9994            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9995            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9996                    >= Build.VERSION_CODES.M;
9997            switch (level) {
9998                case PermissionInfo.PROTECTION_NORMAL: {
9999                    // For all apps normal permissions are install time ones.
10000                    grant = GRANT_INSTALL;
10001                } break;
10002
10003                case PermissionInfo.PROTECTION_DANGEROUS: {
10004                    // If a permission review is required for legacy apps we represent
10005                    // their permissions as always granted runtime ones since we need
10006                    // to keep the review required permission flag per user while an
10007                    // install permission's state is shared across all users.
10008                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10009                        // For legacy apps dangerous permissions are install time ones.
10010                        grant = GRANT_INSTALL;
10011                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10012                        // For legacy apps that became modern, install becomes runtime.
10013                        grant = GRANT_UPGRADE;
10014                    } else if (mPromoteSystemApps
10015                            && isSystemApp(ps)
10016                            && mExistingSystemPackages.contains(ps.name)) {
10017                        // For legacy system apps, install becomes runtime.
10018                        // We cannot check hasInstallPermission() for system apps since those
10019                        // permissions were granted implicitly and not persisted pre-M.
10020                        grant = GRANT_UPGRADE;
10021                    } else {
10022                        // For modern apps keep runtime permissions unchanged.
10023                        grant = GRANT_RUNTIME;
10024                    }
10025                } break;
10026
10027                case PermissionInfo.PROTECTION_SIGNATURE: {
10028                    // For all apps signature permissions are install time ones.
10029                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10030                    if (allowedSig) {
10031                        grant = GRANT_INSTALL;
10032                    }
10033                } break;
10034            }
10035
10036            if (DEBUG_INSTALL) {
10037                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10038            }
10039
10040            if (grant != GRANT_DENIED) {
10041                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10042                    // If this is an existing, non-system package, then
10043                    // we can't add any new permissions to it.
10044                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10045                        // Except...  if this is a permission that was added
10046                        // to the platform (note: need to only do this when
10047                        // updating the platform).
10048                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10049                            grant = GRANT_DENIED;
10050                        }
10051                    }
10052                }
10053
10054                switch (grant) {
10055                    case GRANT_INSTALL: {
10056                        // Revoke this as runtime permission to handle the case of
10057                        // a runtime permission being downgraded to an install one.
10058                        // Also in permission review mode we keep dangerous permissions
10059                        // for legacy apps
10060                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10061                            if (origPermissions.getRuntimePermissionState(
10062                                    bp.name, userId) != null) {
10063                                // Revoke the runtime permission and clear the flags.
10064                                origPermissions.revokeRuntimePermission(bp, userId);
10065                                origPermissions.updatePermissionFlags(bp, userId,
10066                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10067                                // If we revoked a permission permission, we have to write.
10068                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10069                                        changedRuntimePermissionUserIds, userId);
10070                            }
10071                        }
10072                        // Grant an install permission.
10073                        if (permissionsState.grantInstallPermission(bp) !=
10074                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10075                            changedInstallPermission = true;
10076                        }
10077                    } break;
10078
10079                    case GRANT_RUNTIME: {
10080                        // Grant previously granted runtime permissions.
10081                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10082                            PermissionState permissionState = origPermissions
10083                                    .getRuntimePermissionState(bp.name, userId);
10084                            int flags = permissionState != null
10085                                    ? permissionState.getFlags() : 0;
10086                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10087                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10088                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10089                                    // If we cannot put the permission as it was, we have to write.
10090                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10091                                            changedRuntimePermissionUserIds, userId);
10092                                }
10093                                // If the app supports runtime permissions no need for a review.
10094                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10095                                        && appSupportsRuntimePermissions
10096                                        && (flags & PackageManager
10097                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10098                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10099                                    // Since we changed the flags, we have to write.
10100                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10101                                            changedRuntimePermissionUserIds, userId);
10102                                }
10103                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10104                                    && !appSupportsRuntimePermissions) {
10105                                // For legacy apps that need a permission review, every new
10106                                // runtime permission is granted but it is pending a review.
10107                                // We also need to review only platform defined runtime
10108                                // permissions as these are the only ones the platform knows
10109                                // how to disable the API to simulate revocation as legacy
10110                                // apps don't expect to run with revoked permissions.
10111                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10112                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10113                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10114                                        // We changed the flags, hence have to write.
10115                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10116                                                changedRuntimePermissionUserIds, userId);
10117                                    }
10118                                }
10119                                if (permissionsState.grantRuntimePermission(bp, userId)
10120                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10121                                    // We changed the permission, hence have to write.
10122                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10123                                            changedRuntimePermissionUserIds, userId);
10124                                }
10125                            }
10126                            // Propagate the permission flags.
10127                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10128                        }
10129                    } break;
10130
10131                    case GRANT_UPGRADE: {
10132                        // Grant runtime permissions for a previously held install permission.
10133                        PermissionState permissionState = origPermissions
10134                                .getInstallPermissionState(bp.name);
10135                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10136
10137                        if (origPermissions.revokeInstallPermission(bp)
10138                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10139                            // We will be transferring the permission flags, so clear them.
10140                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10141                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10142                            changedInstallPermission = true;
10143                        }
10144
10145                        // If the permission is not to be promoted to runtime we ignore it and
10146                        // also its other flags as they are not applicable to install permissions.
10147                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10148                            for (int userId : currentUserIds) {
10149                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10150                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10151                                    // Transfer the permission flags.
10152                                    permissionsState.updatePermissionFlags(bp, userId,
10153                                            flags, flags);
10154                                    // If we granted the permission, we have to write.
10155                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10156                                            changedRuntimePermissionUserIds, userId);
10157                                }
10158                            }
10159                        }
10160                    } break;
10161
10162                    default: {
10163                        if (packageOfInterest == null
10164                                || packageOfInterest.equals(pkg.packageName)) {
10165                            Slog.w(TAG, "Not granting permission " + perm
10166                                    + " to package " + pkg.packageName
10167                                    + " because it was previously installed without");
10168                        }
10169                    } break;
10170                }
10171            } else {
10172                if (permissionsState.revokeInstallPermission(bp) !=
10173                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10174                    // Also drop the permission flags.
10175                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10176                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10177                    changedInstallPermission = true;
10178                    Slog.i(TAG, "Un-granting permission " + perm
10179                            + " from package " + pkg.packageName
10180                            + " (protectionLevel=" + bp.protectionLevel
10181                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10182                            + ")");
10183                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10184                    // Don't print warning for app op permissions, since it is fine for them
10185                    // not to be granted, there is a UI for the user to decide.
10186                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10187                        Slog.w(TAG, "Not granting permission " + perm
10188                                + " to package " + pkg.packageName
10189                                + " (protectionLevel=" + bp.protectionLevel
10190                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10191                                + ")");
10192                    }
10193                }
10194            }
10195        }
10196
10197        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10198                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10199            // This is the first that we have heard about this package, so the
10200            // permissions we have now selected are fixed until explicitly
10201            // changed.
10202            ps.installPermissionsFixed = true;
10203        }
10204
10205        // Persist the runtime permissions state for users with changes. If permissions
10206        // were revoked because no app in the shared user declares them we have to
10207        // write synchronously to avoid losing runtime permissions state.
10208        for (int userId : changedRuntimePermissionUserIds) {
10209            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10210        }
10211
10212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10213    }
10214
10215    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10216        boolean allowed = false;
10217        final int NP = PackageParser.NEW_PERMISSIONS.length;
10218        for (int ip=0; ip<NP; ip++) {
10219            final PackageParser.NewPermissionInfo npi
10220                    = PackageParser.NEW_PERMISSIONS[ip];
10221            if (npi.name.equals(perm)
10222                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10223                allowed = true;
10224                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10225                        + pkg.packageName);
10226                break;
10227            }
10228        }
10229        return allowed;
10230    }
10231
10232    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10233            BasePermission bp, PermissionsState origPermissions) {
10234        boolean allowed;
10235        allowed = (compareSignatures(
10236                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10237                        == PackageManager.SIGNATURE_MATCH)
10238                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10239                        == PackageManager.SIGNATURE_MATCH);
10240        if (!allowed && (bp.protectionLevel
10241                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10242            if (isSystemApp(pkg)) {
10243                // For updated system applications, a system permission
10244                // is granted only if it had been defined by the original application.
10245                if (pkg.isUpdatedSystemApp()) {
10246                    final PackageSetting sysPs = mSettings
10247                            .getDisabledSystemPkgLPr(pkg.packageName);
10248                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10249                        // If the original was granted this permission, we take
10250                        // that grant decision as read and propagate it to the
10251                        // update.
10252                        if (sysPs.isPrivileged()) {
10253                            allowed = true;
10254                        }
10255                    } else {
10256                        // The system apk may have been updated with an older
10257                        // version of the one on the data partition, but which
10258                        // granted a new system permission that it didn't have
10259                        // before.  In this case we do want to allow the app to
10260                        // now get the new permission if the ancestral apk is
10261                        // privileged to get it.
10262                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10263                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10264                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10265                                    allowed = true;
10266                                    break;
10267                                }
10268                            }
10269                        }
10270                        // Also if a privileged parent package on the system image or any of
10271                        // its children requested a privileged permission, the updated child
10272                        // packages can also get the permission.
10273                        if (pkg.parentPackage != null) {
10274                            final PackageSetting disabledSysParentPs = mSettings
10275                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10276                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10277                                    && disabledSysParentPs.isPrivileged()) {
10278                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10279                                    allowed = true;
10280                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10281                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10282                                    for (int i = 0; i < count; i++) {
10283                                        PackageParser.Package disabledSysChildPkg =
10284                                                disabledSysParentPs.pkg.childPackages.get(i);
10285                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10286                                                perm)) {
10287                                            allowed = true;
10288                                            break;
10289                                        }
10290                                    }
10291                                }
10292                            }
10293                        }
10294                    }
10295                } else {
10296                    allowed = isPrivilegedApp(pkg);
10297                }
10298            }
10299        }
10300        if (!allowed) {
10301            if (!allowed && (bp.protectionLevel
10302                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10303                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10304                // If this was a previously normal/dangerous permission that got moved
10305                // to a system permission as part of the runtime permission redesign, then
10306                // we still want to blindly grant it to old apps.
10307                allowed = true;
10308            }
10309            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10310                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10311                // If this permission is to be granted to the system installer and
10312                // this app is an installer, then it gets the permission.
10313                allowed = true;
10314            }
10315            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10316                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10317                // If this permission is to be granted to the system verifier and
10318                // this app is a verifier, then it gets the permission.
10319                allowed = true;
10320            }
10321            if (!allowed && (bp.protectionLevel
10322                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10323                    && isSystemApp(pkg)) {
10324                // Any pre-installed system app is allowed to get this permission.
10325                allowed = true;
10326            }
10327            if (!allowed && (bp.protectionLevel
10328                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10329                // For development permissions, a development permission
10330                // is granted only if it was already granted.
10331                allowed = origPermissions.hasInstallPermission(perm);
10332            }
10333            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10334                    && pkg.packageName.equals(mSetupWizardPackage)) {
10335                // If this permission is to be granted to the system setup wizard and
10336                // this app is a setup wizard, then it gets the permission.
10337                allowed = true;
10338            }
10339        }
10340        return allowed;
10341    }
10342
10343    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10344        final int permCount = pkg.requestedPermissions.size();
10345        for (int j = 0; j < permCount; j++) {
10346            String requestedPermission = pkg.requestedPermissions.get(j);
10347            if (permission.equals(requestedPermission)) {
10348                return true;
10349            }
10350        }
10351        return false;
10352    }
10353
10354    final class ActivityIntentResolver
10355            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10356        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10357                boolean defaultOnly, int userId) {
10358            if (!sUserManager.exists(userId)) return null;
10359            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10360            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10361        }
10362
10363        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10364                int userId) {
10365            if (!sUserManager.exists(userId)) return null;
10366            mFlags = flags;
10367            return super.queryIntent(intent, resolvedType,
10368                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10369        }
10370
10371        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10372                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10373            if (!sUserManager.exists(userId)) return null;
10374            if (packageActivities == null) {
10375                return null;
10376            }
10377            mFlags = flags;
10378            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10379            final int N = packageActivities.size();
10380            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10381                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10382
10383            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10384            for (int i = 0; i < N; ++i) {
10385                intentFilters = packageActivities.get(i).intents;
10386                if (intentFilters != null && intentFilters.size() > 0) {
10387                    PackageParser.ActivityIntentInfo[] array =
10388                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10389                    intentFilters.toArray(array);
10390                    listCut.add(array);
10391                }
10392            }
10393            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10394        }
10395
10396        /**
10397         * Finds a privileged activity that matches the specified activity names.
10398         */
10399        private PackageParser.Activity findMatchingActivity(
10400                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10401            for (PackageParser.Activity sysActivity : activityList) {
10402                if (sysActivity.info.name.equals(activityInfo.name)) {
10403                    return sysActivity;
10404                }
10405                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10406                    return sysActivity;
10407                }
10408                if (sysActivity.info.targetActivity != null) {
10409                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10410                        return sysActivity;
10411                    }
10412                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10413                        return sysActivity;
10414                    }
10415                }
10416            }
10417            return null;
10418        }
10419
10420        public class IterGenerator<E> {
10421            public Iterator<E> generate(ActivityIntentInfo info) {
10422                return null;
10423            }
10424        }
10425
10426        public class ActionIterGenerator extends IterGenerator<String> {
10427            @Override
10428            public Iterator<String> generate(ActivityIntentInfo info) {
10429                return info.actionsIterator();
10430            }
10431        }
10432
10433        public class CategoriesIterGenerator extends IterGenerator<String> {
10434            @Override
10435            public Iterator<String> generate(ActivityIntentInfo info) {
10436                return info.categoriesIterator();
10437            }
10438        }
10439
10440        public class SchemesIterGenerator extends IterGenerator<String> {
10441            @Override
10442            public Iterator<String> generate(ActivityIntentInfo info) {
10443                return info.schemesIterator();
10444            }
10445        }
10446
10447        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10448            @Override
10449            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10450                return info.authoritiesIterator();
10451            }
10452        }
10453
10454        /**
10455         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10456         * MODIFIED. Do not pass in a list that should not be changed.
10457         */
10458        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10459                IterGenerator<T> generator, Iterator<T> searchIterator) {
10460            // loop through the set of actions; every one must be found in the intent filter
10461            while (searchIterator.hasNext()) {
10462                // we must have at least one filter in the list to consider a match
10463                if (intentList.size() == 0) {
10464                    break;
10465                }
10466
10467                final T searchAction = searchIterator.next();
10468
10469                // loop through the set of intent filters
10470                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10471                while (intentIter.hasNext()) {
10472                    final ActivityIntentInfo intentInfo = intentIter.next();
10473                    boolean selectionFound = false;
10474
10475                    // loop through the intent filter's selection criteria; at least one
10476                    // of them must match the searched criteria
10477                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10478                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10479                        final T intentSelection = intentSelectionIter.next();
10480                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10481                            selectionFound = true;
10482                            break;
10483                        }
10484                    }
10485
10486                    // the selection criteria wasn't found in this filter's set; this filter
10487                    // is not a potential match
10488                    if (!selectionFound) {
10489                        intentIter.remove();
10490                    }
10491                }
10492            }
10493        }
10494
10495        private boolean isProtectedAction(ActivityIntentInfo filter) {
10496            final Iterator<String> actionsIter = filter.actionsIterator();
10497            while (actionsIter != null && actionsIter.hasNext()) {
10498                final String filterAction = actionsIter.next();
10499                if (PROTECTED_ACTIONS.contains(filterAction)) {
10500                    return true;
10501                }
10502            }
10503            return false;
10504        }
10505
10506        /**
10507         * Adjusts the priority of the given intent filter according to policy.
10508         * <p>
10509         * <ul>
10510         * <li>The priority for non privileged applications is capped to '0'</li>
10511         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10512         * <li>The priority for unbundled updates to privileged applications is capped to the
10513         *      priority defined on the system partition</li>
10514         * </ul>
10515         * <p>
10516         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10517         * allowed to obtain any priority on any action.
10518         */
10519        private void adjustPriority(
10520                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10521            // nothing to do; priority is fine as-is
10522            if (intent.getPriority() <= 0) {
10523                return;
10524            }
10525
10526            final ActivityInfo activityInfo = intent.activity.info;
10527            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10528
10529            final boolean privilegedApp =
10530                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10531            if (!privilegedApp) {
10532                // non-privileged applications can never define a priority >0
10533                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10534                        + " package: " + applicationInfo.packageName
10535                        + " activity: " + intent.activity.className
10536                        + " origPrio: " + intent.getPriority());
10537                intent.setPriority(0);
10538                return;
10539            }
10540
10541            if (systemActivities == null) {
10542                // the system package is not disabled; we're parsing the system partition
10543                if (isProtectedAction(intent)) {
10544                    if (mDeferProtectedFilters) {
10545                        // We can't deal with these just yet. No component should ever obtain a
10546                        // >0 priority for a protected actions, with ONE exception -- the setup
10547                        // wizard. The setup wizard, however, cannot be known until we're able to
10548                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10549                        // until all intent filters have been processed. Chicken, meet egg.
10550                        // Let the filter temporarily have a high priority and rectify the
10551                        // priorities after all system packages have been scanned.
10552                        mProtectedFilters.add(intent);
10553                        if (DEBUG_FILTERS) {
10554                            Slog.i(TAG, "Protected action; save for later;"
10555                                    + " package: " + applicationInfo.packageName
10556                                    + " activity: " + intent.activity.className
10557                                    + " origPrio: " + intent.getPriority());
10558                        }
10559                        return;
10560                    } else {
10561                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10562                            Slog.i(TAG, "No setup wizard;"
10563                                + " All protected intents capped to priority 0");
10564                        }
10565                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10566                            if (DEBUG_FILTERS) {
10567                                Slog.i(TAG, "Found setup wizard;"
10568                                    + " allow priority " + intent.getPriority() + ";"
10569                                    + " package: " + intent.activity.info.packageName
10570                                    + " activity: " + intent.activity.className
10571                                    + " priority: " + intent.getPriority());
10572                            }
10573                            // setup wizard gets whatever it wants
10574                            return;
10575                        }
10576                        Slog.w(TAG, "Protected action; cap priority to 0;"
10577                                + " package: " + intent.activity.info.packageName
10578                                + " activity: " + intent.activity.className
10579                                + " origPrio: " + intent.getPriority());
10580                        intent.setPriority(0);
10581                        return;
10582                    }
10583                }
10584                // privileged apps on the system image get whatever priority they request
10585                return;
10586            }
10587
10588            // privileged app unbundled update ... try to find the same activity
10589            final PackageParser.Activity foundActivity =
10590                    findMatchingActivity(systemActivities, activityInfo);
10591            if (foundActivity == null) {
10592                // this is a new activity; it cannot obtain >0 priority
10593                if (DEBUG_FILTERS) {
10594                    Slog.i(TAG, "New activity; cap priority to 0;"
10595                            + " package: " + applicationInfo.packageName
10596                            + " activity: " + intent.activity.className
10597                            + " origPrio: " + intent.getPriority());
10598                }
10599                intent.setPriority(0);
10600                return;
10601            }
10602
10603            // found activity, now check for filter equivalence
10604
10605            // a shallow copy is enough; we modify the list, not its contents
10606            final List<ActivityIntentInfo> intentListCopy =
10607                    new ArrayList<>(foundActivity.intents);
10608            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10609
10610            // find matching action subsets
10611            final Iterator<String> actionsIterator = intent.actionsIterator();
10612            if (actionsIterator != null) {
10613                getIntentListSubset(
10614                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10615                if (intentListCopy.size() == 0) {
10616                    // no more intents to match; we're not equivalent
10617                    if (DEBUG_FILTERS) {
10618                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10619                                + " package: " + applicationInfo.packageName
10620                                + " activity: " + intent.activity.className
10621                                + " origPrio: " + intent.getPriority());
10622                    }
10623                    intent.setPriority(0);
10624                    return;
10625                }
10626            }
10627
10628            // find matching category subsets
10629            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10630            if (categoriesIterator != null) {
10631                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10632                        categoriesIterator);
10633                if (intentListCopy.size() == 0) {
10634                    // no more intents to match; we're not equivalent
10635                    if (DEBUG_FILTERS) {
10636                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10637                                + " package: " + applicationInfo.packageName
10638                                + " activity: " + intent.activity.className
10639                                + " origPrio: " + intent.getPriority());
10640                    }
10641                    intent.setPriority(0);
10642                    return;
10643                }
10644            }
10645
10646            // find matching schemes subsets
10647            final Iterator<String> schemesIterator = intent.schemesIterator();
10648            if (schemesIterator != null) {
10649                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10650                        schemesIterator);
10651                if (intentListCopy.size() == 0) {
10652                    // no more intents to match; we're not equivalent
10653                    if (DEBUG_FILTERS) {
10654                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10655                                + " package: " + applicationInfo.packageName
10656                                + " activity: " + intent.activity.className
10657                                + " origPrio: " + intent.getPriority());
10658                    }
10659                    intent.setPriority(0);
10660                    return;
10661                }
10662            }
10663
10664            // find matching authorities subsets
10665            final Iterator<IntentFilter.AuthorityEntry>
10666                    authoritiesIterator = intent.authoritiesIterator();
10667            if (authoritiesIterator != null) {
10668                getIntentListSubset(intentListCopy,
10669                        new AuthoritiesIterGenerator(),
10670                        authoritiesIterator);
10671                if (intentListCopy.size() == 0) {
10672                    // no more intents to match; we're not equivalent
10673                    if (DEBUG_FILTERS) {
10674                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10675                                + " package: " + applicationInfo.packageName
10676                                + " activity: " + intent.activity.className
10677                                + " origPrio: " + intent.getPriority());
10678                    }
10679                    intent.setPriority(0);
10680                    return;
10681                }
10682            }
10683
10684            // we found matching filter(s); app gets the max priority of all intents
10685            int cappedPriority = 0;
10686            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10687                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10688            }
10689            if (intent.getPriority() > cappedPriority) {
10690                if (DEBUG_FILTERS) {
10691                    Slog.i(TAG, "Found matching filter(s);"
10692                            + " cap priority to " + cappedPriority + ";"
10693                            + " package: " + applicationInfo.packageName
10694                            + " activity: " + intent.activity.className
10695                            + " origPrio: " + intent.getPriority());
10696                }
10697                intent.setPriority(cappedPriority);
10698                return;
10699            }
10700            // all this for nothing; the requested priority was <= what was on the system
10701        }
10702
10703        public final void addActivity(PackageParser.Activity a, String type) {
10704            mActivities.put(a.getComponentName(), a);
10705            if (DEBUG_SHOW_INFO)
10706                Log.v(
10707                TAG, "  " + type + " " +
10708                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10709            if (DEBUG_SHOW_INFO)
10710                Log.v(TAG, "    Class=" + a.info.name);
10711            final int NI = a.intents.size();
10712            for (int j=0; j<NI; j++) {
10713                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10714                if ("activity".equals(type)) {
10715                    final PackageSetting ps =
10716                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10717                    final List<PackageParser.Activity> systemActivities =
10718                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10719                    adjustPriority(systemActivities, intent);
10720                }
10721                if (DEBUG_SHOW_INFO) {
10722                    Log.v(TAG, "    IntentFilter:");
10723                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10724                }
10725                if (!intent.debugCheck()) {
10726                    Log.w(TAG, "==> For Activity " + a.info.name);
10727                }
10728                addFilter(intent);
10729            }
10730        }
10731
10732        public final void removeActivity(PackageParser.Activity a, String type) {
10733            mActivities.remove(a.getComponentName());
10734            if (DEBUG_SHOW_INFO) {
10735                Log.v(TAG, "  " + type + " "
10736                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10737                                : a.info.name) + ":");
10738                Log.v(TAG, "    Class=" + a.info.name);
10739            }
10740            final int NI = a.intents.size();
10741            for (int j=0; j<NI; j++) {
10742                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10743                if (DEBUG_SHOW_INFO) {
10744                    Log.v(TAG, "    IntentFilter:");
10745                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10746                }
10747                removeFilter(intent);
10748            }
10749        }
10750
10751        @Override
10752        protected boolean allowFilterResult(
10753                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10754            ActivityInfo filterAi = filter.activity.info;
10755            for (int i=dest.size()-1; i>=0; i--) {
10756                ActivityInfo destAi = dest.get(i).activityInfo;
10757                if (destAi.name == filterAi.name
10758                        && destAi.packageName == filterAi.packageName) {
10759                    return false;
10760                }
10761            }
10762            return true;
10763        }
10764
10765        @Override
10766        protected ActivityIntentInfo[] newArray(int size) {
10767            return new ActivityIntentInfo[size];
10768        }
10769
10770        @Override
10771        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10772            if (!sUserManager.exists(userId)) return true;
10773            PackageParser.Package p = filter.activity.owner;
10774            if (p != null) {
10775                PackageSetting ps = (PackageSetting)p.mExtras;
10776                if (ps != null) {
10777                    // System apps are never considered stopped for purposes of
10778                    // filtering, because there may be no way for the user to
10779                    // actually re-launch them.
10780                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10781                            && ps.getStopped(userId);
10782                }
10783            }
10784            return false;
10785        }
10786
10787        @Override
10788        protected boolean isPackageForFilter(String packageName,
10789                PackageParser.ActivityIntentInfo info) {
10790            return packageName.equals(info.activity.owner.packageName);
10791        }
10792
10793        @Override
10794        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10795                int match, int userId) {
10796            if (!sUserManager.exists(userId)) return null;
10797            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10798                return null;
10799            }
10800            final PackageParser.Activity activity = info.activity;
10801            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10802            if (ps == null) {
10803                return null;
10804            }
10805            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10806                    ps.readUserState(userId), userId);
10807            if (ai == null) {
10808                return null;
10809            }
10810            final ResolveInfo res = new ResolveInfo();
10811            res.activityInfo = ai;
10812            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10813                res.filter = info;
10814            }
10815            if (info != null) {
10816                res.handleAllWebDataURI = info.handleAllWebDataURI();
10817            }
10818            res.priority = info.getPriority();
10819            res.preferredOrder = activity.owner.mPreferredOrder;
10820            //System.out.println("Result: " + res.activityInfo.className +
10821            //                   " = " + res.priority);
10822            res.match = match;
10823            res.isDefault = info.hasDefault;
10824            res.labelRes = info.labelRes;
10825            res.nonLocalizedLabel = info.nonLocalizedLabel;
10826            if (userNeedsBadging(userId)) {
10827                res.noResourceId = true;
10828            } else {
10829                res.icon = info.icon;
10830            }
10831            res.iconResourceId = info.icon;
10832            res.system = res.activityInfo.applicationInfo.isSystemApp();
10833            return res;
10834        }
10835
10836        @Override
10837        protected void sortResults(List<ResolveInfo> results) {
10838            Collections.sort(results, mResolvePrioritySorter);
10839        }
10840
10841        @Override
10842        protected void dumpFilter(PrintWriter out, String prefix,
10843                PackageParser.ActivityIntentInfo filter) {
10844            out.print(prefix); out.print(
10845                    Integer.toHexString(System.identityHashCode(filter.activity)));
10846                    out.print(' ');
10847                    filter.activity.printComponentShortName(out);
10848                    out.print(" filter ");
10849                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10850        }
10851
10852        @Override
10853        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10854            return filter.activity;
10855        }
10856
10857        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10858            PackageParser.Activity activity = (PackageParser.Activity)label;
10859            out.print(prefix); out.print(
10860                    Integer.toHexString(System.identityHashCode(activity)));
10861                    out.print(' ');
10862                    activity.printComponentShortName(out);
10863            if (count > 1) {
10864                out.print(" ("); out.print(count); out.print(" filters)");
10865            }
10866            out.println();
10867        }
10868
10869        // Keys are String (activity class name), values are Activity.
10870        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10871                = new ArrayMap<ComponentName, PackageParser.Activity>();
10872        private int mFlags;
10873    }
10874
10875    private final class ServiceIntentResolver
10876            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10877        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10878                boolean defaultOnly, int userId) {
10879            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10880            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10881        }
10882
10883        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10884                int userId) {
10885            if (!sUserManager.exists(userId)) return null;
10886            mFlags = flags;
10887            return super.queryIntent(intent, resolvedType,
10888                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10889        }
10890
10891        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10892                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10893            if (!sUserManager.exists(userId)) return null;
10894            if (packageServices == null) {
10895                return null;
10896            }
10897            mFlags = flags;
10898            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10899            final int N = packageServices.size();
10900            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10901                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10902
10903            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10904            for (int i = 0; i < N; ++i) {
10905                intentFilters = packageServices.get(i).intents;
10906                if (intentFilters != null && intentFilters.size() > 0) {
10907                    PackageParser.ServiceIntentInfo[] array =
10908                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10909                    intentFilters.toArray(array);
10910                    listCut.add(array);
10911                }
10912            }
10913            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10914        }
10915
10916        public final void addService(PackageParser.Service s) {
10917            mServices.put(s.getComponentName(), s);
10918            if (DEBUG_SHOW_INFO) {
10919                Log.v(TAG, "  "
10920                        + (s.info.nonLocalizedLabel != null
10921                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10922                Log.v(TAG, "    Class=" + s.info.name);
10923            }
10924            final int NI = s.intents.size();
10925            int j;
10926            for (j=0; j<NI; j++) {
10927                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10928                if (DEBUG_SHOW_INFO) {
10929                    Log.v(TAG, "    IntentFilter:");
10930                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10931                }
10932                if (!intent.debugCheck()) {
10933                    Log.w(TAG, "==> For Service " + s.info.name);
10934                }
10935                addFilter(intent);
10936            }
10937        }
10938
10939        public final void removeService(PackageParser.Service s) {
10940            mServices.remove(s.getComponentName());
10941            if (DEBUG_SHOW_INFO) {
10942                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10943                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10944                Log.v(TAG, "    Class=" + s.info.name);
10945            }
10946            final int NI = s.intents.size();
10947            int j;
10948            for (j=0; j<NI; j++) {
10949                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10950                if (DEBUG_SHOW_INFO) {
10951                    Log.v(TAG, "    IntentFilter:");
10952                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10953                }
10954                removeFilter(intent);
10955            }
10956        }
10957
10958        @Override
10959        protected boolean allowFilterResult(
10960                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10961            ServiceInfo filterSi = filter.service.info;
10962            for (int i=dest.size()-1; i>=0; i--) {
10963                ServiceInfo destAi = dest.get(i).serviceInfo;
10964                if (destAi.name == filterSi.name
10965                        && destAi.packageName == filterSi.packageName) {
10966                    return false;
10967                }
10968            }
10969            return true;
10970        }
10971
10972        @Override
10973        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10974            return new PackageParser.ServiceIntentInfo[size];
10975        }
10976
10977        @Override
10978        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10979            if (!sUserManager.exists(userId)) return true;
10980            PackageParser.Package p = filter.service.owner;
10981            if (p != null) {
10982                PackageSetting ps = (PackageSetting)p.mExtras;
10983                if (ps != null) {
10984                    // System apps are never considered stopped for purposes of
10985                    // filtering, because there may be no way for the user to
10986                    // actually re-launch them.
10987                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10988                            && ps.getStopped(userId);
10989                }
10990            }
10991            return false;
10992        }
10993
10994        @Override
10995        protected boolean isPackageForFilter(String packageName,
10996                PackageParser.ServiceIntentInfo info) {
10997            return packageName.equals(info.service.owner.packageName);
10998        }
10999
11000        @Override
11001        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11002                int match, int userId) {
11003            if (!sUserManager.exists(userId)) return null;
11004            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11005            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11006                return null;
11007            }
11008            final PackageParser.Service service = info.service;
11009            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11010            if (ps == null) {
11011                return null;
11012            }
11013            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11014                    ps.readUserState(userId), userId);
11015            if (si == null) {
11016                return null;
11017            }
11018            final ResolveInfo res = new ResolveInfo();
11019            res.serviceInfo = si;
11020            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11021                res.filter = filter;
11022            }
11023            res.priority = info.getPriority();
11024            res.preferredOrder = service.owner.mPreferredOrder;
11025            res.match = match;
11026            res.isDefault = info.hasDefault;
11027            res.labelRes = info.labelRes;
11028            res.nonLocalizedLabel = info.nonLocalizedLabel;
11029            res.icon = info.icon;
11030            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11031            return res;
11032        }
11033
11034        @Override
11035        protected void sortResults(List<ResolveInfo> results) {
11036            Collections.sort(results, mResolvePrioritySorter);
11037        }
11038
11039        @Override
11040        protected void dumpFilter(PrintWriter out, String prefix,
11041                PackageParser.ServiceIntentInfo filter) {
11042            out.print(prefix); out.print(
11043                    Integer.toHexString(System.identityHashCode(filter.service)));
11044                    out.print(' ');
11045                    filter.service.printComponentShortName(out);
11046                    out.print(" filter ");
11047                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11048        }
11049
11050        @Override
11051        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11052            return filter.service;
11053        }
11054
11055        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11056            PackageParser.Service service = (PackageParser.Service)label;
11057            out.print(prefix); out.print(
11058                    Integer.toHexString(System.identityHashCode(service)));
11059                    out.print(' ');
11060                    service.printComponentShortName(out);
11061            if (count > 1) {
11062                out.print(" ("); out.print(count); out.print(" filters)");
11063            }
11064            out.println();
11065        }
11066
11067//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11068//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11069//            final List<ResolveInfo> retList = Lists.newArrayList();
11070//            while (i.hasNext()) {
11071//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11072//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11073//                    retList.add(resolveInfo);
11074//                }
11075//            }
11076//            return retList;
11077//        }
11078
11079        // Keys are String (activity class name), values are Activity.
11080        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11081                = new ArrayMap<ComponentName, PackageParser.Service>();
11082        private int mFlags;
11083    };
11084
11085    private final class ProviderIntentResolver
11086            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11087        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11088                boolean defaultOnly, int userId) {
11089            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11090            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11091        }
11092
11093        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11094                int userId) {
11095            if (!sUserManager.exists(userId))
11096                return null;
11097            mFlags = flags;
11098            return super.queryIntent(intent, resolvedType,
11099                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11100        }
11101
11102        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11103                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11104            if (!sUserManager.exists(userId))
11105                return null;
11106            if (packageProviders == null) {
11107                return null;
11108            }
11109            mFlags = flags;
11110            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11111            final int N = packageProviders.size();
11112            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11113                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11114
11115            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11116            for (int i = 0; i < N; ++i) {
11117                intentFilters = packageProviders.get(i).intents;
11118                if (intentFilters != null && intentFilters.size() > 0) {
11119                    PackageParser.ProviderIntentInfo[] array =
11120                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11121                    intentFilters.toArray(array);
11122                    listCut.add(array);
11123                }
11124            }
11125            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11126        }
11127
11128        public final void addProvider(PackageParser.Provider p) {
11129            if (mProviders.containsKey(p.getComponentName())) {
11130                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11131                return;
11132            }
11133
11134            mProviders.put(p.getComponentName(), p);
11135            if (DEBUG_SHOW_INFO) {
11136                Log.v(TAG, "  "
11137                        + (p.info.nonLocalizedLabel != null
11138                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11139                Log.v(TAG, "    Class=" + p.info.name);
11140            }
11141            final int NI = p.intents.size();
11142            int j;
11143            for (j = 0; j < NI; j++) {
11144                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11145                if (DEBUG_SHOW_INFO) {
11146                    Log.v(TAG, "    IntentFilter:");
11147                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11148                }
11149                if (!intent.debugCheck()) {
11150                    Log.w(TAG, "==> For Provider " + p.info.name);
11151                }
11152                addFilter(intent);
11153            }
11154        }
11155
11156        public final void removeProvider(PackageParser.Provider p) {
11157            mProviders.remove(p.getComponentName());
11158            if (DEBUG_SHOW_INFO) {
11159                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11160                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11161                Log.v(TAG, "    Class=" + p.info.name);
11162            }
11163            final int NI = p.intents.size();
11164            int j;
11165            for (j = 0; j < NI; j++) {
11166                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11167                if (DEBUG_SHOW_INFO) {
11168                    Log.v(TAG, "    IntentFilter:");
11169                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11170                }
11171                removeFilter(intent);
11172            }
11173        }
11174
11175        @Override
11176        protected boolean allowFilterResult(
11177                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11178            ProviderInfo filterPi = filter.provider.info;
11179            for (int i = dest.size() - 1; i >= 0; i--) {
11180                ProviderInfo destPi = dest.get(i).providerInfo;
11181                if (destPi.name == filterPi.name
11182                        && destPi.packageName == filterPi.packageName) {
11183                    return false;
11184                }
11185            }
11186            return true;
11187        }
11188
11189        @Override
11190        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11191            return new PackageParser.ProviderIntentInfo[size];
11192        }
11193
11194        @Override
11195        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11196            if (!sUserManager.exists(userId))
11197                return true;
11198            PackageParser.Package p = filter.provider.owner;
11199            if (p != null) {
11200                PackageSetting ps = (PackageSetting) p.mExtras;
11201                if (ps != null) {
11202                    // System apps are never considered stopped for purposes of
11203                    // filtering, because there may be no way for the user to
11204                    // actually re-launch them.
11205                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11206                            && ps.getStopped(userId);
11207                }
11208            }
11209            return false;
11210        }
11211
11212        @Override
11213        protected boolean isPackageForFilter(String packageName,
11214                PackageParser.ProviderIntentInfo info) {
11215            return packageName.equals(info.provider.owner.packageName);
11216        }
11217
11218        @Override
11219        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11220                int match, int userId) {
11221            if (!sUserManager.exists(userId))
11222                return null;
11223            final PackageParser.ProviderIntentInfo info = filter;
11224            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11225                return null;
11226            }
11227            final PackageParser.Provider provider = info.provider;
11228            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11229            if (ps == null) {
11230                return null;
11231            }
11232            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11233                    ps.readUserState(userId), userId);
11234            if (pi == null) {
11235                return null;
11236            }
11237            final ResolveInfo res = new ResolveInfo();
11238            res.providerInfo = pi;
11239            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11240                res.filter = filter;
11241            }
11242            res.priority = info.getPriority();
11243            res.preferredOrder = provider.owner.mPreferredOrder;
11244            res.match = match;
11245            res.isDefault = info.hasDefault;
11246            res.labelRes = info.labelRes;
11247            res.nonLocalizedLabel = info.nonLocalizedLabel;
11248            res.icon = info.icon;
11249            res.system = res.providerInfo.applicationInfo.isSystemApp();
11250            return res;
11251        }
11252
11253        @Override
11254        protected void sortResults(List<ResolveInfo> results) {
11255            Collections.sort(results, mResolvePrioritySorter);
11256        }
11257
11258        @Override
11259        protected void dumpFilter(PrintWriter out, String prefix,
11260                PackageParser.ProviderIntentInfo filter) {
11261            out.print(prefix);
11262            out.print(
11263                    Integer.toHexString(System.identityHashCode(filter.provider)));
11264            out.print(' ');
11265            filter.provider.printComponentShortName(out);
11266            out.print(" filter ");
11267            out.println(Integer.toHexString(System.identityHashCode(filter)));
11268        }
11269
11270        @Override
11271        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11272            return filter.provider;
11273        }
11274
11275        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11276            PackageParser.Provider provider = (PackageParser.Provider)label;
11277            out.print(prefix); out.print(
11278                    Integer.toHexString(System.identityHashCode(provider)));
11279                    out.print(' ');
11280                    provider.printComponentShortName(out);
11281            if (count > 1) {
11282                out.print(" ("); out.print(count); out.print(" filters)");
11283            }
11284            out.println();
11285        }
11286
11287        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11288                = new ArrayMap<ComponentName, PackageParser.Provider>();
11289        private int mFlags;
11290    }
11291
11292    private static final class EphemeralIntentResolver
11293            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11294        @Override
11295        protected EphemeralResolveIntentInfo[] newArray(int size) {
11296            return new EphemeralResolveIntentInfo[size];
11297        }
11298
11299        @Override
11300        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11301            return true;
11302        }
11303
11304        @Override
11305        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11306                int userId) {
11307            if (!sUserManager.exists(userId)) {
11308                return null;
11309            }
11310            return info.getEphemeralResolveInfo();
11311        }
11312    }
11313
11314    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11315            new Comparator<ResolveInfo>() {
11316        public int compare(ResolveInfo r1, ResolveInfo r2) {
11317            int v1 = r1.priority;
11318            int v2 = r2.priority;
11319            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11320            if (v1 != v2) {
11321                return (v1 > v2) ? -1 : 1;
11322            }
11323            v1 = r1.preferredOrder;
11324            v2 = r2.preferredOrder;
11325            if (v1 != v2) {
11326                return (v1 > v2) ? -1 : 1;
11327            }
11328            if (r1.isDefault != r2.isDefault) {
11329                return r1.isDefault ? -1 : 1;
11330            }
11331            v1 = r1.match;
11332            v2 = r2.match;
11333            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11334            if (v1 != v2) {
11335                return (v1 > v2) ? -1 : 1;
11336            }
11337            if (r1.system != r2.system) {
11338                return r1.system ? -1 : 1;
11339            }
11340            if (r1.activityInfo != null) {
11341                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11342            }
11343            if (r1.serviceInfo != null) {
11344                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11345            }
11346            if (r1.providerInfo != null) {
11347                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11348            }
11349            return 0;
11350        }
11351    };
11352
11353    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11354            new Comparator<ProviderInfo>() {
11355        public int compare(ProviderInfo p1, ProviderInfo p2) {
11356            final int v1 = p1.initOrder;
11357            final int v2 = p2.initOrder;
11358            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11359        }
11360    };
11361
11362    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11363            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11364            final int[] userIds) {
11365        mHandler.post(new Runnable() {
11366            @Override
11367            public void run() {
11368                try {
11369                    final IActivityManager am = ActivityManagerNative.getDefault();
11370                    if (am == null) return;
11371                    final int[] resolvedUserIds;
11372                    if (userIds == null) {
11373                        resolvedUserIds = am.getRunningUserIds();
11374                    } else {
11375                        resolvedUserIds = userIds;
11376                    }
11377                    for (int id : resolvedUserIds) {
11378                        final Intent intent = new Intent(action,
11379                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11380                        if (extras != null) {
11381                            intent.putExtras(extras);
11382                        }
11383                        if (targetPkg != null) {
11384                            intent.setPackage(targetPkg);
11385                        }
11386                        // Modify the UID when posting to other users
11387                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11388                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11389                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11390                            intent.putExtra(Intent.EXTRA_UID, uid);
11391                        }
11392                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11393                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11394                        if (DEBUG_BROADCASTS) {
11395                            RuntimeException here = new RuntimeException("here");
11396                            here.fillInStackTrace();
11397                            Slog.d(TAG, "Sending to user " + id + ": "
11398                                    + intent.toShortString(false, true, false, false)
11399                                    + " " + intent.getExtras(), here);
11400                        }
11401                        am.broadcastIntent(null, intent, null, finishedReceiver,
11402                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11403                                null, finishedReceiver != null, false, id);
11404                    }
11405                } catch (RemoteException ex) {
11406                }
11407            }
11408        });
11409    }
11410
11411    /**
11412     * Check if the external storage media is available. This is true if there
11413     * is a mounted external storage medium or if the external storage is
11414     * emulated.
11415     */
11416    private boolean isExternalMediaAvailable() {
11417        return mMediaMounted || Environment.isExternalStorageEmulated();
11418    }
11419
11420    @Override
11421    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11422        // writer
11423        synchronized (mPackages) {
11424            if (!isExternalMediaAvailable()) {
11425                // If the external storage is no longer mounted at this point,
11426                // the caller may not have been able to delete all of this
11427                // packages files and can not delete any more.  Bail.
11428                return null;
11429            }
11430            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11431            if (lastPackage != null) {
11432                pkgs.remove(lastPackage);
11433            }
11434            if (pkgs.size() > 0) {
11435                return pkgs.get(0);
11436            }
11437        }
11438        return null;
11439    }
11440
11441    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11442        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11443                userId, andCode ? 1 : 0, packageName);
11444        if (mSystemReady) {
11445            msg.sendToTarget();
11446        } else {
11447            if (mPostSystemReadyMessages == null) {
11448                mPostSystemReadyMessages = new ArrayList<>();
11449            }
11450            mPostSystemReadyMessages.add(msg);
11451        }
11452    }
11453
11454    void startCleaningPackages() {
11455        // reader
11456        if (!isExternalMediaAvailable()) {
11457            return;
11458        }
11459        synchronized (mPackages) {
11460            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11461                return;
11462            }
11463        }
11464        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11465        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11466        IActivityManager am = ActivityManagerNative.getDefault();
11467        if (am != null) {
11468            try {
11469                am.startService(null, intent, null, mContext.getOpPackageName(),
11470                        UserHandle.USER_SYSTEM);
11471            } catch (RemoteException e) {
11472            }
11473        }
11474    }
11475
11476    @Override
11477    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11478            int installFlags, String installerPackageName, int userId) {
11479        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11480
11481        final int callingUid = Binder.getCallingUid();
11482        enforceCrossUserPermission(callingUid, userId,
11483                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11484
11485        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11486            try {
11487                if (observer != null) {
11488                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11489                }
11490            } catch (RemoteException re) {
11491            }
11492            return;
11493        }
11494
11495        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11496            installFlags |= PackageManager.INSTALL_FROM_ADB;
11497
11498        } else {
11499            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11500            // about installerPackageName.
11501
11502            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11503            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11504        }
11505
11506        UserHandle user;
11507        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11508            user = UserHandle.ALL;
11509        } else {
11510            user = new UserHandle(userId);
11511        }
11512
11513        // Only system components can circumvent runtime permissions when installing.
11514        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11515                && mContext.checkCallingOrSelfPermission(Manifest.permission
11516                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11517            throw new SecurityException("You need the "
11518                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11519                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11520        }
11521
11522        final File originFile = new File(originPath);
11523        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11524
11525        final Message msg = mHandler.obtainMessage(INIT_COPY);
11526        final VerificationInfo verificationInfo = new VerificationInfo(
11527                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11528        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11529                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11530                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11531                null /*certificates*/);
11532        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11533        msg.obj = params;
11534
11535        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11536                System.identityHashCode(msg.obj));
11537        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11538                System.identityHashCode(msg.obj));
11539
11540        mHandler.sendMessage(msg);
11541    }
11542
11543    void installStage(String packageName, File stagedDir, String stagedCid,
11544            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11545            String installerPackageName, int installerUid, UserHandle user,
11546            Certificate[][] certificates) {
11547        if (DEBUG_EPHEMERAL) {
11548            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11549                Slog.d(TAG, "Ephemeral install of " + packageName);
11550            }
11551        }
11552        final VerificationInfo verificationInfo = new VerificationInfo(
11553                sessionParams.originatingUri, sessionParams.referrerUri,
11554                sessionParams.originatingUid, installerUid);
11555
11556        final OriginInfo origin;
11557        if (stagedDir != null) {
11558            origin = OriginInfo.fromStagedFile(stagedDir);
11559        } else {
11560            origin = OriginInfo.fromStagedContainer(stagedCid);
11561        }
11562
11563        final Message msg = mHandler.obtainMessage(INIT_COPY);
11564        final InstallParams params = new InstallParams(origin, null, observer,
11565                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11566                verificationInfo, user, sessionParams.abiOverride,
11567                sessionParams.grantedRuntimePermissions, certificates);
11568        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11569        msg.obj = params;
11570
11571        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11572                System.identityHashCode(msg.obj));
11573        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11574                System.identityHashCode(msg.obj));
11575
11576        mHandler.sendMessage(msg);
11577    }
11578
11579    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11580            int userId) {
11581        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11582        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11583    }
11584
11585    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11586            int appId, int userId) {
11587        Bundle extras = new Bundle(1);
11588        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11589
11590        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11591                packageName, extras, 0, null, null, new int[] {userId});
11592        try {
11593            IActivityManager am = ActivityManagerNative.getDefault();
11594            if (isSystem && am.isUserRunning(userId, 0)) {
11595                // The just-installed/enabled app is bundled on the system, so presumed
11596                // to be able to run automatically without needing an explicit launch.
11597                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11598                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11599                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11600                        .setPackage(packageName);
11601                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11602                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11603            }
11604        } catch (RemoteException e) {
11605            // shouldn't happen
11606            Slog.w(TAG, "Unable to bootstrap installed package", e);
11607        }
11608    }
11609
11610    @Override
11611    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11612            int userId) {
11613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11614        PackageSetting pkgSetting;
11615        final int uid = Binder.getCallingUid();
11616        enforceCrossUserPermission(uid, userId,
11617                true /* requireFullPermission */, true /* checkShell */,
11618                "setApplicationHiddenSetting for user " + userId);
11619
11620        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11621            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11622            return false;
11623        }
11624
11625        long callingId = Binder.clearCallingIdentity();
11626        try {
11627            boolean sendAdded = false;
11628            boolean sendRemoved = false;
11629            // writer
11630            synchronized (mPackages) {
11631                pkgSetting = mSettings.mPackages.get(packageName);
11632                if (pkgSetting == null) {
11633                    return false;
11634                }
11635                if (pkgSetting.getHidden(userId) != hidden) {
11636                    pkgSetting.setHidden(hidden, userId);
11637                    mSettings.writePackageRestrictionsLPr(userId);
11638                    if (hidden) {
11639                        sendRemoved = true;
11640                    } else {
11641                        sendAdded = true;
11642                    }
11643                }
11644            }
11645            if (sendAdded) {
11646                sendPackageAddedForUser(packageName, pkgSetting, userId);
11647                return true;
11648            }
11649            if (sendRemoved) {
11650                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11651                        "hiding pkg");
11652                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11653                return true;
11654            }
11655        } finally {
11656            Binder.restoreCallingIdentity(callingId);
11657        }
11658        return false;
11659    }
11660
11661    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11662            int userId) {
11663        final PackageRemovedInfo info = new PackageRemovedInfo();
11664        info.removedPackage = packageName;
11665        info.removedUsers = new int[] {userId};
11666        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11667        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11668    }
11669
11670    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11671        if (pkgList.length > 0) {
11672            Bundle extras = new Bundle(1);
11673            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11674
11675            sendPackageBroadcast(
11676                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11677                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11678                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11679                    new int[] {userId});
11680        }
11681    }
11682
11683    /**
11684     * Returns true if application is not found or there was an error. Otherwise it returns
11685     * the hidden state of the package for the given user.
11686     */
11687    @Override
11688    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11689        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11690        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11691                true /* requireFullPermission */, false /* checkShell */,
11692                "getApplicationHidden for user " + userId);
11693        PackageSetting pkgSetting;
11694        long callingId = Binder.clearCallingIdentity();
11695        try {
11696            // writer
11697            synchronized (mPackages) {
11698                pkgSetting = mSettings.mPackages.get(packageName);
11699                if (pkgSetting == null) {
11700                    return true;
11701                }
11702                return pkgSetting.getHidden(userId);
11703            }
11704        } finally {
11705            Binder.restoreCallingIdentity(callingId);
11706        }
11707    }
11708
11709    /**
11710     * @hide
11711     */
11712    @Override
11713    public int installExistingPackageAsUser(String packageName, int userId) {
11714        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11715                null);
11716        PackageSetting pkgSetting;
11717        final int uid = Binder.getCallingUid();
11718        enforceCrossUserPermission(uid, userId,
11719                true /* requireFullPermission */, true /* checkShell */,
11720                "installExistingPackage for user " + userId);
11721        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11722            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11723        }
11724
11725        long callingId = Binder.clearCallingIdentity();
11726        try {
11727            boolean installed = false;
11728
11729            // writer
11730            synchronized (mPackages) {
11731                pkgSetting = mSettings.mPackages.get(packageName);
11732                if (pkgSetting == null) {
11733                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11734                }
11735                if (!pkgSetting.getInstalled(userId)) {
11736                    pkgSetting.setInstalled(true, userId);
11737                    pkgSetting.setHidden(false, userId);
11738                    mSettings.writePackageRestrictionsLPr(userId);
11739                    installed = true;
11740                }
11741            }
11742
11743            if (installed) {
11744                if (pkgSetting.pkg != null) {
11745                    synchronized (mInstallLock) {
11746                        // We don't need to freeze for a brand new install
11747                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11748                    }
11749                }
11750                sendPackageAddedForUser(packageName, pkgSetting, userId);
11751            }
11752        } finally {
11753            Binder.restoreCallingIdentity(callingId);
11754        }
11755
11756        return PackageManager.INSTALL_SUCCEEDED;
11757    }
11758
11759    boolean isUserRestricted(int userId, String restrictionKey) {
11760        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11761        if (restrictions.getBoolean(restrictionKey, false)) {
11762            Log.w(TAG, "User is restricted: " + restrictionKey);
11763            return true;
11764        }
11765        return false;
11766    }
11767
11768    @Override
11769    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11770            int userId) {
11771        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11773                true /* requireFullPermission */, true /* checkShell */,
11774                "setPackagesSuspended for user " + userId);
11775
11776        if (ArrayUtils.isEmpty(packageNames)) {
11777            return packageNames;
11778        }
11779
11780        // List of package names for whom the suspended state has changed.
11781        List<String> changedPackages = new ArrayList<>(packageNames.length);
11782        // List of package names for whom the suspended state is not set as requested in this
11783        // method.
11784        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11785        long callingId = Binder.clearCallingIdentity();
11786        try {
11787            for (int i = 0; i < packageNames.length; i++) {
11788                String packageName = packageNames[i];
11789                boolean changed = false;
11790                final int appId;
11791                synchronized (mPackages) {
11792                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11793                    if (pkgSetting == null) {
11794                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11795                                + "\". Skipping suspending/un-suspending.");
11796                        unactionedPackages.add(packageName);
11797                        continue;
11798                    }
11799                    appId = pkgSetting.appId;
11800                    if (pkgSetting.getSuspended(userId) != suspended) {
11801                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11802                            unactionedPackages.add(packageName);
11803                            continue;
11804                        }
11805                        pkgSetting.setSuspended(suspended, userId);
11806                        mSettings.writePackageRestrictionsLPr(userId);
11807                        changed = true;
11808                        changedPackages.add(packageName);
11809                    }
11810                }
11811
11812                if (changed && suspended) {
11813                    killApplication(packageName, UserHandle.getUid(userId, appId),
11814                            "suspending package");
11815                }
11816            }
11817        } finally {
11818            Binder.restoreCallingIdentity(callingId);
11819        }
11820
11821        if (!changedPackages.isEmpty()) {
11822            sendPackagesSuspendedForUser(changedPackages.toArray(
11823                    new String[changedPackages.size()]), userId, suspended);
11824        }
11825
11826        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11827    }
11828
11829    @Override
11830    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11831        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11832                true /* requireFullPermission */, false /* checkShell */,
11833                "isPackageSuspendedForUser for user " + userId);
11834        synchronized (mPackages) {
11835            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11836            if (pkgSetting == null) {
11837                throw new IllegalArgumentException("Unknown target package: " + packageName);
11838            }
11839            return pkgSetting.getSuspended(userId);
11840        }
11841    }
11842
11843    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11844        if (isPackageDeviceAdmin(packageName, userId)) {
11845            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11846                    + "\": has an active device admin");
11847            return false;
11848        }
11849
11850        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11851        if (packageName.equals(activeLauncherPackageName)) {
11852            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11853                    + "\": contains the active launcher");
11854            return false;
11855        }
11856
11857        if (packageName.equals(mRequiredInstallerPackage)) {
11858            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11859                    + "\": required for package installation");
11860            return false;
11861        }
11862
11863        if (packageName.equals(mRequiredVerifierPackage)) {
11864            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11865                    + "\": required for package verification");
11866            return false;
11867        }
11868
11869        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11870            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11871                    + "\": is the default dialer");
11872            return false;
11873        }
11874
11875        return true;
11876    }
11877
11878    private String getActiveLauncherPackageName(int userId) {
11879        Intent intent = new Intent(Intent.ACTION_MAIN);
11880        intent.addCategory(Intent.CATEGORY_HOME);
11881        ResolveInfo resolveInfo = resolveIntent(
11882                intent,
11883                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11884                PackageManager.MATCH_DEFAULT_ONLY,
11885                userId);
11886
11887        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11888    }
11889
11890    private String getDefaultDialerPackageName(int userId) {
11891        synchronized (mPackages) {
11892            return mSettings.getDefaultDialerPackageNameLPw(userId);
11893        }
11894    }
11895
11896    @Override
11897    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11898        mContext.enforceCallingOrSelfPermission(
11899                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11900                "Only package verification agents can verify applications");
11901
11902        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11903        final PackageVerificationResponse response = new PackageVerificationResponse(
11904                verificationCode, Binder.getCallingUid());
11905        msg.arg1 = id;
11906        msg.obj = response;
11907        mHandler.sendMessage(msg);
11908    }
11909
11910    @Override
11911    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11912            long millisecondsToDelay) {
11913        mContext.enforceCallingOrSelfPermission(
11914                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11915                "Only package verification agents can extend verification timeouts");
11916
11917        final PackageVerificationState state = mPendingVerification.get(id);
11918        final PackageVerificationResponse response = new PackageVerificationResponse(
11919                verificationCodeAtTimeout, Binder.getCallingUid());
11920
11921        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11922            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11923        }
11924        if (millisecondsToDelay < 0) {
11925            millisecondsToDelay = 0;
11926        }
11927        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11928                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11929            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11930        }
11931
11932        if ((state != null) && !state.timeoutExtended()) {
11933            state.extendTimeout();
11934
11935            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11936            msg.arg1 = id;
11937            msg.obj = response;
11938            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11939        }
11940    }
11941
11942    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11943            int verificationCode, UserHandle user) {
11944        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11945        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11946        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11947        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11948        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11949
11950        mContext.sendBroadcastAsUser(intent, user,
11951                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11952    }
11953
11954    private ComponentName matchComponentForVerifier(String packageName,
11955            List<ResolveInfo> receivers) {
11956        ActivityInfo targetReceiver = null;
11957
11958        final int NR = receivers.size();
11959        for (int i = 0; i < NR; i++) {
11960            final ResolveInfo info = receivers.get(i);
11961            if (info.activityInfo == null) {
11962                continue;
11963            }
11964
11965            if (packageName.equals(info.activityInfo.packageName)) {
11966                targetReceiver = info.activityInfo;
11967                break;
11968            }
11969        }
11970
11971        if (targetReceiver == null) {
11972            return null;
11973        }
11974
11975        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11976    }
11977
11978    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11979            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11980        if (pkgInfo.verifiers.length == 0) {
11981            return null;
11982        }
11983
11984        final int N = pkgInfo.verifiers.length;
11985        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11986        for (int i = 0; i < N; i++) {
11987            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11988
11989            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11990                    receivers);
11991            if (comp == null) {
11992                continue;
11993            }
11994
11995            final int verifierUid = getUidForVerifier(verifierInfo);
11996            if (verifierUid == -1) {
11997                continue;
11998            }
11999
12000            if (DEBUG_VERIFY) {
12001                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12002                        + " with the correct signature");
12003            }
12004            sufficientVerifiers.add(comp);
12005            verificationState.addSufficientVerifier(verifierUid);
12006        }
12007
12008        return sufficientVerifiers;
12009    }
12010
12011    private int getUidForVerifier(VerifierInfo verifierInfo) {
12012        synchronized (mPackages) {
12013            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12014            if (pkg == null) {
12015                return -1;
12016            } else if (pkg.mSignatures.length != 1) {
12017                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12018                        + " has more than one signature; ignoring");
12019                return -1;
12020            }
12021
12022            /*
12023             * If the public key of the package's signature does not match
12024             * our expected public key, then this is a different package and
12025             * we should skip.
12026             */
12027
12028            final byte[] expectedPublicKey;
12029            try {
12030                final Signature verifierSig = pkg.mSignatures[0];
12031                final PublicKey publicKey = verifierSig.getPublicKey();
12032                expectedPublicKey = publicKey.getEncoded();
12033            } catch (CertificateException e) {
12034                return -1;
12035            }
12036
12037            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12038
12039            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12040                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12041                        + " does not have the expected public key; ignoring");
12042                return -1;
12043            }
12044
12045            return pkg.applicationInfo.uid;
12046        }
12047    }
12048
12049    @Override
12050    public void finishPackageInstall(int token, boolean didLaunch) {
12051        enforceSystemOrRoot("Only the system is allowed to finish installs");
12052
12053        if (DEBUG_INSTALL) {
12054            Slog.v(TAG, "BM finishing package install for " + token);
12055        }
12056        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12057
12058        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12059        mHandler.sendMessage(msg);
12060    }
12061
12062    /**
12063     * Get the verification agent timeout.
12064     *
12065     * @return verification timeout in milliseconds
12066     */
12067    private long getVerificationTimeout() {
12068        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12069                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12070                DEFAULT_VERIFICATION_TIMEOUT);
12071    }
12072
12073    /**
12074     * Get the default verification agent response code.
12075     *
12076     * @return default verification response code
12077     */
12078    private int getDefaultVerificationResponse() {
12079        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12080                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12081                DEFAULT_VERIFICATION_RESPONSE);
12082    }
12083
12084    /**
12085     * Check whether or not package verification has been enabled.
12086     *
12087     * @return true if verification should be performed
12088     */
12089    private boolean isVerificationEnabled(int userId, int installFlags) {
12090        if (!DEFAULT_VERIFY_ENABLE) {
12091            return false;
12092        }
12093        // Ephemeral apps don't get the full verification treatment
12094        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12095            if (DEBUG_EPHEMERAL) {
12096                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12097            }
12098            return false;
12099        }
12100
12101        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12102
12103        // Check if installing from ADB
12104        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12105            // Do not run verification in a test harness environment
12106            if (ActivityManager.isRunningInTestHarness()) {
12107                return false;
12108            }
12109            if (ensureVerifyAppsEnabled) {
12110                return true;
12111            }
12112            // Check if the developer does not want package verification for ADB installs
12113            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12114                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12115                return false;
12116            }
12117        }
12118
12119        if (ensureVerifyAppsEnabled) {
12120            return true;
12121        }
12122
12123        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12124                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12125    }
12126
12127    @Override
12128    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12129            throws RemoteException {
12130        mContext.enforceCallingOrSelfPermission(
12131                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12132                "Only intentfilter verification agents can verify applications");
12133
12134        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12135        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12136                Binder.getCallingUid(), verificationCode, failedDomains);
12137        msg.arg1 = id;
12138        msg.obj = response;
12139        mHandler.sendMessage(msg);
12140    }
12141
12142    @Override
12143    public int getIntentVerificationStatus(String packageName, int userId) {
12144        synchronized (mPackages) {
12145            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12146        }
12147    }
12148
12149    @Override
12150    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12151        mContext.enforceCallingOrSelfPermission(
12152                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12153
12154        boolean result = false;
12155        synchronized (mPackages) {
12156            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12157        }
12158        if (result) {
12159            scheduleWritePackageRestrictionsLocked(userId);
12160        }
12161        return result;
12162    }
12163
12164    @Override
12165    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12166            String packageName) {
12167        synchronized (mPackages) {
12168            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12169        }
12170    }
12171
12172    @Override
12173    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12174        if (TextUtils.isEmpty(packageName)) {
12175            return ParceledListSlice.emptyList();
12176        }
12177        synchronized (mPackages) {
12178            PackageParser.Package pkg = mPackages.get(packageName);
12179            if (pkg == null || pkg.activities == null) {
12180                return ParceledListSlice.emptyList();
12181            }
12182            final int count = pkg.activities.size();
12183            ArrayList<IntentFilter> result = new ArrayList<>();
12184            for (int n=0; n<count; n++) {
12185                PackageParser.Activity activity = pkg.activities.get(n);
12186                if (activity.intents != null && activity.intents.size() > 0) {
12187                    result.addAll(activity.intents);
12188                }
12189            }
12190            return new ParceledListSlice<>(result);
12191        }
12192    }
12193
12194    @Override
12195    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12196        mContext.enforceCallingOrSelfPermission(
12197                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12198
12199        synchronized (mPackages) {
12200            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12201            if (packageName != null) {
12202                result |= updateIntentVerificationStatus(packageName,
12203                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12204                        userId);
12205                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12206                        packageName, userId);
12207            }
12208            return result;
12209        }
12210    }
12211
12212    @Override
12213    public String getDefaultBrowserPackageName(int userId) {
12214        synchronized (mPackages) {
12215            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12216        }
12217    }
12218
12219    /**
12220     * Get the "allow unknown sources" setting.
12221     *
12222     * @return the current "allow unknown sources" setting
12223     */
12224    private int getUnknownSourcesSettings() {
12225        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12226                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12227                -1);
12228    }
12229
12230    @Override
12231    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12232        final int uid = Binder.getCallingUid();
12233        // writer
12234        synchronized (mPackages) {
12235            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12236            if (targetPackageSetting == null) {
12237                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12238            }
12239
12240            PackageSetting installerPackageSetting;
12241            if (installerPackageName != null) {
12242                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12243                if (installerPackageSetting == null) {
12244                    throw new IllegalArgumentException("Unknown installer package: "
12245                            + installerPackageName);
12246                }
12247            } else {
12248                installerPackageSetting = null;
12249            }
12250
12251            Signature[] callerSignature;
12252            Object obj = mSettings.getUserIdLPr(uid);
12253            if (obj != null) {
12254                if (obj instanceof SharedUserSetting) {
12255                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12256                } else if (obj instanceof PackageSetting) {
12257                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12258                } else {
12259                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12260                }
12261            } else {
12262                throw new SecurityException("Unknown calling UID: " + uid);
12263            }
12264
12265            // Verify: can't set installerPackageName to a package that is
12266            // not signed with the same cert as the caller.
12267            if (installerPackageSetting != null) {
12268                if (compareSignatures(callerSignature,
12269                        installerPackageSetting.signatures.mSignatures)
12270                        != PackageManager.SIGNATURE_MATCH) {
12271                    throw new SecurityException(
12272                            "Caller does not have same cert as new installer package "
12273                            + installerPackageName);
12274                }
12275            }
12276
12277            // Verify: if target already has an installer package, it must
12278            // be signed with the same cert as the caller.
12279            if (targetPackageSetting.installerPackageName != null) {
12280                PackageSetting setting = mSettings.mPackages.get(
12281                        targetPackageSetting.installerPackageName);
12282                // If the currently set package isn't valid, then it's always
12283                // okay to change it.
12284                if (setting != null) {
12285                    if (compareSignatures(callerSignature,
12286                            setting.signatures.mSignatures)
12287                            != PackageManager.SIGNATURE_MATCH) {
12288                        throw new SecurityException(
12289                                "Caller does not have same cert as old installer package "
12290                                + targetPackageSetting.installerPackageName);
12291                    }
12292                }
12293            }
12294
12295            // Okay!
12296            targetPackageSetting.installerPackageName = installerPackageName;
12297            if (installerPackageName != null) {
12298                mSettings.mInstallerPackages.add(installerPackageName);
12299            }
12300            scheduleWriteSettingsLocked();
12301        }
12302    }
12303
12304    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12305        // Queue up an async operation since the package installation may take a little while.
12306        mHandler.post(new Runnable() {
12307            public void run() {
12308                mHandler.removeCallbacks(this);
12309                 // Result object to be returned
12310                PackageInstalledInfo res = new PackageInstalledInfo();
12311                res.setReturnCode(currentStatus);
12312                res.uid = -1;
12313                res.pkg = null;
12314                res.removedInfo = null;
12315                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12316                    args.doPreInstall(res.returnCode);
12317                    synchronized (mInstallLock) {
12318                        installPackageTracedLI(args, res);
12319                    }
12320                    args.doPostInstall(res.returnCode, res.uid);
12321                }
12322
12323                // A restore should be performed at this point if (a) the install
12324                // succeeded, (b) the operation is not an update, and (c) the new
12325                // package has not opted out of backup participation.
12326                final boolean update = res.removedInfo != null
12327                        && res.removedInfo.removedPackage != null;
12328                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12329                boolean doRestore = !update
12330                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12331
12332                // Set up the post-install work request bookkeeping.  This will be used
12333                // and cleaned up by the post-install event handling regardless of whether
12334                // there's a restore pass performed.  Token values are >= 1.
12335                int token;
12336                if (mNextInstallToken < 0) mNextInstallToken = 1;
12337                token = mNextInstallToken++;
12338
12339                PostInstallData data = new PostInstallData(args, res);
12340                mRunningInstalls.put(token, data);
12341                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12342
12343                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12344                    // Pass responsibility to the Backup Manager.  It will perform a
12345                    // restore if appropriate, then pass responsibility back to the
12346                    // Package Manager to run the post-install observer callbacks
12347                    // and broadcasts.
12348                    IBackupManager bm = IBackupManager.Stub.asInterface(
12349                            ServiceManager.getService(Context.BACKUP_SERVICE));
12350                    if (bm != null) {
12351                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12352                                + " to BM for possible restore");
12353                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12354                        try {
12355                            // TODO: http://b/22388012
12356                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12357                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12358                            } else {
12359                                doRestore = false;
12360                            }
12361                        } catch (RemoteException e) {
12362                            // can't happen; the backup manager is local
12363                        } catch (Exception e) {
12364                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12365                            doRestore = false;
12366                        }
12367                    } else {
12368                        Slog.e(TAG, "Backup Manager not found!");
12369                        doRestore = false;
12370                    }
12371                }
12372
12373                if (!doRestore) {
12374                    // No restore possible, or the Backup Manager was mysteriously not
12375                    // available -- just fire the post-install work request directly.
12376                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12377
12378                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12379
12380                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12381                    mHandler.sendMessage(msg);
12382                }
12383            }
12384        });
12385    }
12386
12387    /**
12388     * Callback from PackageSettings whenever an app is first transitioned out of the
12389     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12390     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12391     * here whether the app is the target of an ongoing install, and only send the
12392     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12393     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12394     * handling.
12395     */
12396    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12397        // Serialize this with the rest of the install-process message chain.  In the
12398        // restore-at-install case, this Runnable will necessarily run before the
12399        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12400        // are coherent.  In the non-restore case, the app has already completed install
12401        // and been launched through some other means, so it is not in a problematic
12402        // state for observers to see the FIRST_LAUNCH signal.
12403        mHandler.post(new Runnable() {
12404            @Override
12405            public void run() {
12406                for (int i = 0; i < mRunningInstalls.size(); i++) {
12407                    final PostInstallData data = mRunningInstalls.valueAt(i);
12408                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12409                        // right package; but is it for the right user?
12410                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12411                            if (userId == data.res.newUsers[uIndex]) {
12412                                if (DEBUG_BACKUP) {
12413                                    Slog.i(TAG, "Package " + pkgName
12414                                            + " being restored so deferring FIRST_LAUNCH");
12415                                }
12416                                return;
12417                            }
12418                        }
12419                    }
12420                }
12421                // didn't find it, so not being restored
12422                if (DEBUG_BACKUP) {
12423                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12424                }
12425                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12426            }
12427        });
12428    }
12429
12430    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12431        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12432                installerPkg, null, userIds);
12433    }
12434
12435    private abstract class HandlerParams {
12436        private static final int MAX_RETRIES = 4;
12437
12438        /**
12439         * Number of times startCopy() has been attempted and had a non-fatal
12440         * error.
12441         */
12442        private int mRetries = 0;
12443
12444        /** User handle for the user requesting the information or installation. */
12445        private final UserHandle mUser;
12446        String traceMethod;
12447        int traceCookie;
12448
12449        HandlerParams(UserHandle user) {
12450            mUser = user;
12451        }
12452
12453        UserHandle getUser() {
12454            return mUser;
12455        }
12456
12457        HandlerParams setTraceMethod(String traceMethod) {
12458            this.traceMethod = traceMethod;
12459            return this;
12460        }
12461
12462        HandlerParams setTraceCookie(int traceCookie) {
12463            this.traceCookie = traceCookie;
12464            return this;
12465        }
12466
12467        final boolean startCopy() {
12468            boolean res;
12469            try {
12470                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12471
12472                if (++mRetries > MAX_RETRIES) {
12473                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12474                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12475                    handleServiceError();
12476                    return false;
12477                } else {
12478                    handleStartCopy();
12479                    res = true;
12480                }
12481            } catch (RemoteException e) {
12482                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12483                mHandler.sendEmptyMessage(MCS_RECONNECT);
12484                res = false;
12485            }
12486            handleReturnCode();
12487            return res;
12488        }
12489
12490        final void serviceError() {
12491            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12492            handleServiceError();
12493            handleReturnCode();
12494        }
12495
12496        abstract void handleStartCopy() throws RemoteException;
12497        abstract void handleServiceError();
12498        abstract void handleReturnCode();
12499    }
12500
12501    class MeasureParams extends HandlerParams {
12502        private final PackageStats mStats;
12503        private boolean mSuccess;
12504
12505        private final IPackageStatsObserver mObserver;
12506
12507        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12508            super(new UserHandle(stats.userHandle));
12509            mObserver = observer;
12510            mStats = stats;
12511        }
12512
12513        @Override
12514        public String toString() {
12515            return "MeasureParams{"
12516                + Integer.toHexString(System.identityHashCode(this))
12517                + " " + mStats.packageName + "}";
12518        }
12519
12520        @Override
12521        void handleStartCopy() throws RemoteException {
12522            synchronized (mInstallLock) {
12523                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12524            }
12525
12526            if (mSuccess) {
12527                final boolean mounted;
12528                if (Environment.isExternalStorageEmulated()) {
12529                    mounted = true;
12530                } else {
12531                    final String status = Environment.getExternalStorageState();
12532                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12533                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12534                }
12535
12536                if (mounted) {
12537                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12538
12539                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12540                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12541
12542                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12543                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12544
12545                    // Always subtract cache size, since it's a subdirectory
12546                    mStats.externalDataSize -= mStats.externalCacheSize;
12547
12548                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12549                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12550
12551                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12552                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12553                }
12554            }
12555        }
12556
12557        @Override
12558        void handleReturnCode() {
12559            if (mObserver != null) {
12560                try {
12561                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12562                } catch (RemoteException e) {
12563                    Slog.i(TAG, "Observer no longer exists.");
12564                }
12565            }
12566        }
12567
12568        @Override
12569        void handleServiceError() {
12570            Slog.e(TAG, "Could not measure application " + mStats.packageName
12571                            + " external storage");
12572        }
12573    }
12574
12575    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12576            throws RemoteException {
12577        long result = 0;
12578        for (File path : paths) {
12579            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12580        }
12581        return result;
12582    }
12583
12584    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12585        for (File path : paths) {
12586            try {
12587                mcs.clearDirectory(path.getAbsolutePath());
12588            } catch (RemoteException e) {
12589            }
12590        }
12591    }
12592
12593    static class OriginInfo {
12594        /**
12595         * Location where install is coming from, before it has been
12596         * copied/renamed into place. This could be a single monolithic APK
12597         * file, or a cluster directory. This location may be untrusted.
12598         */
12599        final File file;
12600        final String cid;
12601
12602        /**
12603         * Flag indicating that {@link #file} or {@link #cid} has already been
12604         * staged, meaning downstream users don't need to defensively copy the
12605         * contents.
12606         */
12607        final boolean staged;
12608
12609        /**
12610         * Flag indicating that {@link #file} or {@link #cid} is an already
12611         * installed app that is being moved.
12612         */
12613        final boolean existing;
12614
12615        final String resolvedPath;
12616        final File resolvedFile;
12617
12618        static OriginInfo fromNothing() {
12619            return new OriginInfo(null, null, false, false);
12620        }
12621
12622        static OriginInfo fromUntrustedFile(File file) {
12623            return new OriginInfo(file, null, false, false);
12624        }
12625
12626        static OriginInfo fromExistingFile(File file) {
12627            return new OriginInfo(file, null, false, true);
12628        }
12629
12630        static OriginInfo fromStagedFile(File file) {
12631            return new OriginInfo(file, null, true, false);
12632        }
12633
12634        static OriginInfo fromStagedContainer(String cid) {
12635            return new OriginInfo(null, cid, true, false);
12636        }
12637
12638        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12639            this.file = file;
12640            this.cid = cid;
12641            this.staged = staged;
12642            this.existing = existing;
12643
12644            if (cid != null) {
12645                resolvedPath = PackageHelper.getSdDir(cid);
12646                resolvedFile = new File(resolvedPath);
12647            } else if (file != null) {
12648                resolvedPath = file.getAbsolutePath();
12649                resolvedFile = file;
12650            } else {
12651                resolvedPath = null;
12652                resolvedFile = null;
12653            }
12654        }
12655    }
12656
12657    static class MoveInfo {
12658        final int moveId;
12659        final String fromUuid;
12660        final String toUuid;
12661        final String packageName;
12662        final String dataAppName;
12663        final int appId;
12664        final String seinfo;
12665        final int targetSdkVersion;
12666
12667        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12668                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12669            this.moveId = moveId;
12670            this.fromUuid = fromUuid;
12671            this.toUuid = toUuid;
12672            this.packageName = packageName;
12673            this.dataAppName = dataAppName;
12674            this.appId = appId;
12675            this.seinfo = seinfo;
12676            this.targetSdkVersion = targetSdkVersion;
12677        }
12678    }
12679
12680    static class VerificationInfo {
12681        /** A constant used to indicate that a uid value is not present. */
12682        public static final int NO_UID = -1;
12683
12684        /** URI referencing where the package was downloaded from. */
12685        final Uri originatingUri;
12686
12687        /** HTTP referrer URI associated with the originatingURI. */
12688        final Uri referrer;
12689
12690        /** UID of the application that the install request originated from. */
12691        final int originatingUid;
12692
12693        /** UID of application requesting the install */
12694        final int installerUid;
12695
12696        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12697            this.originatingUri = originatingUri;
12698            this.referrer = referrer;
12699            this.originatingUid = originatingUid;
12700            this.installerUid = installerUid;
12701        }
12702    }
12703
12704    class InstallParams extends HandlerParams {
12705        final OriginInfo origin;
12706        final MoveInfo move;
12707        final IPackageInstallObserver2 observer;
12708        int installFlags;
12709        final String installerPackageName;
12710        final String volumeUuid;
12711        private InstallArgs mArgs;
12712        private int mRet;
12713        final String packageAbiOverride;
12714        final String[] grantedRuntimePermissions;
12715        final VerificationInfo verificationInfo;
12716        final Certificate[][] certificates;
12717
12718        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12719                int installFlags, String installerPackageName, String volumeUuid,
12720                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12721                String[] grantedPermissions, Certificate[][] certificates) {
12722            super(user);
12723            this.origin = origin;
12724            this.move = move;
12725            this.observer = observer;
12726            this.installFlags = installFlags;
12727            this.installerPackageName = installerPackageName;
12728            this.volumeUuid = volumeUuid;
12729            this.verificationInfo = verificationInfo;
12730            this.packageAbiOverride = packageAbiOverride;
12731            this.grantedRuntimePermissions = grantedPermissions;
12732            this.certificates = certificates;
12733        }
12734
12735        @Override
12736        public String toString() {
12737            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12738                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12739        }
12740
12741        private int installLocationPolicy(PackageInfoLite pkgLite) {
12742            String packageName = pkgLite.packageName;
12743            int installLocation = pkgLite.installLocation;
12744            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12745            // reader
12746            synchronized (mPackages) {
12747                // Currently installed package which the new package is attempting to replace or
12748                // null if no such package is installed.
12749                PackageParser.Package installedPkg = mPackages.get(packageName);
12750                // Package which currently owns the data which the new package will own if installed.
12751                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12752                // will be null whereas dataOwnerPkg will contain information about the package
12753                // which was uninstalled while keeping its data.
12754                PackageParser.Package dataOwnerPkg = installedPkg;
12755                if (dataOwnerPkg  == null) {
12756                    PackageSetting ps = mSettings.mPackages.get(packageName);
12757                    if (ps != null) {
12758                        dataOwnerPkg = ps.pkg;
12759                    }
12760                }
12761
12762                if (dataOwnerPkg != null) {
12763                    // If installed, the package will get access to data left on the device by its
12764                    // predecessor. As a security measure, this is permited only if this is not a
12765                    // version downgrade or if the predecessor package is marked as debuggable and
12766                    // a downgrade is explicitly requested.
12767                    //
12768                    // On debuggable platform builds, downgrades are permitted even for
12769                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12770                    // not offer security guarantees and thus it's OK to disable some security
12771                    // mechanisms to make debugging/testing easier on those builds. However, even on
12772                    // debuggable builds downgrades of packages are permitted only if requested via
12773                    // installFlags. This is because we aim to keep the behavior of debuggable
12774                    // platform builds as close as possible to the behavior of non-debuggable
12775                    // platform builds.
12776                    final boolean downgradeRequested =
12777                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12778                    final boolean packageDebuggable =
12779                                (dataOwnerPkg.applicationInfo.flags
12780                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12781                    final boolean downgradePermitted =
12782                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12783                    if (!downgradePermitted) {
12784                        try {
12785                            checkDowngrade(dataOwnerPkg, pkgLite);
12786                        } catch (PackageManagerException e) {
12787                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12788                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12789                        }
12790                    }
12791                }
12792
12793                if (installedPkg != null) {
12794                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12795                        // Check for updated system application.
12796                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12797                            if (onSd) {
12798                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12799                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12800                            }
12801                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12802                        } else {
12803                            if (onSd) {
12804                                // Install flag overrides everything.
12805                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12806                            }
12807                            // If current upgrade specifies particular preference
12808                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12809                                // Application explicitly specified internal.
12810                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12811                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12812                                // App explictly prefers external. Let policy decide
12813                            } else {
12814                                // Prefer previous location
12815                                if (isExternal(installedPkg)) {
12816                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12817                                }
12818                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12819                            }
12820                        }
12821                    } else {
12822                        // Invalid install. Return error code
12823                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12824                    }
12825                }
12826            }
12827            // All the special cases have been taken care of.
12828            // Return result based on recommended install location.
12829            if (onSd) {
12830                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12831            }
12832            return pkgLite.recommendedInstallLocation;
12833        }
12834
12835        /*
12836         * Invoke remote method to get package information and install
12837         * location values. Override install location based on default
12838         * policy if needed and then create install arguments based
12839         * on the install location.
12840         */
12841        public void handleStartCopy() throws RemoteException {
12842            int ret = PackageManager.INSTALL_SUCCEEDED;
12843
12844            // If we're already staged, we've firmly committed to an install location
12845            if (origin.staged) {
12846                if (origin.file != null) {
12847                    installFlags |= PackageManager.INSTALL_INTERNAL;
12848                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12849                } else if (origin.cid != null) {
12850                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12851                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12852                } else {
12853                    throw new IllegalStateException("Invalid stage location");
12854                }
12855            }
12856
12857            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12858            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12859            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12860            PackageInfoLite pkgLite = null;
12861
12862            if (onInt && onSd) {
12863                // Check if both bits are set.
12864                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12865                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12866            } else if (onSd && ephemeral) {
12867                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12868                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12869            } else {
12870                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12871                        packageAbiOverride);
12872
12873                if (DEBUG_EPHEMERAL && ephemeral) {
12874                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12875                }
12876
12877                /*
12878                 * If we have too little free space, try to free cache
12879                 * before giving up.
12880                 */
12881                if (!origin.staged && pkgLite.recommendedInstallLocation
12882                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12883                    // TODO: focus freeing disk space on the target device
12884                    final StorageManager storage = StorageManager.from(mContext);
12885                    final long lowThreshold = storage.getStorageLowBytes(
12886                            Environment.getDataDirectory());
12887
12888                    final long sizeBytes = mContainerService.calculateInstalledSize(
12889                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12890
12891                    try {
12892                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12893                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12894                                installFlags, packageAbiOverride);
12895                    } catch (InstallerException e) {
12896                        Slog.w(TAG, "Failed to free cache", e);
12897                    }
12898
12899                    /*
12900                     * The cache free must have deleted the file we
12901                     * downloaded to install.
12902                     *
12903                     * TODO: fix the "freeCache" call to not delete
12904                     *       the file we care about.
12905                     */
12906                    if (pkgLite.recommendedInstallLocation
12907                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12908                        pkgLite.recommendedInstallLocation
12909                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12910                    }
12911                }
12912            }
12913
12914            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12915                int loc = pkgLite.recommendedInstallLocation;
12916                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12917                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12918                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12919                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12920                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12921                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12922                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12923                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12924                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12925                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12926                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12927                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12928                } else {
12929                    // Override with defaults if needed.
12930                    loc = installLocationPolicy(pkgLite);
12931                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12932                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12933                    } else if (!onSd && !onInt) {
12934                        // Override install location with flags
12935                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12936                            // Set the flag to install on external media.
12937                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12938                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12939                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12940                            if (DEBUG_EPHEMERAL) {
12941                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12942                            }
12943                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12944                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12945                                    |PackageManager.INSTALL_INTERNAL);
12946                        } else {
12947                            // Make sure the flag for installing on external
12948                            // media is unset
12949                            installFlags |= PackageManager.INSTALL_INTERNAL;
12950                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12951                        }
12952                    }
12953                }
12954            }
12955
12956            final InstallArgs args = createInstallArgs(this);
12957            mArgs = args;
12958
12959            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12960                // TODO: http://b/22976637
12961                // Apps installed for "all" users use the device owner to verify the app
12962                UserHandle verifierUser = getUser();
12963                if (verifierUser == UserHandle.ALL) {
12964                    verifierUser = UserHandle.SYSTEM;
12965                }
12966
12967                /*
12968                 * Determine if we have any installed package verifiers. If we
12969                 * do, then we'll defer to them to verify the packages.
12970                 */
12971                final int requiredUid = mRequiredVerifierPackage == null ? -1
12972                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12973                                verifierUser.getIdentifier());
12974                if (!origin.existing && requiredUid != -1
12975                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12976                    final Intent verification = new Intent(
12977                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12978                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12979                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12980                            PACKAGE_MIME_TYPE);
12981                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12982
12983                    // Query all live verifiers based on current user state
12984                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12985                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12986
12987                    if (DEBUG_VERIFY) {
12988                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12989                                + verification.toString() + " with " + pkgLite.verifiers.length
12990                                + " optional verifiers");
12991                    }
12992
12993                    final int verificationId = mPendingVerificationToken++;
12994
12995                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12996
12997                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12998                            installerPackageName);
12999
13000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13001                            installFlags);
13002
13003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13004                            pkgLite.packageName);
13005
13006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13007                            pkgLite.versionCode);
13008
13009                    if (verificationInfo != null) {
13010                        if (verificationInfo.originatingUri != null) {
13011                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13012                                    verificationInfo.originatingUri);
13013                        }
13014                        if (verificationInfo.referrer != null) {
13015                            verification.putExtra(Intent.EXTRA_REFERRER,
13016                                    verificationInfo.referrer);
13017                        }
13018                        if (verificationInfo.originatingUid >= 0) {
13019                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13020                                    verificationInfo.originatingUid);
13021                        }
13022                        if (verificationInfo.installerUid >= 0) {
13023                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13024                                    verificationInfo.installerUid);
13025                        }
13026                    }
13027
13028                    final PackageVerificationState verificationState = new PackageVerificationState(
13029                            requiredUid, args);
13030
13031                    mPendingVerification.append(verificationId, verificationState);
13032
13033                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13034                            receivers, verificationState);
13035
13036                    /*
13037                     * If any sufficient verifiers were listed in the package
13038                     * manifest, attempt to ask them.
13039                     */
13040                    if (sufficientVerifiers != null) {
13041                        final int N = sufficientVerifiers.size();
13042                        if (N == 0) {
13043                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13044                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13045                        } else {
13046                            for (int i = 0; i < N; i++) {
13047                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13048
13049                                final Intent sufficientIntent = new Intent(verification);
13050                                sufficientIntent.setComponent(verifierComponent);
13051                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13052                            }
13053                        }
13054                    }
13055
13056                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13057                            mRequiredVerifierPackage, receivers);
13058                    if (ret == PackageManager.INSTALL_SUCCEEDED
13059                            && mRequiredVerifierPackage != null) {
13060                        Trace.asyncTraceBegin(
13061                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13062                        /*
13063                         * Send the intent to the required verification agent,
13064                         * but only start the verification timeout after the
13065                         * target BroadcastReceivers have run.
13066                         */
13067                        verification.setComponent(requiredVerifierComponent);
13068                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13069                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13070                                new BroadcastReceiver() {
13071                                    @Override
13072                                    public void onReceive(Context context, Intent intent) {
13073                                        final Message msg = mHandler
13074                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13075                                        msg.arg1 = verificationId;
13076                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13077                                    }
13078                                }, null, 0, null, null);
13079
13080                        /*
13081                         * We don't want the copy to proceed until verification
13082                         * succeeds, so null out this field.
13083                         */
13084                        mArgs = null;
13085                    }
13086                } else {
13087                    /*
13088                     * No package verification is enabled, so immediately start
13089                     * the remote call to initiate copy using temporary file.
13090                     */
13091                    ret = args.copyApk(mContainerService, true);
13092                }
13093            }
13094
13095            mRet = ret;
13096        }
13097
13098        @Override
13099        void handleReturnCode() {
13100            // If mArgs is null, then MCS couldn't be reached. When it
13101            // reconnects, it will try again to install. At that point, this
13102            // will succeed.
13103            if (mArgs != null) {
13104                processPendingInstall(mArgs, mRet);
13105            }
13106        }
13107
13108        @Override
13109        void handleServiceError() {
13110            mArgs = createInstallArgs(this);
13111            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13112        }
13113
13114        public boolean isForwardLocked() {
13115            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13116        }
13117    }
13118
13119    /**
13120     * Used during creation of InstallArgs
13121     *
13122     * @param installFlags package installation flags
13123     * @return true if should be installed on external storage
13124     */
13125    private static boolean installOnExternalAsec(int installFlags) {
13126        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13127            return false;
13128        }
13129        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13130            return true;
13131        }
13132        return false;
13133    }
13134
13135    /**
13136     * Used during creation of InstallArgs
13137     *
13138     * @param installFlags package installation flags
13139     * @return true if should be installed as forward locked
13140     */
13141    private static boolean installForwardLocked(int installFlags) {
13142        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13143    }
13144
13145    private InstallArgs createInstallArgs(InstallParams params) {
13146        if (params.move != null) {
13147            return new MoveInstallArgs(params);
13148        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13149            return new AsecInstallArgs(params);
13150        } else {
13151            return new FileInstallArgs(params);
13152        }
13153    }
13154
13155    /**
13156     * Create args that describe an existing installed package. Typically used
13157     * when cleaning up old installs, or used as a move source.
13158     */
13159    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13160            String resourcePath, String[] instructionSets) {
13161        final boolean isInAsec;
13162        if (installOnExternalAsec(installFlags)) {
13163            /* Apps on SD card are always in ASEC containers. */
13164            isInAsec = true;
13165        } else if (installForwardLocked(installFlags)
13166                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13167            /*
13168             * Forward-locked apps are only in ASEC containers if they're the
13169             * new style
13170             */
13171            isInAsec = true;
13172        } else {
13173            isInAsec = false;
13174        }
13175
13176        if (isInAsec) {
13177            return new AsecInstallArgs(codePath, instructionSets,
13178                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13179        } else {
13180            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13181        }
13182    }
13183
13184    static abstract class InstallArgs {
13185        /** @see InstallParams#origin */
13186        final OriginInfo origin;
13187        /** @see InstallParams#move */
13188        final MoveInfo move;
13189
13190        final IPackageInstallObserver2 observer;
13191        // Always refers to PackageManager flags only
13192        final int installFlags;
13193        final String installerPackageName;
13194        final String volumeUuid;
13195        final UserHandle user;
13196        final String abiOverride;
13197        final String[] installGrantPermissions;
13198        /** If non-null, drop an async trace when the install completes */
13199        final String traceMethod;
13200        final int traceCookie;
13201        final Certificate[][] certificates;
13202
13203        // The list of instruction sets supported by this app. This is currently
13204        // only used during the rmdex() phase to clean up resources. We can get rid of this
13205        // if we move dex files under the common app path.
13206        /* nullable */ String[] instructionSets;
13207
13208        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13209                int installFlags, String installerPackageName, String volumeUuid,
13210                UserHandle user, String[] instructionSets,
13211                String abiOverride, String[] installGrantPermissions,
13212                String traceMethod, int traceCookie, Certificate[][] certificates) {
13213            this.origin = origin;
13214            this.move = move;
13215            this.installFlags = installFlags;
13216            this.observer = observer;
13217            this.installerPackageName = installerPackageName;
13218            this.volumeUuid = volumeUuid;
13219            this.user = user;
13220            this.instructionSets = instructionSets;
13221            this.abiOverride = abiOverride;
13222            this.installGrantPermissions = installGrantPermissions;
13223            this.traceMethod = traceMethod;
13224            this.traceCookie = traceCookie;
13225            this.certificates = certificates;
13226        }
13227
13228        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13229        abstract int doPreInstall(int status);
13230
13231        /**
13232         * Rename package into final resting place. All paths on the given
13233         * scanned package should be updated to reflect the rename.
13234         */
13235        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13236        abstract int doPostInstall(int status, int uid);
13237
13238        /** @see PackageSettingBase#codePathString */
13239        abstract String getCodePath();
13240        /** @see PackageSettingBase#resourcePathString */
13241        abstract String getResourcePath();
13242
13243        // Need installer lock especially for dex file removal.
13244        abstract void cleanUpResourcesLI();
13245        abstract boolean doPostDeleteLI(boolean delete);
13246
13247        /**
13248         * Called before the source arguments are copied. This is used mostly
13249         * for MoveParams when it needs to read the source file to put it in the
13250         * destination.
13251         */
13252        int doPreCopy() {
13253            return PackageManager.INSTALL_SUCCEEDED;
13254        }
13255
13256        /**
13257         * Called after the source arguments are copied. This is used mostly for
13258         * MoveParams when it needs to read the source file to put it in the
13259         * destination.
13260         */
13261        int doPostCopy(int uid) {
13262            return PackageManager.INSTALL_SUCCEEDED;
13263        }
13264
13265        protected boolean isFwdLocked() {
13266            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13267        }
13268
13269        protected boolean isExternalAsec() {
13270            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13271        }
13272
13273        protected boolean isEphemeral() {
13274            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13275        }
13276
13277        UserHandle getUser() {
13278            return user;
13279        }
13280    }
13281
13282    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13283        if (!allCodePaths.isEmpty()) {
13284            if (instructionSets == null) {
13285                throw new IllegalStateException("instructionSet == null");
13286            }
13287            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13288            for (String codePath : allCodePaths) {
13289                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13290                    try {
13291                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13292                    } catch (InstallerException ignored) {
13293                    }
13294                }
13295            }
13296        }
13297    }
13298
13299    /**
13300     * Logic to handle installation of non-ASEC applications, including copying
13301     * and renaming logic.
13302     */
13303    class FileInstallArgs extends InstallArgs {
13304        private File codeFile;
13305        private File resourceFile;
13306
13307        // Example topology:
13308        // /data/app/com.example/base.apk
13309        // /data/app/com.example/split_foo.apk
13310        // /data/app/com.example/lib/arm/libfoo.so
13311        // /data/app/com.example/lib/arm64/libfoo.so
13312        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13313
13314        /** New install */
13315        FileInstallArgs(InstallParams params) {
13316            super(params.origin, params.move, params.observer, params.installFlags,
13317                    params.installerPackageName, params.volumeUuid,
13318                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13319                    params.grantedRuntimePermissions,
13320                    params.traceMethod, params.traceCookie, params.certificates);
13321            if (isFwdLocked()) {
13322                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13323            }
13324        }
13325
13326        /** Existing install */
13327        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13328            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13329                    null, null, null, 0, null /*certificates*/);
13330            this.codeFile = (codePath != null) ? new File(codePath) : null;
13331            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13332        }
13333
13334        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13336            try {
13337                return doCopyApk(imcs, temp);
13338            } finally {
13339                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13340            }
13341        }
13342
13343        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13344            if (origin.staged) {
13345                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13346                codeFile = origin.file;
13347                resourceFile = origin.file;
13348                return PackageManager.INSTALL_SUCCEEDED;
13349            }
13350
13351            try {
13352                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13353                final File tempDir =
13354                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13355                codeFile = tempDir;
13356                resourceFile = tempDir;
13357            } catch (IOException e) {
13358                Slog.w(TAG, "Failed to create copy file: " + e);
13359                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13360            }
13361
13362            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13363                @Override
13364                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13365                    if (!FileUtils.isValidExtFilename(name)) {
13366                        throw new IllegalArgumentException("Invalid filename: " + name);
13367                    }
13368                    try {
13369                        final File file = new File(codeFile, name);
13370                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13371                                O_RDWR | O_CREAT, 0644);
13372                        Os.chmod(file.getAbsolutePath(), 0644);
13373                        return new ParcelFileDescriptor(fd);
13374                    } catch (ErrnoException e) {
13375                        throw new RemoteException("Failed to open: " + e.getMessage());
13376                    }
13377                }
13378            };
13379
13380            int ret = PackageManager.INSTALL_SUCCEEDED;
13381            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13382            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13383                Slog.e(TAG, "Failed to copy package");
13384                return ret;
13385            }
13386
13387            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13388            NativeLibraryHelper.Handle handle = null;
13389            try {
13390                handle = NativeLibraryHelper.Handle.create(codeFile);
13391                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13392                        abiOverride);
13393            } catch (IOException e) {
13394                Slog.e(TAG, "Copying native libraries failed", e);
13395                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13396            } finally {
13397                IoUtils.closeQuietly(handle);
13398            }
13399
13400            return ret;
13401        }
13402
13403        int doPreInstall(int status) {
13404            if (status != PackageManager.INSTALL_SUCCEEDED) {
13405                cleanUp();
13406            }
13407            return status;
13408        }
13409
13410        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13411            if (status != PackageManager.INSTALL_SUCCEEDED) {
13412                cleanUp();
13413                return false;
13414            }
13415
13416            final File targetDir = codeFile.getParentFile();
13417            final File beforeCodeFile = codeFile;
13418            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13419
13420            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13421            try {
13422                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13423            } catch (ErrnoException e) {
13424                Slog.w(TAG, "Failed to rename", e);
13425                return false;
13426            }
13427
13428            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13429                Slog.w(TAG, "Failed to restorecon");
13430                return false;
13431            }
13432
13433            // Reflect the rename internally
13434            codeFile = afterCodeFile;
13435            resourceFile = afterCodeFile;
13436
13437            // Reflect the rename in scanned details
13438            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13439            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13440                    afterCodeFile, pkg.baseCodePath));
13441            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13442                    afterCodeFile, pkg.splitCodePaths));
13443
13444            // Reflect the rename in app info
13445            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13446            pkg.setApplicationInfoCodePath(pkg.codePath);
13447            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13448            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13449            pkg.setApplicationInfoResourcePath(pkg.codePath);
13450            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13451            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13452
13453            return true;
13454        }
13455
13456        int doPostInstall(int status, int uid) {
13457            if (status != PackageManager.INSTALL_SUCCEEDED) {
13458                cleanUp();
13459            }
13460            return status;
13461        }
13462
13463        @Override
13464        String getCodePath() {
13465            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13466        }
13467
13468        @Override
13469        String getResourcePath() {
13470            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13471        }
13472
13473        private boolean cleanUp() {
13474            if (codeFile == null || !codeFile.exists()) {
13475                return false;
13476            }
13477
13478            removeCodePathLI(codeFile);
13479
13480            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13481                resourceFile.delete();
13482            }
13483
13484            return true;
13485        }
13486
13487        void cleanUpResourcesLI() {
13488            // Try enumerating all code paths before deleting
13489            List<String> allCodePaths = Collections.EMPTY_LIST;
13490            if (codeFile != null && codeFile.exists()) {
13491                try {
13492                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13493                    allCodePaths = pkg.getAllCodePaths();
13494                } catch (PackageParserException e) {
13495                    // Ignored; we tried our best
13496                }
13497            }
13498
13499            cleanUp();
13500            removeDexFiles(allCodePaths, instructionSets);
13501        }
13502
13503        boolean doPostDeleteLI(boolean delete) {
13504            // XXX err, shouldn't we respect the delete flag?
13505            cleanUpResourcesLI();
13506            return true;
13507        }
13508    }
13509
13510    private boolean isAsecExternal(String cid) {
13511        final String asecPath = PackageHelper.getSdFilesystem(cid);
13512        return !asecPath.startsWith(mAsecInternalPath);
13513    }
13514
13515    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13516            PackageManagerException {
13517        if (copyRet < 0) {
13518            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13519                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13520                throw new PackageManagerException(copyRet, message);
13521            }
13522        }
13523    }
13524
13525    /**
13526     * Extract the MountService "container ID" from the full code path of an
13527     * .apk.
13528     */
13529    static String cidFromCodePath(String fullCodePath) {
13530        int eidx = fullCodePath.lastIndexOf("/");
13531        String subStr1 = fullCodePath.substring(0, eidx);
13532        int sidx = subStr1.lastIndexOf("/");
13533        return subStr1.substring(sidx+1, eidx);
13534    }
13535
13536    /**
13537     * Logic to handle installation of ASEC applications, including copying and
13538     * renaming logic.
13539     */
13540    class AsecInstallArgs extends InstallArgs {
13541        static final String RES_FILE_NAME = "pkg.apk";
13542        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13543
13544        String cid;
13545        String packagePath;
13546        String resourcePath;
13547
13548        /** New install */
13549        AsecInstallArgs(InstallParams params) {
13550            super(params.origin, params.move, params.observer, params.installFlags,
13551                    params.installerPackageName, params.volumeUuid,
13552                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13553                    params.grantedRuntimePermissions,
13554                    params.traceMethod, params.traceCookie, params.certificates);
13555        }
13556
13557        /** Existing install */
13558        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13559                        boolean isExternal, boolean isForwardLocked) {
13560            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13561              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13562                    instructionSets, null, null, null, 0, null /*certificates*/);
13563            // Hackily pretend we're still looking at a full code path
13564            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13565                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13566            }
13567
13568            // Extract cid from fullCodePath
13569            int eidx = fullCodePath.lastIndexOf("/");
13570            String subStr1 = fullCodePath.substring(0, eidx);
13571            int sidx = subStr1.lastIndexOf("/");
13572            cid = subStr1.substring(sidx+1, eidx);
13573            setMountPath(subStr1);
13574        }
13575
13576        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13577            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13578              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13579                    instructionSets, null, null, null, 0, null /*certificates*/);
13580            this.cid = cid;
13581            setMountPath(PackageHelper.getSdDir(cid));
13582        }
13583
13584        void createCopyFile() {
13585            cid = mInstallerService.allocateExternalStageCidLegacy();
13586        }
13587
13588        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13589            if (origin.staged && origin.cid != null) {
13590                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13591                cid = origin.cid;
13592                setMountPath(PackageHelper.getSdDir(cid));
13593                return PackageManager.INSTALL_SUCCEEDED;
13594            }
13595
13596            if (temp) {
13597                createCopyFile();
13598            } else {
13599                /*
13600                 * Pre-emptively destroy the container since it's destroyed if
13601                 * copying fails due to it existing anyway.
13602                 */
13603                PackageHelper.destroySdDir(cid);
13604            }
13605
13606            final String newMountPath = imcs.copyPackageToContainer(
13607                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13608                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13609
13610            if (newMountPath != null) {
13611                setMountPath(newMountPath);
13612                return PackageManager.INSTALL_SUCCEEDED;
13613            } else {
13614                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13615            }
13616        }
13617
13618        @Override
13619        String getCodePath() {
13620            return packagePath;
13621        }
13622
13623        @Override
13624        String getResourcePath() {
13625            return resourcePath;
13626        }
13627
13628        int doPreInstall(int status) {
13629            if (status != PackageManager.INSTALL_SUCCEEDED) {
13630                // Destroy container
13631                PackageHelper.destroySdDir(cid);
13632            } else {
13633                boolean mounted = PackageHelper.isContainerMounted(cid);
13634                if (!mounted) {
13635                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13636                            Process.SYSTEM_UID);
13637                    if (newMountPath != null) {
13638                        setMountPath(newMountPath);
13639                    } else {
13640                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13641                    }
13642                }
13643            }
13644            return status;
13645        }
13646
13647        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13648            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13649            String newMountPath = null;
13650            if (PackageHelper.isContainerMounted(cid)) {
13651                // Unmount the container
13652                if (!PackageHelper.unMountSdDir(cid)) {
13653                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13654                    return false;
13655                }
13656            }
13657            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13658                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13659                        " which might be stale. Will try to clean up.");
13660                // Clean up the stale container and proceed to recreate.
13661                if (!PackageHelper.destroySdDir(newCacheId)) {
13662                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13663                    return false;
13664                }
13665                // Successfully cleaned up stale container. Try to rename again.
13666                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13667                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13668                            + " inspite of cleaning it up.");
13669                    return false;
13670                }
13671            }
13672            if (!PackageHelper.isContainerMounted(newCacheId)) {
13673                Slog.w(TAG, "Mounting container " + newCacheId);
13674                newMountPath = PackageHelper.mountSdDir(newCacheId,
13675                        getEncryptKey(), Process.SYSTEM_UID);
13676            } else {
13677                newMountPath = PackageHelper.getSdDir(newCacheId);
13678            }
13679            if (newMountPath == null) {
13680                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13681                return false;
13682            }
13683            Log.i(TAG, "Succesfully renamed " + cid +
13684                    " to " + newCacheId +
13685                    " at new path: " + newMountPath);
13686            cid = newCacheId;
13687
13688            final File beforeCodeFile = new File(packagePath);
13689            setMountPath(newMountPath);
13690            final File afterCodeFile = new File(packagePath);
13691
13692            // Reflect the rename in scanned details
13693            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13694            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13695                    afterCodeFile, pkg.baseCodePath));
13696            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13697                    afterCodeFile, pkg.splitCodePaths));
13698
13699            // Reflect the rename in app info
13700            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13701            pkg.setApplicationInfoCodePath(pkg.codePath);
13702            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13703            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13704            pkg.setApplicationInfoResourcePath(pkg.codePath);
13705            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13706            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13707
13708            return true;
13709        }
13710
13711        private void setMountPath(String mountPath) {
13712            final File mountFile = new File(mountPath);
13713
13714            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13715            if (monolithicFile.exists()) {
13716                packagePath = monolithicFile.getAbsolutePath();
13717                if (isFwdLocked()) {
13718                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13719                } else {
13720                    resourcePath = packagePath;
13721                }
13722            } else {
13723                packagePath = mountFile.getAbsolutePath();
13724                resourcePath = packagePath;
13725            }
13726        }
13727
13728        int doPostInstall(int status, int uid) {
13729            if (status != PackageManager.INSTALL_SUCCEEDED) {
13730                cleanUp();
13731            } else {
13732                final int groupOwner;
13733                final String protectedFile;
13734                if (isFwdLocked()) {
13735                    groupOwner = UserHandle.getSharedAppGid(uid);
13736                    protectedFile = RES_FILE_NAME;
13737                } else {
13738                    groupOwner = -1;
13739                    protectedFile = null;
13740                }
13741
13742                if (uid < Process.FIRST_APPLICATION_UID
13743                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13744                    Slog.e(TAG, "Failed to finalize " + cid);
13745                    PackageHelper.destroySdDir(cid);
13746                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13747                }
13748
13749                boolean mounted = PackageHelper.isContainerMounted(cid);
13750                if (!mounted) {
13751                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13752                }
13753            }
13754            return status;
13755        }
13756
13757        private void cleanUp() {
13758            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13759
13760            // Destroy secure container
13761            PackageHelper.destroySdDir(cid);
13762        }
13763
13764        private List<String> getAllCodePaths() {
13765            final File codeFile = new File(getCodePath());
13766            if (codeFile != null && codeFile.exists()) {
13767                try {
13768                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13769                    return pkg.getAllCodePaths();
13770                } catch (PackageParserException e) {
13771                    // Ignored; we tried our best
13772                }
13773            }
13774            return Collections.EMPTY_LIST;
13775        }
13776
13777        void cleanUpResourcesLI() {
13778            // Enumerate all code paths before deleting
13779            cleanUpResourcesLI(getAllCodePaths());
13780        }
13781
13782        private void cleanUpResourcesLI(List<String> allCodePaths) {
13783            cleanUp();
13784            removeDexFiles(allCodePaths, instructionSets);
13785        }
13786
13787        String getPackageName() {
13788            return getAsecPackageName(cid);
13789        }
13790
13791        boolean doPostDeleteLI(boolean delete) {
13792            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13793            final List<String> allCodePaths = getAllCodePaths();
13794            boolean mounted = PackageHelper.isContainerMounted(cid);
13795            if (mounted) {
13796                // Unmount first
13797                if (PackageHelper.unMountSdDir(cid)) {
13798                    mounted = false;
13799                }
13800            }
13801            if (!mounted && delete) {
13802                cleanUpResourcesLI(allCodePaths);
13803            }
13804            return !mounted;
13805        }
13806
13807        @Override
13808        int doPreCopy() {
13809            if (isFwdLocked()) {
13810                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13811                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13812                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13813                }
13814            }
13815
13816            return PackageManager.INSTALL_SUCCEEDED;
13817        }
13818
13819        @Override
13820        int doPostCopy(int uid) {
13821            if (isFwdLocked()) {
13822                if (uid < Process.FIRST_APPLICATION_UID
13823                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13824                                RES_FILE_NAME)) {
13825                    Slog.e(TAG, "Failed to finalize " + cid);
13826                    PackageHelper.destroySdDir(cid);
13827                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13828                }
13829            }
13830
13831            return PackageManager.INSTALL_SUCCEEDED;
13832        }
13833    }
13834
13835    /**
13836     * Logic to handle movement of existing installed applications.
13837     */
13838    class MoveInstallArgs extends InstallArgs {
13839        private File codeFile;
13840        private File resourceFile;
13841
13842        /** New install */
13843        MoveInstallArgs(InstallParams params) {
13844            super(params.origin, params.move, params.observer, params.installFlags,
13845                    params.installerPackageName, params.volumeUuid,
13846                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13847                    params.grantedRuntimePermissions,
13848                    params.traceMethod, params.traceCookie, params.certificates);
13849        }
13850
13851        int copyApk(IMediaContainerService imcs, boolean temp) {
13852            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13853                    + move.fromUuid + " to " + move.toUuid);
13854            synchronized (mInstaller) {
13855                try {
13856                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13857                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13858                } catch (InstallerException e) {
13859                    Slog.w(TAG, "Failed to move app", e);
13860                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13861                }
13862            }
13863
13864            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13865            resourceFile = codeFile;
13866            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13867
13868            return PackageManager.INSTALL_SUCCEEDED;
13869        }
13870
13871        int doPreInstall(int status) {
13872            if (status != PackageManager.INSTALL_SUCCEEDED) {
13873                cleanUp(move.toUuid);
13874            }
13875            return status;
13876        }
13877
13878        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13879            if (status != PackageManager.INSTALL_SUCCEEDED) {
13880                cleanUp(move.toUuid);
13881                return false;
13882            }
13883
13884            // Reflect the move in app info
13885            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13886            pkg.setApplicationInfoCodePath(pkg.codePath);
13887            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13888            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13889            pkg.setApplicationInfoResourcePath(pkg.codePath);
13890            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13891            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13892
13893            return true;
13894        }
13895
13896        int doPostInstall(int status, int uid) {
13897            if (status == PackageManager.INSTALL_SUCCEEDED) {
13898                cleanUp(move.fromUuid);
13899            } else {
13900                cleanUp(move.toUuid);
13901            }
13902            return status;
13903        }
13904
13905        @Override
13906        String getCodePath() {
13907            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13908        }
13909
13910        @Override
13911        String getResourcePath() {
13912            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13913        }
13914
13915        private boolean cleanUp(String volumeUuid) {
13916            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13917                    move.dataAppName);
13918            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13919            final int[] userIds = sUserManager.getUserIds();
13920            synchronized (mInstallLock) {
13921                // Clean up both app data and code
13922                // All package moves are frozen until finished
13923                for (int userId : userIds) {
13924                    try {
13925                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13926                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13927                    } catch (InstallerException e) {
13928                        Slog.w(TAG, String.valueOf(e));
13929                    }
13930                }
13931                removeCodePathLI(codeFile);
13932            }
13933            return true;
13934        }
13935
13936        void cleanUpResourcesLI() {
13937            throw new UnsupportedOperationException();
13938        }
13939
13940        boolean doPostDeleteLI(boolean delete) {
13941            throw new UnsupportedOperationException();
13942        }
13943    }
13944
13945    static String getAsecPackageName(String packageCid) {
13946        int idx = packageCid.lastIndexOf("-");
13947        if (idx == -1) {
13948            return packageCid;
13949        }
13950        return packageCid.substring(0, idx);
13951    }
13952
13953    // Utility method used to create code paths based on package name and available index.
13954    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13955        String idxStr = "";
13956        int idx = 1;
13957        // Fall back to default value of idx=1 if prefix is not
13958        // part of oldCodePath
13959        if (oldCodePath != null) {
13960            String subStr = oldCodePath;
13961            // Drop the suffix right away
13962            if (suffix != null && subStr.endsWith(suffix)) {
13963                subStr = subStr.substring(0, subStr.length() - suffix.length());
13964            }
13965            // If oldCodePath already contains prefix find out the
13966            // ending index to either increment or decrement.
13967            int sidx = subStr.lastIndexOf(prefix);
13968            if (sidx != -1) {
13969                subStr = subStr.substring(sidx + prefix.length());
13970                if (subStr != null) {
13971                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13972                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13973                    }
13974                    try {
13975                        idx = Integer.parseInt(subStr);
13976                        if (idx <= 1) {
13977                            idx++;
13978                        } else {
13979                            idx--;
13980                        }
13981                    } catch(NumberFormatException e) {
13982                    }
13983                }
13984            }
13985        }
13986        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13987        return prefix + idxStr;
13988    }
13989
13990    private File getNextCodePath(File targetDir, String packageName) {
13991        int suffix = 1;
13992        File result;
13993        do {
13994            result = new File(targetDir, packageName + "-" + suffix);
13995            suffix++;
13996        } while (result.exists());
13997        return result;
13998    }
13999
14000    // Utility method that returns the relative package path with respect
14001    // to the installation directory. Like say for /data/data/com.test-1.apk
14002    // string com.test-1 is returned.
14003    static String deriveCodePathName(String codePath) {
14004        if (codePath == null) {
14005            return null;
14006        }
14007        final File codeFile = new File(codePath);
14008        final String name = codeFile.getName();
14009        if (codeFile.isDirectory()) {
14010            return name;
14011        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14012            final int lastDot = name.lastIndexOf('.');
14013            return name.substring(0, lastDot);
14014        } else {
14015            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14016            return null;
14017        }
14018    }
14019
14020    static class PackageInstalledInfo {
14021        String name;
14022        int uid;
14023        // The set of users that originally had this package installed.
14024        int[] origUsers;
14025        // The set of users that now have this package installed.
14026        int[] newUsers;
14027        PackageParser.Package pkg;
14028        int returnCode;
14029        String returnMsg;
14030        PackageRemovedInfo removedInfo;
14031        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14032
14033        public void setError(int code, String msg) {
14034            setReturnCode(code);
14035            setReturnMessage(msg);
14036            Slog.w(TAG, msg);
14037        }
14038
14039        public void setError(String msg, PackageParserException e) {
14040            setReturnCode(e.error);
14041            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14042            Slog.w(TAG, msg, e);
14043        }
14044
14045        public void setError(String msg, PackageManagerException e) {
14046            returnCode = e.error;
14047            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14048            Slog.w(TAG, msg, e);
14049        }
14050
14051        public void setReturnCode(int returnCode) {
14052            this.returnCode = returnCode;
14053            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14054            for (int i = 0; i < childCount; i++) {
14055                addedChildPackages.valueAt(i).returnCode = returnCode;
14056            }
14057        }
14058
14059        private void setReturnMessage(String returnMsg) {
14060            this.returnMsg = returnMsg;
14061            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14062            for (int i = 0; i < childCount; i++) {
14063                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14064            }
14065        }
14066
14067        // In some error cases we want to convey more info back to the observer
14068        String origPackage;
14069        String origPermission;
14070    }
14071
14072    /*
14073     * Install a non-existing package.
14074     */
14075    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14076            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14077            PackageInstalledInfo res) {
14078        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14079
14080        // Remember this for later, in case we need to rollback this install
14081        String pkgName = pkg.packageName;
14082
14083        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14084
14085        synchronized(mPackages) {
14086            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14087                // A package with the same name is already installed, though
14088                // it has been renamed to an older name.  The package we
14089                // are trying to install should be installed as an update to
14090                // the existing one, but that has not been requested, so bail.
14091                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14092                        + " without first uninstalling package running as "
14093                        + mSettings.mRenamedPackages.get(pkgName));
14094                return;
14095            }
14096            if (mPackages.containsKey(pkgName)) {
14097                // Don't allow installation over an existing package with the same name.
14098                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14099                        + " without first uninstalling.");
14100                return;
14101            }
14102        }
14103
14104        try {
14105            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14106                    System.currentTimeMillis(), user);
14107
14108            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14109
14110            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14111                prepareAppDataAfterInstallLIF(newPackage);
14112
14113            } else {
14114                // Remove package from internal structures, but keep around any
14115                // data that might have already existed
14116                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14117                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14118            }
14119        } catch (PackageManagerException e) {
14120            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14121        }
14122
14123        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14124    }
14125
14126    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14127        // Can't rotate keys during boot or if sharedUser.
14128        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14129                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14130            return false;
14131        }
14132        // app is using upgradeKeySets; make sure all are valid
14133        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14134        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14135        for (int i = 0; i < upgradeKeySets.length; i++) {
14136            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14137                Slog.wtf(TAG, "Package "
14138                         + (oldPs.name != null ? oldPs.name : "<null>")
14139                         + " contains upgrade-key-set reference to unknown key-set: "
14140                         + upgradeKeySets[i]
14141                         + " reverting to signatures check.");
14142                return false;
14143            }
14144        }
14145        return true;
14146    }
14147
14148    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14149        // Upgrade keysets are being used.  Determine if new package has a superset of the
14150        // required keys.
14151        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14152        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14153        for (int i = 0; i < upgradeKeySets.length; i++) {
14154            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14155            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14156                return true;
14157            }
14158        }
14159        return false;
14160    }
14161
14162    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14163        try (DigestInputStream digestStream =
14164                new DigestInputStream(new FileInputStream(file), digest)) {
14165            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14166        }
14167    }
14168
14169    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14170            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14171        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14172
14173        final PackageParser.Package oldPackage;
14174        final String pkgName = pkg.packageName;
14175        final int[] allUsers;
14176        final int[] installedUsers;
14177
14178        synchronized(mPackages) {
14179            oldPackage = mPackages.get(pkgName);
14180            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14181
14182            // don't allow upgrade to target a release SDK from a pre-release SDK
14183            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14184                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14185            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14186                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14187            if (oldTargetsPreRelease
14188                    && !newTargetsPreRelease
14189                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14190                Slog.w(TAG, "Can't install package targeting released sdk");
14191                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14192                return;
14193            }
14194
14195            // don't allow an upgrade from full to ephemeral
14196            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14197            if (isEphemeral && !oldIsEphemeral) {
14198                // can't downgrade from full to ephemeral
14199                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14200                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14201                return;
14202            }
14203
14204            // verify signatures are valid
14205            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14206            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14207                if (!checkUpgradeKeySetLP(ps, pkg)) {
14208                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14209                            "New package not signed by keys specified by upgrade-keysets: "
14210                                    + pkgName);
14211                    return;
14212                }
14213            } else {
14214                // default to original signature matching
14215                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14216                        != PackageManager.SIGNATURE_MATCH) {
14217                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14218                            "New package has a different signature: " + pkgName);
14219                    return;
14220                }
14221            }
14222
14223            // don't allow a system upgrade unless the upgrade hash matches
14224            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14225                byte[] digestBytes = null;
14226                try {
14227                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14228                    updateDigest(digest, new File(pkg.baseCodePath));
14229                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14230                        for (String path : pkg.splitCodePaths) {
14231                            updateDigest(digest, new File(path));
14232                        }
14233                    }
14234                    digestBytes = digest.digest();
14235                } catch (NoSuchAlgorithmException | IOException e) {
14236                    res.setError(INSTALL_FAILED_INVALID_APK,
14237                            "Could not compute hash: " + pkgName);
14238                    return;
14239                }
14240                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14241                    res.setError(INSTALL_FAILED_INVALID_APK,
14242                            "New package fails restrict-update check: " + pkgName);
14243                    return;
14244                }
14245                // retain upgrade restriction
14246                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14247            }
14248
14249            // Check for shared user id changes
14250            String invalidPackageName =
14251                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14252            if (invalidPackageName != null) {
14253                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14254                        "Package " + invalidPackageName + " tried to change user "
14255                                + oldPackage.mSharedUserId);
14256                return;
14257            }
14258
14259            // In case of rollback, remember per-user/profile install state
14260            allUsers = sUserManager.getUserIds();
14261            installedUsers = ps.queryInstalledUsers(allUsers, true);
14262        }
14263
14264        // Update what is removed
14265        res.removedInfo = new PackageRemovedInfo();
14266        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14267        res.removedInfo.removedPackage = oldPackage.packageName;
14268        res.removedInfo.isUpdate = true;
14269        res.removedInfo.origUsers = installedUsers;
14270        final int childCount = (oldPackage.childPackages != null)
14271                ? oldPackage.childPackages.size() : 0;
14272        for (int i = 0; i < childCount; i++) {
14273            boolean childPackageUpdated = false;
14274            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14275            if (res.addedChildPackages != null) {
14276                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14277                if (childRes != null) {
14278                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14279                    childRes.removedInfo.removedPackage = childPkg.packageName;
14280                    childRes.removedInfo.isUpdate = true;
14281                    childPackageUpdated = true;
14282                }
14283            }
14284            if (!childPackageUpdated) {
14285                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14286                childRemovedRes.removedPackage = childPkg.packageName;
14287                childRemovedRes.isUpdate = false;
14288                childRemovedRes.dataRemoved = true;
14289                synchronized (mPackages) {
14290                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14291                    if (childPs != null) {
14292                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14293                    }
14294                }
14295                if (res.removedInfo.removedChildPackages == null) {
14296                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14297                }
14298                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14299            }
14300        }
14301
14302        boolean sysPkg = (isSystemApp(oldPackage));
14303        if (sysPkg) {
14304            // Set the system/privileged flags as needed
14305            final boolean privileged =
14306                    (oldPackage.applicationInfo.privateFlags
14307                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14308            final int systemPolicyFlags = policyFlags
14309                    | PackageParser.PARSE_IS_SYSTEM
14310                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14311
14312            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14313                    user, allUsers, installerPackageName, res);
14314        } else {
14315            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14316                    user, allUsers, installerPackageName, res);
14317        }
14318    }
14319
14320    public List<String> getPreviousCodePaths(String packageName) {
14321        final PackageSetting ps = mSettings.mPackages.get(packageName);
14322        final List<String> result = new ArrayList<String>();
14323        if (ps != null && ps.oldCodePaths != null) {
14324            result.addAll(ps.oldCodePaths);
14325        }
14326        return result;
14327    }
14328
14329    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14330            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14331            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14332        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14333                + deletedPackage);
14334
14335        String pkgName = deletedPackage.packageName;
14336        boolean deletedPkg = true;
14337        boolean addedPkg = false;
14338        boolean updatedSettings = false;
14339        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14340        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14341                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14342
14343        final long origUpdateTime = (pkg.mExtras != null)
14344                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14345
14346        // First delete the existing package while retaining the data directory
14347        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14348                res.removedInfo, true, pkg)) {
14349            // If the existing package wasn't successfully deleted
14350            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14351            deletedPkg = false;
14352        } else {
14353            // Successfully deleted the old package; proceed with replace.
14354
14355            // If deleted package lived in a container, give users a chance to
14356            // relinquish resources before killing.
14357            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14358                if (DEBUG_INSTALL) {
14359                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14360                }
14361                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14362                final ArrayList<String> pkgList = new ArrayList<String>(1);
14363                pkgList.add(deletedPackage.applicationInfo.packageName);
14364                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14365            }
14366
14367            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14368                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14369            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14370
14371            try {
14372                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14373                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14374                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14375
14376                // Update the in-memory copy of the previous code paths.
14377                PackageSetting ps = mSettings.mPackages.get(pkgName);
14378                if (!killApp) {
14379                    if (ps.oldCodePaths == null) {
14380                        ps.oldCodePaths = new ArraySet<>();
14381                    }
14382                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14383                    if (deletedPackage.splitCodePaths != null) {
14384                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14385                    }
14386                } else {
14387                    ps.oldCodePaths = null;
14388                }
14389                if (ps.childPackageNames != null) {
14390                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14391                        final String childPkgName = ps.childPackageNames.get(i);
14392                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14393                        childPs.oldCodePaths = ps.oldCodePaths;
14394                    }
14395                }
14396                prepareAppDataAfterInstallLIF(newPackage);
14397                addedPkg = true;
14398            } catch (PackageManagerException e) {
14399                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14400            }
14401        }
14402
14403        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14404            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14405
14406            // Revert all internal state mutations and added folders for the failed install
14407            if (addedPkg) {
14408                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14409                        res.removedInfo, true, null);
14410            }
14411
14412            // Restore the old package
14413            if (deletedPkg) {
14414                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14415                File restoreFile = new File(deletedPackage.codePath);
14416                // Parse old package
14417                boolean oldExternal = isExternal(deletedPackage);
14418                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14419                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14420                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14421                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14422                try {
14423                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14424                            null);
14425                } catch (PackageManagerException e) {
14426                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14427                            + e.getMessage());
14428                    return;
14429                }
14430
14431                synchronized (mPackages) {
14432                    // Ensure the installer package name up to date
14433                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14434
14435                    // Update permissions for restored package
14436                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14437
14438                    mSettings.writeLPr();
14439                }
14440
14441                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14442            }
14443        } else {
14444            synchronized (mPackages) {
14445                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14446                if (ps != null) {
14447                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14448                    if (res.removedInfo.removedChildPackages != null) {
14449                        final int childCount = res.removedInfo.removedChildPackages.size();
14450                        // Iterate in reverse as we may modify the collection
14451                        for (int i = childCount - 1; i >= 0; i--) {
14452                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14453                            if (res.addedChildPackages.containsKey(childPackageName)) {
14454                                res.removedInfo.removedChildPackages.removeAt(i);
14455                            } else {
14456                                PackageRemovedInfo childInfo = res.removedInfo
14457                                        .removedChildPackages.valueAt(i);
14458                                childInfo.removedForAllUsers = mPackages.get(
14459                                        childInfo.removedPackage) == null;
14460                            }
14461                        }
14462                    }
14463                }
14464            }
14465        }
14466    }
14467
14468    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14469            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14470            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14471        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14472                + ", old=" + deletedPackage);
14473
14474        final boolean disabledSystem;
14475
14476        // Remove existing system package
14477        removePackageLI(deletedPackage, true);
14478
14479        synchronized (mPackages) {
14480            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14481        }
14482        if (!disabledSystem) {
14483            // We didn't need to disable the .apk as a current system package,
14484            // which means we are replacing another update that is already
14485            // installed.  We need to make sure to delete the older one's .apk.
14486            res.removedInfo.args = createInstallArgsForExisting(0,
14487                    deletedPackage.applicationInfo.getCodePath(),
14488                    deletedPackage.applicationInfo.getResourcePath(),
14489                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14490        } else {
14491            res.removedInfo.args = null;
14492        }
14493
14494        // Successfully disabled the old package. Now proceed with re-installation
14495        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14496                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14497        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14498
14499        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14500        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14501                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14502
14503        PackageParser.Package newPackage = null;
14504        try {
14505            // Add the package to the internal data structures
14506            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14507
14508            // Set the update and install times
14509            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14510            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14511                    System.currentTimeMillis());
14512
14513            // Update the package dynamic state if succeeded
14514            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14515                // Now that the install succeeded make sure we remove data
14516                // directories for any child package the update removed.
14517                final int deletedChildCount = (deletedPackage.childPackages != null)
14518                        ? deletedPackage.childPackages.size() : 0;
14519                final int newChildCount = (newPackage.childPackages != null)
14520                        ? newPackage.childPackages.size() : 0;
14521                for (int i = 0; i < deletedChildCount; i++) {
14522                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14523                    boolean childPackageDeleted = true;
14524                    for (int j = 0; j < newChildCount; j++) {
14525                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14526                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14527                            childPackageDeleted = false;
14528                            break;
14529                        }
14530                    }
14531                    if (childPackageDeleted) {
14532                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14533                                deletedChildPkg.packageName);
14534                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14535                            PackageRemovedInfo removedChildRes = res.removedInfo
14536                                    .removedChildPackages.get(deletedChildPkg.packageName);
14537                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14538                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14539                        }
14540                    }
14541                }
14542
14543                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14544                prepareAppDataAfterInstallLIF(newPackage);
14545            }
14546        } catch (PackageManagerException e) {
14547            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14548            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14549        }
14550
14551        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14552            // Re installation failed. Restore old information
14553            // Remove new pkg information
14554            if (newPackage != null) {
14555                removeInstalledPackageLI(newPackage, true);
14556            }
14557            // Add back the old system package
14558            try {
14559                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14560            } catch (PackageManagerException e) {
14561                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14562            }
14563
14564            synchronized (mPackages) {
14565                if (disabledSystem) {
14566                    enableSystemPackageLPw(deletedPackage);
14567                }
14568
14569                // Ensure the installer package name up to date
14570                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14571
14572                // Update permissions for restored package
14573                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14574
14575                mSettings.writeLPr();
14576            }
14577
14578            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14579                    + " after failed upgrade");
14580        }
14581    }
14582
14583    /**
14584     * Checks whether the parent or any of the child packages have a change shared
14585     * user. For a package to be a valid update the shred users of the parent and
14586     * the children should match. We may later support changing child shared users.
14587     * @param oldPkg The updated package.
14588     * @param newPkg The update package.
14589     * @return The shared user that change between the versions.
14590     */
14591    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14592            PackageParser.Package newPkg) {
14593        // Check parent shared user
14594        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14595            return newPkg.packageName;
14596        }
14597        // Check child shared users
14598        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14599        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14600        for (int i = 0; i < newChildCount; i++) {
14601            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14602            // If this child was present, did it have the same shared user?
14603            for (int j = 0; j < oldChildCount; j++) {
14604                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14605                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14606                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14607                    return newChildPkg.packageName;
14608                }
14609            }
14610        }
14611        return null;
14612    }
14613
14614    private void removeNativeBinariesLI(PackageSetting ps) {
14615        // Remove the lib path for the parent package
14616        if (ps != null) {
14617            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14618            // Remove the lib path for the child packages
14619            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14620            for (int i = 0; i < childCount; i++) {
14621                PackageSetting childPs = null;
14622                synchronized (mPackages) {
14623                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14624                }
14625                if (childPs != null) {
14626                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14627                            .legacyNativeLibraryPathString);
14628                }
14629            }
14630        }
14631    }
14632
14633    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14634        // Enable the parent package
14635        mSettings.enableSystemPackageLPw(pkg.packageName);
14636        // Enable the child packages
14637        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14638        for (int i = 0; i < childCount; i++) {
14639            PackageParser.Package childPkg = pkg.childPackages.get(i);
14640            mSettings.enableSystemPackageLPw(childPkg.packageName);
14641        }
14642    }
14643
14644    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14645            PackageParser.Package newPkg) {
14646        // Disable the parent package (parent always replaced)
14647        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14648        // Disable the child packages
14649        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14650        for (int i = 0; i < childCount; i++) {
14651            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14652            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14653            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14654        }
14655        return disabled;
14656    }
14657
14658    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14659            String installerPackageName) {
14660        // Enable the parent package
14661        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14662        // Enable the child packages
14663        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14664        for (int i = 0; i < childCount; i++) {
14665            PackageParser.Package childPkg = pkg.childPackages.get(i);
14666            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14667        }
14668    }
14669
14670    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14671        // Collect all used permissions in the UID
14672        ArraySet<String> usedPermissions = new ArraySet<>();
14673        final int packageCount = su.packages.size();
14674        for (int i = 0; i < packageCount; i++) {
14675            PackageSetting ps = su.packages.valueAt(i);
14676            if (ps.pkg == null) {
14677                continue;
14678            }
14679            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14680            for (int j = 0; j < requestedPermCount; j++) {
14681                String permission = ps.pkg.requestedPermissions.get(j);
14682                BasePermission bp = mSettings.mPermissions.get(permission);
14683                if (bp != null) {
14684                    usedPermissions.add(permission);
14685                }
14686            }
14687        }
14688
14689        PermissionsState permissionsState = su.getPermissionsState();
14690        // Prune install permissions
14691        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14692        final int installPermCount = installPermStates.size();
14693        for (int i = installPermCount - 1; i >= 0;  i--) {
14694            PermissionState permissionState = installPermStates.get(i);
14695            if (!usedPermissions.contains(permissionState.getName())) {
14696                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14697                if (bp != null) {
14698                    permissionsState.revokeInstallPermission(bp);
14699                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14700                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14701                }
14702            }
14703        }
14704
14705        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14706
14707        // Prune runtime permissions
14708        for (int userId : allUserIds) {
14709            List<PermissionState> runtimePermStates = permissionsState
14710                    .getRuntimePermissionStates(userId);
14711            final int runtimePermCount = runtimePermStates.size();
14712            for (int i = runtimePermCount - 1; i >= 0; i--) {
14713                PermissionState permissionState = runtimePermStates.get(i);
14714                if (!usedPermissions.contains(permissionState.getName())) {
14715                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14716                    if (bp != null) {
14717                        permissionsState.revokeRuntimePermission(bp, userId);
14718                        permissionsState.updatePermissionFlags(bp, userId,
14719                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14720                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14721                                runtimePermissionChangedUserIds, userId);
14722                    }
14723                }
14724            }
14725        }
14726
14727        return runtimePermissionChangedUserIds;
14728    }
14729
14730    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14731            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14732        // Update the parent package setting
14733        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14734                res, user);
14735        // Update the child packages setting
14736        final int childCount = (newPackage.childPackages != null)
14737                ? newPackage.childPackages.size() : 0;
14738        for (int i = 0; i < childCount; i++) {
14739            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14740            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14741            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14742                    childRes.origUsers, childRes, user);
14743        }
14744    }
14745
14746    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14747            String installerPackageName, int[] allUsers, int[] installedForUsers,
14748            PackageInstalledInfo res, UserHandle user) {
14749        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14750
14751        String pkgName = newPackage.packageName;
14752        synchronized (mPackages) {
14753            //write settings. the installStatus will be incomplete at this stage.
14754            //note that the new package setting would have already been
14755            //added to mPackages. It hasn't been persisted yet.
14756            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14758            mSettings.writeLPr();
14759            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14760        }
14761
14762        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14763        synchronized (mPackages) {
14764            updatePermissionsLPw(newPackage.packageName, newPackage,
14765                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14766                            ? UPDATE_PERMISSIONS_ALL : 0));
14767            // For system-bundled packages, we assume that installing an upgraded version
14768            // of the package implies that the user actually wants to run that new code,
14769            // so we enable the package.
14770            PackageSetting ps = mSettings.mPackages.get(pkgName);
14771            final int userId = user.getIdentifier();
14772            if (ps != null) {
14773                if (isSystemApp(newPackage)) {
14774                    if (DEBUG_INSTALL) {
14775                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14776                    }
14777                    // Enable system package for requested users
14778                    if (res.origUsers != null) {
14779                        for (int origUserId : res.origUsers) {
14780                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14781                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14782                                        origUserId, installerPackageName);
14783                            }
14784                        }
14785                    }
14786                    // Also convey the prior install/uninstall state
14787                    if (allUsers != null && installedForUsers != null) {
14788                        for (int currentUserId : allUsers) {
14789                            final boolean installed = ArrayUtils.contains(
14790                                    installedForUsers, currentUserId);
14791                            if (DEBUG_INSTALL) {
14792                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14793                            }
14794                            ps.setInstalled(installed, currentUserId);
14795                        }
14796                        // these install state changes will be persisted in the
14797                        // upcoming call to mSettings.writeLPr().
14798                    }
14799                }
14800                // It's implied that when a user requests installation, they want the app to be
14801                // installed and enabled.
14802                if (userId != UserHandle.USER_ALL) {
14803                    ps.setInstalled(true, userId);
14804                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14805                }
14806            }
14807            res.name = pkgName;
14808            res.uid = newPackage.applicationInfo.uid;
14809            res.pkg = newPackage;
14810            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14811            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14812            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14813            //to update install status
14814            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14815            mSettings.writeLPr();
14816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14817        }
14818
14819        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14820    }
14821
14822    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14823        try {
14824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14825            installPackageLI(args, res);
14826        } finally {
14827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14828        }
14829    }
14830
14831    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14832        final int installFlags = args.installFlags;
14833        final String installerPackageName = args.installerPackageName;
14834        final String volumeUuid = args.volumeUuid;
14835        final File tmpPackageFile = new File(args.getCodePath());
14836        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14837        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14838                || (args.volumeUuid != null));
14839        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14840        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14841        boolean replace = false;
14842        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14843        if (args.move != null) {
14844            // moving a complete application; perform an initial scan on the new install location
14845            scanFlags |= SCAN_INITIAL;
14846        }
14847        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14848            scanFlags |= SCAN_DONT_KILL_APP;
14849        }
14850
14851        // Result object to be returned
14852        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14853
14854        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14855
14856        // Sanity check
14857        if (ephemeral && (forwardLocked || onExternal)) {
14858            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14859                    + " external=" + onExternal);
14860            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14861            return;
14862        }
14863
14864        // Retrieve PackageSettings and parse package
14865        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14866                | PackageParser.PARSE_ENFORCE_CODE
14867                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14868                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14869                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14870                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14871        PackageParser pp = new PackageParser();
14872        pp.setSeparateProcesses(mSeparateProcesses);
14873        pp.setDisplayMetrics(mMetrics);
14874
14875        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14876        final PackageParser.Package pkg;
14877        try {
14878            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14879        } catch (PackageParserException e) {
14880            res.setError("Failed parse during installPackageLI", e);
14881            return;
14882        } finally {
14883            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14884        }
14885
14886        // If we are installing a clustered package add results for the children
14887        if (pkg.childPackages != null) {
14888            synchronized (mPackages) {
14889                final int childCount = pkg.childPackages.size();
14890                for (int i = 0; i < childCount; i++) {
14891                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14892                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14893                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14894                    childRes.pkg = childPkg;
14895                    childRes.name = childPkg.packageName;
14896                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14897                    if (childPs != null) {
14898                        childRes.origUsers = childPs.queryInstalledUsers(
14899                                sUserManager.getUserIds(), true);
14900                    }
14901                    if ((mPackages.containsKey(childPkg.packageName))) {
14902                        childRes.removedInfo = new PackageRemovedInfo();
14903                        childRes.removedInfo.removedPackage = childPkg.packageName;
14904                    }
14905                    if (res.addedChildPackages == null) {
14906                        res.addedChildPackages = new ArrayMap<>();
14907                    }
14908                    res.addedChildPackages.put(childPkg.packageName, childRes);
14909                }
14910            }
14911        }
14912
14913        // If package doesn't declare API override, mark that we have an install
14914        // time CPU ABI override.
14915        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14916            pkg.cpuAbiOverride = args.abiOverride;
14917        }
14918
14919        String pkgName = res.name = pkg.packageName;
14920        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14921            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14922                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14923                return;
14924            }
14925        }
14926
14927        try {
14928            // either use what we've been given or parse directly from the APK
14929            if (args.certificates != null) {
14930                try {
14931                    PackageParser.populateCertificates(pkg, args.certificates);
14932                } catch (PackageParserException e) {
14933                    // there was something wrong with the certificates we were given;
14934                    // try to pull them from the APK
14935                    PackageParser.collectCertificates(pkg, parseFlags);
14936                }
14937            } else {
14938                PackageParser.collectCertificates(pkg, parseFlags);
14939            }
14940        } catch (PackageParserException e) {
14941            res.setError("Failed collect during installPackageLI", e);
14942            return;
14943        }
14944
14945        // Get rid of all references to package scan path via parser.
14946        pp = null;
14947        String oldCodePath = null;
14948        boolean systemApp = false;
14949        synchronized (mPackages) {
14950            // Check if installing already existing package
14951            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14952                String oldName = mSettings.mRenamedPackages.get(pkgName);
14953                if (pkg.mOriginalPackages != null
14954                        && pkg.mOriginalPackages.contains(oldName)
14955                        && mPackages.containsKey(oldName)) {
14956                    // This package is derived from an original package,
14957                    // and this device has been updating from that original
14958                    // name.  We must continue using the original name, so
14959                    // rename the new package here.
14960                    pkg.setPackageName(oldName);
14961                    pkgName = pkg.packageName;
14962                    replace = true;
14963                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14964                            + oldName + " pkgName=" + pkgName);
14965                } else if (mPackages.containsKey(pkgName)) {
14966                    // This package, under its official name, already exists
14967                    // on the device; we should replace it.
14968                    replace = true;
14969                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14970                }
14971
14972                // Child packages are installed through the parent package
14973                if (pkg.parentPackage != null) {
14974                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14975                            "Package " + pkg.packageName + " is child of package "
14976                                    + pkg.parentPackage.parentPackage + ". Child packages "
14977                                    + "can be updated only through the parent package.");
14978                    return;
14979                }
14980
14981                if (replace) {
14982                    // Prevent apps opting out from runtime permissions
14983                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14984                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14985                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14986                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14987                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14988                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14989                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14990                                        + " doesn't support runtime permissions but the old"
14991                                        + " target SDK " + oldTargetSdk + " does.");
14992                        return;
14993                    }
14994
14995                    // Prevent installing of child packages
14996                    if (oldPackage.parentPackage != null) {
14997                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14998                                "Package " + pkg.packageName + " is child of package "
14999                                        + oldPackage.parentPackage + ". Child packages "
15000                                        + "can be updated only through the parent package.");
15001                        return;
15002                    }
15003                }
15004            }
15005
15006            PackageSetting ps = mSettings.mPackages.get(pkgName);
15007            if (ps != null) {
15008                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15009
15010                // Quick sanity check that we're signed correctly if updating;
15011                // we'll check this again later when scanning, but we want to
15012                // bail early here before tripping over redefined permissions.
15013                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15014                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15015                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15016                                + pkg.packageName + " upgrade keys do not match the "
15017                                + "previously installed version");
15018                        return;
15019                    }
15020                } else {
15021                    try {
15022                        verifySignaturesLP(ps, pkg);
15023                    } catch (PackageManagerException e) {
15024                        res.setError(e.error, e.getMessage());
15025                        return;
15026                    }
15027                }
15028
15029                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15030                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15031                    systemApp = (ps.pkg.applicationInfo.flags &
15032                            ApplicationInfo.FLAG_SYSTEM) != 0;
15033                }
15034                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15035            }
15036
15037            // Check whether the newly-scanned package wants to define an already-defined perm
15038            int N = pkg.permissions.size();
15039            for (int i = N-1; i >= 0; i--) {
15040                PackageParser.Permission perm = pkg.permissions.get(i);
15041                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15042                if (bp != null) {
15043                    // If the defining package is signed with our cert, it's okay.  This
15044                    // also includes the "updating the same package" case, of course.
15045                    // "updating same package" could also involve key-rotation.
15046                    final boolean sigsOk;
15047                    if (bp.sourcePackage.equals(pkg.packageName)
15048                            && (bp.packageSetting instanceof PackageSetting)
15049                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15050                                    scanFlags))) {
15051                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15052                    } else {
15053                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15054                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15055                    }
15056                    if (!sigsOk) {
15057                        // If the owning package is the system itself, we log but allow
15058                        // install to proceed; we fail the install on all other permission
15059                        // redefinitions.
15060                        if (!bp.sourcePackage.equals("android")) {
15061                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15062                                    + pkg.packageName + " attempting to redeclare permission "
15063                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15064                            res.origPermission = perm.info.name;
15065                            res.origPackage = bp.sourcePackage;
15066                            return;
15067                        } else {
15068                            Slog.w(TAG, "Package " + pkg.packageName
15069                                    + " attempting to redeclare system permission "
15070                                    + perm.info.name + "; ignoring new declaration");
15071                            pkg.permissions.remove(i);
15072                        }
15073                    }
15074                }
15075            }
15076        }
15077
15078        if (systemApp) {
15079            if (onExternal) {
15080                // Abort update; system app can't be replaced with app on sdcard
15081                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15082                        "Cannot install updates to system apps on sdcard");
15083                return;
15084            } else if (ephemeral) {
15085                // Abort update; system app can't be replaced with an ephemeral app
15086                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15087                        "Cannot update a system app with an ephemeral app");
15088                return;
15089            }
15090        }
15091
15092        if (args.move != null) {
15093            // We did an in-place move, so dex is ready to roll
15094            scanFlags |= SCAN_NO_DEX;
15095            scanFlags |= SCAN_MOVE;
15096
15097            synchronized (mPackages) {
15098                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15099                if (ps == null) {
15100                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15101                            "Missing settings for moved package " + pkgName);
15102                }
15103
15104                // We moved the entire application as-is, so bring over the
15105                // previously derived ABI information.
15106                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15107                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15108            }
15109
15110        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15111            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15112            scanFlags |= SCAN_NO_DEX;
15113
15114            try {
15115                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15116                    args.abiOverride : pkg.cpuAbiOverride);
15117                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15118                        true /* extract libs */);
15119            } catch (PackageManagerException pme) {
15120                Slog.e(TAG, "Error deriving application ABI", pme);
15121                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15122                return;
15123            }
15124
15125            // Shared libraries for the package need to be updated.
15126            synchronized (mPackages) {
15127                try {
15128                    updateSharedLibrariesLPw(pkg, null);
15129                } catch (PackageManagerException e) {
15130                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15131                }
15132            }
15133            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15134            // Do not run PackageDexOptimizer through the local performDexOpt
15135            // method because `pkg` may not be in `mPackages` yet.
15136            //
15137            // Also, don't fail application installs if the dexopt step fails.
15138            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15139                    null /* instructionSets */, false /* checkProfiles */,
15140                    getCompilerFilterForReason(REASON_INSTALL));
15141            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15142
15143            // Notify BackgroundDexOptService that the package has been changed.
15144            // If this is an update of a package which used to fail to compile,
15145            // BDOS will remove it from its blacklist.
15146            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15147        }
15148
15149        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15150            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15151            return;
15152        }
15153
15154        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15155
15156        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15157                "installPackageLI")) {
15158            if (replace) {
15159                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15160                        installerPackageName, res);
15161            } else {
15162                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15163                        args.user, installerPackageName, volumeUuid, res);
15164            }
15165        }
15166        synchronized (mPackages) {
15167            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15168            if (ps != null) {
15169                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15170            }
15171
15172            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15173            for (int i = 0; i < childCount; i++) {
15174                PackageParser.Package childPkg = pkg.childPackages.get(i);
15175                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15176                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15177                if (childPs != null) {
15178                    childRes.newUsers = childPs.queryInstalledUsers(
15179                            sUserManager.getUserIds(), true);
15180                }
15181            }
15182        }
15183    }
15184
15185    private void startIntentFilterVerifications(int userId, boolean replacing,
15186            PackageParser.Package pkg) {
15187        if (mIntentFilterVerifierComponent == null) {
15188            Slog.w(TAG, "No IntentFilter verification will not be done as "
15189                    + "there is no IntentFilterVerifier available!");
15190            return;
15191        }
15192
15193        final int verifierUid = getPackageUid(
15194                mIntentFilterVerifierComponent.getPackageName(),
15195                MATCH_DEBUG_TRIAGED_MISSING,
15196                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15197
15198        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15199        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15200        mHandler.sendMessage(msg);
15201
15202        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15203        for (int i = 0; i < childCount; i++) {
15204            PackageParser.Package childPkg = pkg.childPackages.get(i);
15205            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15206            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15207            mHandler.sendMessage(msg);
15208        }
15209    }
15210
15211    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15212            PackageParser.Package pkg) {
15213        int size = pkg.activities.size();
15214        if (size == 0) {
15215            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15216                    "No activity, so no need to verify any IntentFilter!");
15217            return;
15218        }
15219
15220        final boolean hasDomainURLs = hasDomainURLs(pkg);
15221        if (!hasDomainURLs) {
15222            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15223                    "No domain URLs, so no need to verify any IntentFilter!");
15224            return;
15225        }
15226
15227        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15228                + " if any IntentFilter from the " + size
15229                + " Activities needs verification ...");
15230
15231        int count = 0;
15232        final String packageName = pkg.packageName;
15233
15234        synchronized (mPackages) {
15235            // If this is a new install and we see that we've already run verification for this
15236            // package, we have nothing to do: it means the state was restored from backup.
15237            if (!replacing) {
15238                IntentFilterVerificationInfo ivi =
15239                        mSettings.getIntentFilterVerificationLPr(packageName);
15240                if (ivi != null) {
15241                    if (DEBUG_DOMAIN_VERIFICATION) {
15242                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15243                                + ivi.getStatusString());
15244                    }
15245                    return;
15246                }
15247            }
15248
15249            // If any filters need to be verified, then all need to be.
15250            boolean needToVerify = false;
15251            for (PackageParser.Activity a : pkg.activities) {
15252                for (ActivityIntentInfo filter : a.intents) {
15253                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15254                        if (DEBUG_DOMAIN_VERIFICATION) {
15255                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15256                        }
15257                        needToVerify = true;
15258                        break;
15259                    }
15260                }
15261            }
15262
15263            if (needToVerify) {
15264                final int verificationId = mIntentFilterVerificationToken++;
15265                for (PackageParser.Activity a : pkg.activities) {
15266                    for (ActivityIntentInfo filter : a.intents) {
15267                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15268                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15269                                    "Verification needed for IntentFilter:" + filter.toString());
15270                            mIntentFilterVerifier.addOneIntentFilterVerification(
15271                                    verifierUid, userId, verificationId, filter, packageName);
15272                            count++;
15273                        }
15274                    }
15275                }
15276            }
15277        }
15278
15279        if (count > 0) {
15280            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15281                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15282                    +  " for userId:" + userId);
15283            mIntentFilterVerifier.startVerifications(userId);
15284        } else {
15285            if (DEBUG_DOMAIN_VERIFICATION) {
15286                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15287            }
15288        }
15289    }
15290
15291    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15292        final ComponentName cn  = filter.activity.getComponentName();
15293        final String packageName = cn.getPackageName();
15294
15295        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15296                packageName);
15297        if (ivi == null) {
15298            return true;
15299        }
15300        int status = ivi.getStatus();
15301        switch (status) {
15302            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15303            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15304                return true;
15305
15306            default:
15307                // Nothing to do
15308                return false;
15309        }
15310    }
15311
15312    private static boolean isMultiArch(ApplicationInfo info) {
15313        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15314    }
15315
15316    private static boolean isExternal(PackageParser.Package pkg) {
15317        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15318    }
15319
15320    private static boolean isExternal(PackageSetting ps) {
15321        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15322    }
15323
15324    private static boolean isEphemeral(PackageParser.Package pkg) {
15325        return pkg.applicationInfo.isEphemeralApp();
15326    }
15327
15328    private static boolean isEphemeral(PackageSetting ps) {
15329        return ps.pkg != null && isEphemeral(ps.pkg);
15330    }
15331
15332    private static boolean isSystemApp(PackageParser.Package pkg) {
15333        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15334    }
15335
15336    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15337        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15338    }
15339
15340    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15341        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15342    }
15343
15344    private static boolean isSystemApp(PackageSetting ps) {
15345        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15346    }
15347
15348    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15349        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15350    }
15351
15352    private int packageFlagsToInstallFlags(PackageSetting ps) {
15353        int installFlags = 0;
15354        if (isEphemeral(ps)) {
15355            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15356        }
15357        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15358            // This existing package was an external ASEC install when we have
15359            // the external flag without a UUID
15360            installFlags |= PackageManager.INSTALL_EXTERNAL;
15361        }
15362        if (ps.isForwardLocked()) {
15363            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15364        }
15365        return installFlags;
15366    }
15367
15368    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15369        if (isExternal(pkg)) {
15370            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15371                return StorageManager.UUID_PRIMARY_PHYSICAL;
15372            } else {
15373                return pkg.volumeUuid;
15374            }
15375        } else {
15376            return StorageManager.UUID_PRIVATE_INTERNAL;
15377        }
15378    }
15379
15380    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15381        if (isExternal(pkg)) {
15382            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15383                return mSettings.getExternalVersion();
15384            } else {
15385                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15386            }
15387        } else {
15388            return mSettings.getInternalVersion();
15389        }
15390    }
15391
15392    private void deleteTempPackageFiles() {
15393        final FilenameFilter filter = new FilenameFilter() {
15394            public boolean accept(File dir, String name) {
15395                return name.startsWith("vmdl") && name.endsWith(".tmp");
15396            }
15397        };
15398        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15399            file.delete();
15400        }
15401    }
15402
15403    @Override
15404    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15405            int flags) {
15406        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15407                flags);
15408    }
15409
15410    @Override
15411    public void deletePackage(final String packageName,
15412            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15413        mContext.enforceCallingOrSelfPermission(
15414                android.Manifest.permission.DELETE_PACKAGES, null);
15415        Preconditions.checkNotNull(packageName);
15416        Preconditions.checkNotNull(observer);
15417        final int uid = Binder.getCallingUid();
15418        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15419        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15420        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15421            mContext.enforceCallingOrSelfPermission(
15422                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15423                    "deletePackage for user " + userId);
15424        }
15425
15426        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15427            try {
15428                observer.onPackageDeleted(packageName,
15429                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15430            } catch (RemoteException re) {
15431            }
15432            return;
15433        }
15434
15435        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15436            try {
15437                observer.onPackageDeleted(packageName,
15438                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15439            } catch (RemoteException re) {
15440            }
15441            return;
15442        }
15443
15444        if (DEBUG_REMOVE) {
15445            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15446                    + " deleteAllUsers: " + deleteAllUsers );
15447        }
15448        // Queue up an async operation since the package deletion may take a little while.
15449        mHandler.post(new Runnable() {
15450            public void run() {
15451                mHandler.removeCallbacks(this);
15452                int returnCode;
15453                if (!deleteAllUsers) {
15454                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15455                } else {
15456                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15457                    // If nobody is blocking uninstall, proceed with delete for all users
15458                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15459                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15460                    } else {
15461                        // Otherwise uninstall individually for users with blockUninstalls=false
15462                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15463                        for (int userId : users) {
15464                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15465                                returnCode = deletePackageX(packageName, userId, userFlags);
15466                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15467                                    Slog.w(TAG, "Package delete failed for user " + userId
15468                                            + ", returnCode " + returnCode);
15469                                }
15470                            }
15471                        }
15472                        // The app has only been marked uninstalled for certain users.
15473                        // We still need to report that delete was blocked
15474                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15475                    }
15476                }
15477                try {
15478                    observer.onPackageDeleted(packageName, returnCode, null);
15479                } catch (RemoteException e) {
15480                    Log.i(TAG, "Observer no longer exists.");
15481                } //end catch
15482            } //end run
15483        });
15484    }
15485
15486    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15487        int[] result = EMPTY_INT_ARRAY;
15488        for (int userId : userIds) {
15489            if (getBlockUninstallForUser(packageName, userId)) {
15490                result = ArrayUtils.appendInt(result, userId);
15491            }
15492        }
15493        return result;
15494    }
15495
15496    @Override
15497    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15498        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15499    }
15500
15501    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15502        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15503                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15504        try {
15505            if (dpm != null) {
15506                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15507                        /* callingUserOnly =*/ false);
15508                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15509                        : deviceOwnerComponentName.getPackageName();
15510                // Does the package contains the device owner?
15511                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15512                // this check is probably not needed, since DO should be registered as a device
15513                // admin on some user too. (Original bug for this: b/17657954)
15514                if (packageName.equals(deviceOwnerPackageName)) {
15515                    return true;
15516                }
15517                // Does it contain a device admin for any user?
15518                int[] users;
15519                if (userId == UserHandle.USER_ALL) {
15520                    users = sUserManager.getUserIds();
15521                } else {
15522                    users = new int[]{userId};
15523                }
15524                for (int i = 0; i < users.length; ++i) {
15525                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15526                        return true;
15527                    }
15528                }
15529            }
15530        } catch (RemoteException e) {
15531        }
15532        return false;
15533    }
15534
15535    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15536        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15537    }
15538
15539    /**
15540     *  This method is an internal method that could be get invoked either
15541     *  to delete an installed package or to clean up a failed installation.
15542     *  After deleting an installed package, a broadcast is sent to notify any
15543     *  listeners that the package has been removed. For cleaning up a failed
15544     *  installation, the broadcast is not necessary since the package's
15545     *  installation wouldn't have sent the initial broadcast either
15546     *  The key steps in deleting a package are
15547     *  deleting the package information in internal structures like mPackages,
15548     *  deleting the packages base directories through installd
15549     *  updating mSettings to reflect current status
15550     *  persisting settings for later use
15551     *  sending a broadcast if necessary
15552     */
15553    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15554        final PackageRemovedInfo info = new PackageRemovedInfo();
15555        final boolean res;
15556
15557        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15558                ? UserHandle.ALL : new UserHandle(userId);
15559
15560        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15561            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15562            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15563        }
15564
15565        PackageSetting uninstalledPs = null;
15566
15567        // for the uninstall-updates case and restricted profiles, remember the per-
15568        // user handle installed state
15569        int[] allUsers;
15570        synchronized (mPackages) {
15571            uninstalledPs = mSettings.mPackages.get(packageName);
15572            if (uninstalledPs == null) {
15573                Slog.w(TAG, "Not removing non-existent package " + packageName);
15574                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15575            }
15576            allUsers = sUserManager.getUserIds();
15577            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15578        }
15579
15580        synchronized (mInstallLock) {
15581            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15582            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15583                    "deletePackageX")) {
15584                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15585                        deleteFlags | REMOVE_CHATTY, info, true, null);
15586            }
15587            synchronized (mPackages) {
15588                if (res) {
15589                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15590                }
15591            }
15592        }
15593
15594        if (res) {
15595            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15596            info.sendPackageRemovedBroadcasts(killApp);
15597            info.sendSystemPackageUpdatedBroadcasts();
15598            info.sendSystemPackageAppearedBroadcasts();
15599        }
15600        // Force a gc here.
15601        Runtime.getRuntime().gc();
15602        // Delete the resources here after sending the broadcast to let
15603        // other processes clean up before deleting resources.
15604        if (info.args != null) {
15605            synchronized (mInstallLock) {
15606                info.args.doPostDeleteLI(true);
15607            }
15608        }
15609
15610        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15611    }
15612
15613    class PackageRemovedInfo {
15614        String removedPackage;
15615        int uid = -1;
15616        int removedAppId = -1;
15617        int[] origUsers;
15618        int[] removedUsers = null;
15619        boolean isRemovedPackageSystemUpdate = false;
15620        boolean isUpdate;
15621        boolean dataRemoved;
15622        boolean removedForAllUsers;
15623        // Clean up resources deleted packages.
15624        InstallArgs args = null;
15625        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15626        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15627
15628        void sendPackageRemovedBroadcasts(boolean killApp) {
15629            sendPackageRemovedBroadcastInternal(killApp);
15630            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15631            for (int i = 0; i < childCount; i++) {
15632                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15633                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15634            }
15635        }
15636
15637        void sendSystemPackageUpdatedBroadcasts() {
15638            if (isRemovedPackageSystemUpdate) {
15639                sendSystemPackageUpdatedBroadcastsInternal();
15640                final int childCount = (removedChildPackages != null)
15641                        ? removedChildPackages.size() : 0;
15642                for (int i = 0; i < childCount; i++) {
15643                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15644                    if (childInfo.isRemovedPackageSystemUpdate) {
15645                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15646                    }
15647                }
15648            }
15649        }
15650
15651        void sendSystemPackageAppearedBroadcasts() {
15652            final int packageCount = (appearedChildPackages != null)
15653                    ? appearedChildPackages.size() : 0;
15654            for (int i = 0; i < packageCount; i++) {
15655                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15656                for (int userId : installedInfo.newUsers) {
15657                    sendPackageAddedForUser(installedInfo.name, true,
15658                            UserHandle.getAppId(installedInfo.uid), userId);
15659                }
15660            }
15661        }
15662
15663        private void sendSystemPackageUpdatedBroadcastsInternal() {
15664            Bundle extras = new Bundle(2);
15665            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15666            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15667            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15668                    extras, 0, null, null, null);
15669            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15670                    extras, 0, null, null, null);
15671            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15672                    null, 0, removedPackage, null, null);
15673        }
15674
15675        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15676            Bundle extras = new Bundle(2);
15677            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15678            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15679            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15680            if (isUpdate || isRemovedPackageSystemUpdate) {
15681                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15682            }
15683            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15684            if (removedPackage != null) {
15685                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15686                        extras, 0, null, null, removedUsers);
15687                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15688                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15689                            removedPackage, extras, 0, null, null, removedUsers);
15690                }
15691            }
15692            if (removedAppId >= 0) {
15693                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15694                        removedUsers);
15695            }
15696        }
15697    }
15698
15699    /*
15700     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15701     * flag is not set, the data directory is removed as well.
15702     * make sure this flag is set for partially installed apps. If not its meaningless to
15703     * delete a partially installed application.
15704     */
15705    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15706            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15707        String packageName = ps.name;
15708        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15709        // Retrieve object to delete permissions for shared user later on
15710        final PackageParser.Package deletedPkg;
15711        final PackageSetting deletedPs;
15712        // reader
15713        synchronized (mPackages) {
15714            deletedPkg = mPackages.get(packageName);
15715            deletedPs = mSettings.mPackages.get(packageName);
15716            if (outInfo != null) {
15717                outInfo.removedPackage = packageName;
15718                outInfo.removedUsers = deletedPs != null
15719                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15720                        : null;
15721            }
15722        }
15723
15724        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15725
15726        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15727            final PackageParser.Package resolvedPkg;
15728            if (deletedPkg != null) {
15729                resolvedPkg = deletedPkg;
15730            } else {
15731                // We don't have a parsed package when it lives on an ejected
15732                // adopted storage device, so fake something together
15733                resolvedPkg = new PackageParser.Package(ps.name);
15734                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15735            }
15736            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15737                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15738            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15739            if (outInfo != null) {
15740                outInfo.dataRemoved = true;
15741            }
15742            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15743        }
15744
15745        // writer
15746        synchronized (mPackages) {
15747            if (deletedPs != null) {
15748                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15749                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15750                    clearDefaultBrowserIfNeeded(packageName);
15751                    if (outInfo != null) {
15752                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15753                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15754                    }
15755                    updatePermissionsLPw(deletedPs.name, null, 0);
15756                    if (deletedPs.sharedUser != null) {
15757                        // Remove permissions associated with package. Since runtime
15758                        // permissions are per user we have to kill the removed package
15759                        // or packages running under the shared user of the removed
15760                        // package if revoking the permissions requested only by the removed
15761                        // package is successful and this causes a change in gids.
15762                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15763                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15764                                    userId);
15765                            if (userIdToKill == UserHandle.USER_ALL
15766                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15767                                // If gids changed for this user, kill all affected packages.
15768                                mHandler.post(new Runnable() {
15769                                    @Override
15770                                    public void run() {
15771                                        // This has to happen with no lock held.
15772                                        killApplication(deletedPs.name, deletedPs.appId,
15773                                                KILL_APP_REASON_GIDS_CHANGED);
15774                                    }
15775                                });
15776                                break;
15777                            }
15778                        }
15779                    }
15780                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15781                }
15782                // make sure to preserve per-user disabled state if this removal was just
15783                // a downgrade of a system app to the factory package
15784                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15785                    if (DEBUG_REMOVE) {
15786                        Slog.d(TAG, "Propagating install state across downgrade");
15787                    }
15788                    for (int userId : allUserHandles) {
15789                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15790                        if (DEBUG_REMOVE) {
15791                            Slog.d(TAG, "    user " + userId + " => " + installed);
15792                        }
15793                        ps.setInstalled(installed, userId);
15794                    }
15795                }
15796            }
15797            // can downgrade to reader
15798            if (writeSettings) {
15799                // Save settings now
15800                mSettings.writeLPr();
15801            }
15802        }
15803        if (outInfo != null) {
15804            // A user ID was deleted here. Go through all users and remove it
15805            // from KeyStore.
15806            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15807        }
15808    }
15809
15810    static boolean locationIsPrivileged(File path) {
15811        try {
15812            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15813                    .getCanonicalPath();
15814            return path.getCanonicalPath().startsWith(privilegedAppDir);
15815        } catch (IOException e) {
15816            Slog.e(TAG, "Unable to access code path " + path);
15817        }
15818        return false;
15819    }
15820
15821    /*
15822     * Tries to delete system package.
15823     */
15824    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15825            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15826            boolean writeSettings) {
15827        if (deletedPs.parentPackageName != null) {
15828            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15829            return false;
15830        }
15831
15832        final boolean applyUserRestrictions
15833                = (allUserHandles != null) && (outInfo.origUsers != null);
15834        final PackageSetting disabledPs;
15835        // Confirm if the system package has been updated
15836        // An updated system app can be deleted. This will also have to restore
15837        // the system pkg from system partition
15838        // reader
15839        synchronized (mPackages) {
15840            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15841        }
15842
15843        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15844                + " disabledPs=" + disabledPs);
15845
15846        if (disabledPs == null) {
15847            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15848            return false;
15849        } else if (DEBUG_REMOVE) {
15850            Slog.d(TAG, "Deleting system pkg from data partition");
15851        }
15852
15853        if (DEBUG_REMOVE) {
15854            if (applyUserRestrictions) {
15855                Slog.d(TAG, "Remembering install states:");
15856                for (int userId : allUserHandles) {
15857                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15858                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15859                }
15860            }
15861        }
15862
15863        // Delete the updated package
15864        outInfo.isRemovedPackageSystemUpdate = true;
15865        if (outInfo.removedChildPackages != null) {
15866            final int childCount = (deletedPs.childPackageNames != null)
15867                    ? deletedPs.childPackageNames.size() : 0;
15868            for (int i = 0; i < childCount; i++) {
15869                String childPackageName = deletedPs.childPackageNames.get(i);
15870                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15871                        .contains(childPackageName)) {
15872                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15873                            childPackageName);
15874                    if (childInfo != null) {
15875                        childInfo.isRemovedPackageSystemUpdate = true;
15876                    }
15877                }
15878            }
15879        }
15880
15881        if (disabledPs.versionCode < deletedPs.versionCode) {
15882            // Delete data for downgrades
15883            flags &= ~PackageManager.DELETE_KEEP_DATA;
15884        } else {
15885            // Preserve data by setting flag
15886            flags |= PackageManager.DELETE_KEEP_DATA;
15887        }
15888
15889        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15890                outInfo, writeSettings, disabledPs.pkg);
15891        if (!ret) {
15892            return false;
15893        }
15894
15895        // writer
15896        synchronized (mPackages) {
15897            // Reinstate the old system package
15898            enableSystemPackageLPw(disabledPs.pkg);
15899            // Remove any native libraries from the upgraded package.
15900            removeNativeBinariesLI(deletedPs);
15901        }
15902
15903        // Install the system package
15904        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15905        int parseFlags = mDefParseFlags
15906                | PackageParser.PARSE_MUST_BE_APK
15907                | PackageParser.PARSE_IS_SYSTEM
15908                | PackageParser.PARSE_IS_SYSTEM_DIR;
15909        if (locationIsPrivileged(disabledPs.codePath)) {
15910            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15911        }
15912
15913        final PackageParser.Package newPkg;
15914        try {
15915            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15916        } catch (PackageManagerException e) {
15917            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15918                    + e.getMessage());
15919            return false;
15920        }
15921
15922        prepareAppDataAfterInstallLIF(newPkg);
15923
15924        // writer
15925        synchronized (mPackages) {
15926            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15927
15928            // Propagate the permissions state as we do not want to drop on the floor
15929            // runtime permissions. The update permissions method below will take
15930            // care of removing obsolete permissions and grant install permissions.
15931            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15932            updatePermissionsLPw(newPkg.packageName, newPkg,
15933                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15934
15935            if (applyUserRestrictions) {
15936                if (DEBUG_REMOVE) {
15937                    Slog.d(TAG, "Propagating install state across reinstall");
15938                }
15939                for (int userId : allUserHandles) {
15940                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15941                    if (DEBUG_REMOVE) {
15942                        Slog.d(TAG, "    user " + userId + " => " + installed);
15943                    }
15944                    ps.setInstalled(installed, userId);
15945
15946                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15947                }
15948                // Regardless of writeSettings we need to ensure that this restriction
15949                // state propagation is persisted
15950                mSettings.writeAllUsersPackageRestrictionsLPr();
15951            }
15952            // can downgrade to reader here
15953            if (writeSettings) {
15954                mSettings.writeLPr();
15955            }
15956        }
15957        return true;
15958    }
15959
15960    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15961            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15962            PackageRemovedInfo outInfo, boolean writeSettings,
15963            PackageParser.Package replacingPackage) {
15964        synchronized (mPackages) {
15965            if (outInfo != null) {
15966                outInfo.uid = ps.appId;
15967            }
15968
15969            if (outInfo != null && outInfo.removedChildPackages != null) {
15970                final int childCount = (ps.childPackageNames != null)
15971                        ? ps.childPackageNames.size() : 0;
15972                for (int i = 0; i < childCount; i++) {
15973                    String childPackageName = ps.childPackageNames.get(i);
15974                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15975                    if (childPs == null) {
15976                        return false;
15977                    }
15978                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15979                            childPackageName);
15980                    if (childInfo != null) {
15981                        childInfo.uid = childPs.appId;
15982                    }
15983                }
15984            }
15985        }
15986
15987        // Delete package data from internal structures and also remove data if flag is set
15988        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15989
15990        // Delete the child packages data
15991        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15992        for (int i = 0; i < childCount; i++) {
15993            PackageSetting childPs;
15994            synchronized (mPackages) {
15995                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15996            }
15997            if (childPs != null) {
15998                PackageRemovedInfo childOutInfo = (outInfo != null
15999                        && outInfo.removedChildPackages != null)
16000                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16001                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16002                        && (replacingPackage != null
16003                        && !replacingPackage.hasChildPackage(childPs.name))
16004                        ? flags & ~DELETE_KEEP_DATA : flags;
16005                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16006                        deleteFlags, writeSettings);
16007            }
16008        }
16009
16010        // Delete application code and resources only for parent packages
16011        if (ps.parentPackageName == null) {
16012            if (deleteCodeAndResources && (outInfo != null)) {
16013                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16014                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16015                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16016            }
16017        }
16018
16019        return true;
16020    }
16021
16022    @Override
16023    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16024            int userId) {
16025        mContext.enforceCallingOrSelfPermission(
16026                android.Manifest.permission.DELETE_PACKAGES, null);
16027        synchronized (mPackages) {
16028            PackageSetting ps = mSettings.mPackages.get(packageName);
16029            if (ps == null) {
16030                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16031                return false;
16032            }
16033            if (!ps.getInstalled(userId)) {
16034                // Can't block uninstall for an app that is not installed or enabled.
16035                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16036                return false;
16037            }
16038            ps.setBlockUninstall(blockUninstall, userId);
16039            mSettings.writePackageRestrictionsLPr(userId);
16040        }
16041        return true;
16042    }
16043
16044    @Override
16045    public boolean getBlockUninstallForUser(String packageName, int userId) {
16046        synchronized (mPackages) {
16047            PackageSetting ps = mSettings.mPackages.get(packageName);
16048            if (ps == null) {
16049                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16050                return false;
16051            }
16052            return ps.getBlockUninstall(userId);
16053        }
16054    }
16055
16056    @Override
16057    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16058        int callingUid = Binder.getCallingUid();
16059        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16060            throw new SecurityException(
16061                    "setRequiredForSystemUser can only be run by the system or root");
16062        }
16063        synchronized (mPackages) {
16064            PackageSetting ps = mSettings.mPackages.get(packageName);
16065            if (ps == null) {
16066                Log.w(TAG, "Package doesn't exist: " + packageName);
16067                return false;
16068            }
16069            if (systemUserApp) {
16070                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16071            } else {
16072                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16073            }
16074            mSettings.writeLPr();
16075        }
16076        return true;
16077    }
16078
16079    /*
16080     * This method handles package deletion in general
16081     */
16082    private boolean deletePackageLIF(String packageName, UserHandle user,
16083            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16084            PackageRemovedInfo outInfo, boolean writeSettings,
16085            PackageParser.Package replacingPackage) {
16086        if (packageName == null) {
16087            Slog.w(TAG, "Attempt to delete null packageName.");
16088            return false;
16089        }
16090
16091        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16092
16093        PackageSetting ps;
16094
16095        synchronized (mPackages) {
16096            ps = mSettings.mPackages.get(packageName);
16097            if (ps == null) {
16098                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16099                return false;
16100            }
16101
16102            if (ps.parentPackageName != null && (!isSystemApp(ps)
16103                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16104                if (DEBUG_REMOVE) {
16105                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16106                            + ((user == null) ? UserHandle.USER_ALL : user));
16107                }
16108                final int removedUserId = (user != null) ? user.getIdentifier()
16109                        : UserHandle.USER_ALL;
16110                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16111                    return false;
16112                }
16113                markPackageUninstalledForUserLPw(ps, user);
16114                scheduleWritePackageRestrictionsLocked(user);
16115                return true;
16116            }
16117        }
16118
16119        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16120                && user.getIdentifier() != UserHandle.USER_ALL)) {
16121            // The caller is asking that the package only be deleted for a single
16122            // user.  To do this, we just mark its uninstalled state and delete
16123            // its data. If this is a system app, we only allow this to happen if
16124            // they have set the special DELETE_SYSTEM_APP which requests different
16125            // semantics than normal for uninstalling system apps.
16126            markPackageUninstalledForUserLPw(ps, user);
16127
16128            if (!isSystemApp(ps)) {
16129                // Do not uninstall the APK if an app should be cached
16130                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16131                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16132                    // Other user still have this package installed, so all
16133                    // we need to do is clear this user's data and save that
16134                    // it is uninstalled.
16135                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16136                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16137                        return false;
16138                    }
16139                    scheduleWritePackageRestrictionsLocked(user);
16140                    return true;
16141                } else {
16142                    // We need to set it back to 'installed' so the uninstall
16143                    // broadcasts will be sent correctly.
16144                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16145                    ps.setInstalled(true, user.getIdentifier());
16146                }
16147            } else {
16148                // This is a system app, so we assume that the
16149                // other users still have this package installed, so all
16150                // we need to do is clear this user's data and save that
16151                // it is uninstalled.
16152                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16153                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16154                    return false;
16155                }
16156                scheduleWritePackageRestrictionsLocked(user);
16157                return true;
16158            }
16159        }
16160
16161        // If we are deleting a composite package for all users, keep track
16162        // of result for each child.
16163        if (ps.childPackageNames != null && outInfo != null) {
16164            synchronized (mPackages) {
16165                final int childCount = ps.childPackageNames.size();
16166                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16167                for (int i = 0; i < childCount; i++) {
16168                    String childPackageName = ps.childPackageNames.get(i);
16169                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16170                    childInfo.removedPackage = childPackageName;
16171                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16172                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16173                    if (childPs != null) {
16174                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16175                    }
16176                }
16177            }
16178        }
16179
16180        boolean ret = false;
16181        if (isSystemApp(ps)) {
16182            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16183            // When an updated system application is deleted we delete the existing resources
16184            // as well and fall back to existing code in system partition
16185            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16186        } else {
16187            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16188            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16189                    outInfo, writeSettings, replacingPackage);
16190        }
16191
16192        // Take a note whether we deleted the package for all users
16193        if (outInfo != null) {
16194            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16195            if (outInfo.removedChildPackages != null) {
16196                synchronized (mPackages) {
16197                    final int childCount = outInfo.removedChildPackages.size();
16198                    for (int i = 0; i < childCount; i++) {
16199                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16200                        if (childInfo != null) {
16201                            childInfo.removedForAllUsers = mPackages.get(
16202                                    childInfo.removedPackage) == null;
16203                        }
16204                    }
16205                }
16206            }
16207            // If we uninstalled an update to a system app there may be some
16208            // child packages that appeared as they are declared in the system
16209            // app but were not declared in the update.
16210            if (isSystemApp(ps)) {
16211                synchronized (mPackages) {
16212                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16213                    final int childCount = (updatedPs.childPackageNames != null)
16214                            ? updatedPs.childPackageNames.size() : 0;
16215                    for (int i = 0; i < childCount; i++) {
16216                        String childPackageName = updatedPs.childPackageNames.get(i);
16217                        if (outInfo.removedChildPackages == null
16218                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16219                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16220                            if (childPs == null) {
16221                                continue;
16222                            }
16223                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16224                            installRes.name = childPackageName;
16225                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16226                            installRes.pkg = mPackages.get(childPackageName);
16227                            installRes.uid = childPs.pkg.applicationInfo.uid;
16228                            if (outInfo.appearedChildPackages == null) {
16229                                outInfo.appearedChildPackages = new ArrayMap<>();
16230                            }
16231                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16232                        }
16233                    }
16234                }
16235            }
16236        }
16237
16238        return ret;
16239    }
16240
16241    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16242        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16243                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16244        for (int nextUserId : userIds) {
16245            if (DEBUG_REMOVE) {
16246                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16247            }
16248            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16249                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16250                    false /*hidden*/, false /*suspended*/, null, null, null,
16251                    false /*blockUninstall*/,
16252                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16253        }
16254    }
16255
16256    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16257            PackageRemovedInfo outInfo) {
16258        final PackageParser.Package pkg;
16259        synchronized (mPackages) {
16260            pkg = mPackages.get(ps.name);
16261        }
16262
16263        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16264                : new int[] {userId};
16265        for (int nextUserId : userIds) {
16266            if (DEBUG_REMOVE) {
16267                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16268                        + nextUserId);
16269            }
16270
16271            destroyAppDataLIF(pkg, userId,
16272                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16273            destroyAppProfilesLIF(pkg, userId);
16274            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16275            schedulePackageCleaning(ps.name, nextUserId, false);
16276            synchronized (mPackages) {
16277                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16278                    scheduleWritePackageRestrictionsLocked(nextUserId);
16279                }
16280                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16281            }
16282        }
16283
16284        if (outInfo != null) {
16285            outInfo.removedPackage = ps.name;
16286            outInfo.removedAppId = ps.appId;
16287            outInfo.removedUsers = userIds;
16288        }
16289
16290        return true;
16291    }
16292
16293    private final class ClearStorageConnection implements ServiceConnection {
16294        IMediaContainerService mContainerService;
16295
16296        @Override
16297        public void onServiceConnected(ComponentName name, IBinder service) {
16298            synchronized (this) {
16299                mContainerService = IMediaContainerService.Stub.asInterface(service);
16300                notifyAll();
16301            }
16302        }
16303
16304        @Override
16305        public void onServiceDisconnected(ComponentName name) {
16306        }
16307    }
16308
16309    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16310        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16311
16312        final boolean mounted;
16313        if (Environment.isExternalStorageEmulated()) {
16314            mounted = true;
16315        } else {
16316            final String status = Environment.getExternalStorageState();
16317
16318            mounted = status.equals(Environment.MEDIA_MOUNTED)
16319                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16320        }
16321
16322        if (!mounted) {
16323            return;
16324        }
16325
16326        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16327        int[] users;
16328        if (userId == UserHandle.USER_ALL) {
16329            users = sUserManager.getUserIds();
16330        } else {
16331            users = new int[] { userId };
16332        }
16333        final ClearStorageConnection conn = new ClearStorageConnection();
16334        if (mContext.bindServiceAsUser(
16335                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16336            try {
16337                for (int curUser : users) {
16338                    long timeout = SystemClock.uptimeMillis() + 5000;
16339                    synchronized (conn) {
16340                        long now;
16341                        while (conn.mContainerService == null &&
16342                                (now = SystemClock.uptimeMillis()) < timeout) {
16343                            try {
16344                                conn.wait(timeout - now);
16345                            } catch (InterruptedException e) {
16346                            }
16347                        }
16348                    }
16349                    if (conn.mContainerService == null) {
16350                        return;
16351                    }
16352
16353                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16354                    clearDirectory(conn.mContainerService,
16355                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16356                    if (allData) {
16357                        clearDirectory(conn.mContainerService,
16358                                userEnv.buildExternalStorageAppDataDirs(packageName));
16359                        clearDirectory(conn.mContainerService,
16360                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16361                    }
16362                }
16363            } finally {
16364                mContext.unbindService(conn);
16365            }
16366        }
16367    }
16368
16369    @Override
16370    public void clearApplicationProfileData(String packageName) {
16371        enforceSystemOrRoot("Only the system can clear all profile data");
16372
16373        final PackageParser.Package pkg;
16374        synchronized (mPackages) {
16375            pkg = mPackages.get(packageName);
16376        }
16377
16378        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16379            synchronized (mInstallLock) {
16380                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16381                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16382                        true /* removeBaseMarker */);
16383            }
16384        }
16385    }
16386
16387    @Override
16388    public void clearApplicationUserData(final String packageName,
16389            final IPackageDataObserver observer, final int userId) {
16390        mContext.enforceCallingOrSelfPermission(
16391                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16392
16393        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16394                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16395
16396        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16397            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16398        }
16399        // Queue up an async operation since the package deletion may take a little while.
16400        mHandler.post(new Runnable() {
16401            public void run() {
16402                mHandler.removeCallbacks(this);
16403                final boolean succeeded;
16404                try (PackageFreezer freezer = freezePackage(packageName,
16405                        "clearApplicationUserData")) {
16406                    synchronized (mInstallLock) {
16407                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16408                    }
16409                    clearExternalStorageDataSync(packageName, userId, true);
16410                }
16411                if (succeeded) {
16412                    // invoke DeviceStorageMonitor's update method to clear any notifications
16413                    DeviceStorageMonitorInternal dsm = LocalServices
16414                            .getService(DeviceStorageMonitorInternal.class);
16415                    if (dsm != null) {
16416                        dsm.checkMemory();
16417                    }
16418                }
16419                if(observer != null) {
16420                    try {
16421                        observer.onRemoveCompleted(packageName, succeeded);
16422                    } catch (RemoteException e) {
16423                        Log.i(TAG, "Observer no longer exists.");
16424                    }
16425                } //end if observer
16426            } //end run
16427        });
16428    }
16429
16430    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16431        if (packageName == null) {
16432            Slog.w(TAG, "Attempt to delete null packageName.");
16433            return false;
16434        }
16435
16436        // Try finding details about the requested package
16437        PackageParser.Package pkg;
16438        synchronized (mPackages) {
16439            pkg = mPackages.get(packageName);
16440            if (pkg == null) {
16441                final PackageSetting ps = mSettings.mPackages.get(packageName);
16442                if (ps != null) {
16443                    pkg = ps.pkg;
16444                }
16445            }
16446
16447            if (pkg == null) {
16448                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16449                return false;
16450            }
16451
16452            PackageSetting ps = (PackageSetting) pkg.mExtras;
16453            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16454        }
16455
16456        clearAppDataLIF(pkg, userId,
16457                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16458
16459        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16460        removeKeystoreDataIfNeeded(userId, appId);
16461
16462        UserManagerInternal umInternal = getUserManagerInternal();
16463        final int flags;
16464        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16465            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16466        } else if (umInternal.isUserRunning(userId)) {
16467            flags = StorageManager.FLAG_STORAGE_DE;
16468        } else {
16469            flags = 0;
16470        }
16471        prepareAppDataContentsLIF(pkg, userId, flags);
16472
16473        return true;
16474    }
16475
16476    /**
16477     * Reverts user permission state changes (permissions and flags) in
16478     * all packages for a given user.
16479     *
16480     * @param userId The device user for which to do a reset.
16481     */
16482    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16483        final int packageCount = mPackages.size();
16484        for (int i = 0; i < packageCount; i++) {
16485            PackageParser.Package pkg = mPackages.valueAt(i);
16486            PackageSetting ps = (PackageSetting) pkg.mExtras;
16487            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16488        }
16489    }
16490
16491    private void resetNetworkPolicies(int userId) {
16492        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16493    }
16494
16495    /**
16496     * Reverts user permission state changes (permissions and flags).
16497     *
16498     * @param ps The package for which to reset.
16499     * @param userId The device user for which to do a reset.
16500     */
16501    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16502            final PackageSetting ps, final int userId) {
16503        if (ps.pkg == null) {
16504            return;
16505        }
16506
16507        // These are flags that can change base on user actions.
16508        final int userSettableMask = FLAG_PERMISSION_USER_SET
16509                | FLAG_PERMISSION_USER_FIXED
16510                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16511                | FLAG_PERMISSION_REVIEW_REQUIRED;
16512
16513        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16514                | FLAG_PERMISSION_POLICY_FIXED;
16515
16516        boolean writeInstallPermissions = false;
16517        boolean writeRuntimePermissions = false;
16518
16519        final int permissionCount = ps.pkg.requestedPermissions.size();
16520        for (int i = 0; i < permissionCount; i++) {
16521            String permission = ps.pkg.requestedPermissions.get(i);
16522
16523            BasePermission bp = mSettings.mPermissions.get(permission);
16524            if (bp == null) {
16525                continue;
16526            }
16527
16528            // If shared user we just reset the state to which only this app contributed.
16529            if (ps.sharedUser != null) {
16530                boolean used = false;
16531                final int packageCount = ps.sharedUser.packages.size();
16532                for (int j = 0; j < packageCount; j++) {
16533                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16534                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16535                            && pkg.pkg.requestedPermissions.contains(permission)) {
16536                        used = true;
16537                        break;
16538                    }
16539                }
16540                if (used) {
16541                    continue;
16542                }
16543            }
16544
16545            PermissionsState permissionsState = ps.getPermissionsState();
16546
16547            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16548
16549            // Always clear the user settable flags.
16550            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16551                    bp.name) != null;
16552            // If permission review is enabled and this is a legacy app, mark the
16553            // permission as requiring a review as this is the initial state.
16554            int flags = 0;
16555            if (Build.PERMISSIONS_REVIEW_REQUIRED
16556                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16557                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16558            }
16559            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16560                if (hasInstallState) {
16561                    writeInstallPermissions = true;
16562                } else {
16563                    writeRuntimePermissions = true;
16564                }
16565            }
16566
16567            // Below is only runtime permission handling.
16568            if (!bp.isRuntime()) {
16569                continue;
16570            }
16571
16572            // Never clobber system or policy.
16573            if ((oldFlags & policyOrSystemFlags) != 0) {
16574                continue;
16575            }
16576
16577            // If this permission was granted by default, make sure it is.
16578            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16579                if (permissionsState.grantRuntimePermission(bp, userId)
16580                        != PERMISSION_OPERATION_FAILURE) {
16581                    writeRuntimePermissions = true;
16582                }
16583            // If permission review is enabled the permissions for a legacy apps
16584            // are represented as constantly granted runtime ones, so don't revoke.
16585            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16586                // Otherwise, reset the permission.
16587                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16588                switch (revokeResult) {
16589                    case PERMISSION_OPERATION_SUCCESS:
16590                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16591                        writeRuntimePermissions = true;
16592                        final int appId = ps.appId;
16593                        mHandler.post(new Runnable() {
16594                            @Override
16595                            public void run() {
16596                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16597                            }
16598                        });
16599                    } break;
16600                }
16601            }
16602        }
16603
16604        // Synchronously write as we are taking permissions away.
16605        if (writeRuntimePermissions) {
16606            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16607        }
16608
16609        // Synchronously write as we are taking permissions away.
16610        if (writeInstallPermissions) {
16611            mSettings.writeLPr();
16612        }
16613    }
16614
16615    /**
16616     * Remove entries from the keystore daemon. Will only remove it if the
16617     * {@code appId} is valid.
16618     */
16619    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16620        if (appId < 0) {
16621            return;
16622        }
16623
16624        final KeyStore keyStore = KeyStore.getInstance();
16625        if (keyStore != null) {
16626            if (userId == UserHandle.USER_ALL) {
16627                for (final int individual : sUserManager.getUserIds()) {
16628                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16629                }
16630            } else {
16631                keyStore.clearUid(UserHandle.getUid(userId, appId));
16632            }
16633        } else {
16634            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16635        }
16636    }
16637
16638    @Override
16639    public void deleteApplicationCacheFiles(final String packageName,
16640            final IPackageDataObserver observer) {
16641        final int userId = UserHandle.getCallingUserId();
16642        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16643    }
16644
16645    @Override
16646    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16647            final IPackageDataObserver observer) {
16648        mContext.enforceCallingOrSelfPermission(
16649                android.Manifest.permission.DELETE_CACHE_FILES, null);
16650        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16651                /* requireFullPermission= */ true, /* checkShell= */ false,
16652                "delete application cache files");
16653
16654        final PackageParser.Package pkg;
16655        synchronized (mPackages) {
16656            pkg = mPackages.get(packageName);
16657        }
16658
16659        // Queue up an async operation since the package deletion may take a little while.
16660        mHandler.post(new Runnable() {
16661            public void run() {
16662                synchronized (mInstallLock) {
16663                    final int flags = StorageManager.FLAG_STORAGE_DE
16664                            | StorageManager.FLAG_STORAGE_CE;
16665                    // We're only clearing cache files, so we don't care if the
16666                    // app is unfrozen and still able to run
16667                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16668                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16669                }
16670                clearExternalStorageDataSync(packageName, userId, false);
16671                if (observer != null) {
16672                    try {
16673                        observer.onRemoveCompleted(packageName, true);
16674                    } catch (RemoteException e) {
16675                        Log.i(TAG, "Observer no longer exists.");
16676                    }
16677                }
16678            }
16679        });
16680    }
16681
16682    @Override
16683    public void getPackageSizeInfo(final String packageName, int userHandle,
16684            final IPackageStatsObserver observer) {
16685        mContext.enforceCallingOrSelfPermission(
16686                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16687        if (packageName == null) {
16688            throw new IllegalArgumentException("Attempt to get size of null packageName");
16689        }
16690
16691        PackageStats stats = new PackageStats(packageName, userHandle);
16692
16693        /*
16694         * Queue up an async operation since the package measurement may take a
16695         * little while.
16696         */
16697        Message msg = mHandler.obtainMessage(INIT_COPY);
16698        msg.obj = new MeasureParams(stats, observer);
16699        mHandler.sendMessage(msg);
16700    }
16701
16702    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16703        final PackageSetting ps;
16704        synchronized (mPackages) {
16705            ps = mSettings.mPackages.get(packageName);
16706            if (ps == null) {
16707                Slog.w(TAG, "Failed to find settings for " + packageName);
16708                return false;
16709            }
16710        }
16711        try {
16712            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16713                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16714                    ps.getCeDataInode(userId), ps.codePathString, stats);
16715        } catch (InstallerException e) {
16716            Slog.w(TAG, String.valueOf(e));
16717            return false;
16718        }
16719
16720        // For now, ignore code size of packages on system partition
16721        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16722            stats.codeSize = 0;
16723        }
16724
16725        return true;
16726    }
16727
16728    private int getUidTargetSdkVersionLockedLPr(int uid) {
16729        Object obj = mSettings.getUserIdLPr(uid);
16730        if (obj instanceof SharedUserSetting) {
16731            final SharedUserSetting sus = (SharedUserSetting) obj;
16732            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16733            final Iterator<PackageSetting> it = sus.packages.iterator();
16734            while (it.hasNext()) {
16735                final PackageSetting ps = it.next();
16736                if (ps.pkg != null) {
16737                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16738                    if (v < vers) vers = v;
16739                }
16740            }
16741            return vers;
16742        } else if (obj instanceof PackageSetting) {
16743            final PackageSetting ps = (PackageSetting) obj;
16744            if (ps.pkg != null) {
16745                return ps.pkg.applicationInfo.targetSdkVersion;
16746            }
16747        }
16748        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16749    }
16750
16751    @Override
16752    public void addPreferredActivity(IntentFilter filter, int match,
16753            ComponentName[] set, ComponentName activity, int userId) {
16754        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16755                "Adding preferred");
16756    }
16757
16758    private void addPreferredActivityInternal(IntentFilter filter, int match,
16759            ComponentName[] set, ComponentName activity, boolean always, int userId,
16760            String opname) {
16761        // writer
16762        int callingUid = Binder.getCallingUid();
16763        enforceCrossUserPermission(callingUid, userId,
16764                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16765        if (filter.countActions() == 0) {
16766            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16767            return;
16768        }
16769        synchronized (mPackages) {
16770            if (mContext.checkCallingOrSelfPermission(
16771                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16772                    != PackageManager.PERMISSION_GRANTED) {
16773                if (getUidTargetSdkVersionLockedLPr(callingUid)
16774                        < Build.VERSION_CODES.FROYO) {
16775                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16776                            + callingUid);
16777                    return;
16778                }
16779                mContext.enforceCallingOrSelfPermission(
16780                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16781            }
16782
16783            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16784            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16785                    + userId + ":");
16786            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16787            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16788            scheduleWritePackageRestrictionsLocked(userId);
16789        }
16790    }
16791
16792    @Override
16793    public void replacePreferredActivity(IntentFilter filter, int match,
16794            ComponentName[] set, ComponentName activity, int userId) {
16795        if (filter.countActions() != 1) {
16796            throw new IllegalArgumentException(
16797                    "replacePreferredActivity expects filter to have only 1 action.");
16798        }
16799        if (filter.countDataAuthorities() != 0
16800                || filter.countDataPaths() != 0
16801                || filter.countDataSchemes() > 1
16802                || filter.countDataTypes() != 0) {
16803            throw new IllegalArgumentException(
16804                    "replacePreferredActivity expects filter to have no data authorities, " +
16805                    "paths, or types; and at most one scheme.");
16806        }
16807
16808        final int callingUid = Binder.getCallingUid();
16809        enforceCrossUserPermission(callingUid, userId,
16810                true /* requireFullPermission */, false /* checkShell */,
16811                "replace preferred activity");
16812        synchronized (mPackages) {
16813            if (mContext.checkCallingOrSelfPermission(
16814                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16815                    != PackageManager.PERMISSION_GRANTED) {
16816                if (getUidTargetSdkVersionLockedLPr(callingUid)
16817                        < Build.VERSION_CODES.FROYO) {
16818                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16819                            + Binder.getCallingUid());
16820                    return;
16821                }
16822                mContext.enforceCallingOrSelfPermission(
16823                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16824            }
16825
16826            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16827            if (pir != null) {
16828                // Get all of the existing entries that exactly match this filter.
16829                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16830                if (existing != null && existing.size() == 1) {
16831                    PreferredActivity cur = existing.get(0);
16832                    if (DEBUG_PREFERRED) {
16833                        Slog.i(TAG, "Checking replace of preferred:");
16834                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16835                        if (!cur.mPref.mAlways) {
16836                            Slog.i(TAG, "  -- CUR; not mAlways!");
16837                        } else {
16838                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16839                            Slog.i(TAG, "  -- CUR: mSet="
16840                                    + Arrays.toString(cur.mPref.mSetComponents));
16841                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16842                            Slog.i(TAG, "  -- NEW: mMatch="
16843                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16844                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16845                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16846                        }
16847                    }
16848                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16849                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16850                            && cur.mPref.sameSet(set)) {
16851                        // Setting the preferred activity to what it happens to be already
16852                        if (DEBUG_PREFERRED) {
16853                            Slog.i(TAG, "Replacing with same preferred activity "
16854                                    + cur.mPref.mShortComponent + " for user "
16855                                    + userId + ":");
16856                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16857                        }
16858                        return;
16859                    }
16860                }
16861
16862                if (existing != null) {
16863                    if (DEBUG_PREFERRED) {
16864                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16865                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16866                    }
16867                    for (int i = 0; i < existing.size(); i++) {
16868                        PreferredActivity pa = existing.get(i);
16869                        if (DEBUG_PREFERRED) {
16870                            Slog.i(TAG, "Removing existing preferred activity "
16871                                    + pa.mPref.mComponent + ":");
16872                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16873                        }
16874                        pir.removeFilter(pa);
16875                    }
16876                }
16877            }
16878            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16879                    "Replacing preferred");
16880        }
16881    }
16882
16883    @Override
16884    public void clearPackagePreferredActivities(String packageName) {
16885        final int uid = Binder.getCallingUid();
16886        // writer
16887        synchronized (mPackages) {
16888            PackageParser.Package pkg = mPackages.get(packageName);
16889            if (pkg == null || pkg.applicationInfo.uid != uid) {
16890                if (mContext.checkCallingOrSelfPermission(
16891                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16892                        != PackageManager.PERMISSION_GRANTED) {
16893                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16894                            < Build.VERSION_CODES.FROYO) {
16895                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16896                                + Binder.getCallingUid());
16897                        return;
16898                    }
16899                    mContext.enforceCallingOrSelfPermission(
16900                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16901                }
16902            }
16903
16904            int user = UserHandle.getCallingUserId();
16905            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16906                scheduleWritePackageRestrictionsLocked(user);
16907            }
16908        }
16909    }
16910
16911    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16912    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16913        ArrayList<PreferredActivity> removed = null;
16914        boolean changed = false;
16915        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16916            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16917            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16918            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16919                continue;
16920            }
16921            Iterator<PreferredActivity> it = pir.filterIterator();
16922            while (it.hasNext()) {
16923                PreferredActivity pa = it.next();
16924                // Mark entry for removal only if it matches the package name
16925                // and the entry is of type "always".
16926                if (packageName == null ||
16927                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16928                                && pa.mPref.mAlways)) {
16929                    if (removed == null) {
16930                        removed = new ArrayList<PreferredActivity>();
16931                    }
16932                    removed.add(pa);
16933                }
16934            }
16935            if (removed != null) {
16936                for (int j=0; j<removed.size(); j++) {
16937                    PreferredActivity pa = removed.get(j);
16938                    pir.removeFilter(pa);
16939                }
16940                changed = true;
16941            }
16942        }
16943        return changed;
16944    }
16945
16946    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16947    private void clearIntentFilterVerificationsLPw(int userId) {
16948        final int packageCount = mPackages.size();
16949        for (int i = 0; i < packageCount; i++) {
16950            PackageParser.Package pkg = mPackages.valueAt(i);
16951            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16952        }
16953    }
16954
16955    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16956    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16957        if (userId == UserHandle.USER_ALL) {
16958            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16959                    sUserManager.getUserIds())) {
16960                for (int oneUserId : sUserManager.getUserIds()) {
16961                    scheduleWritePackageRestrictionsLocked(oneUserId);
16962                }
16963            }
16964        } else {
16965            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16966                scheduleWritePackageRestrictionsLocked(userId);
16967            }
16968        }
16969    }
16970
16971    void clearDefaultBrowserIfNeeded(String packageName) {
16972        for (int oneUserId : sUserManager.getUserIds()) {
16973            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16974            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16975            if (packageName.equals(defaultBrowserPackageName)) {
16976                setDefaultBrowserPackageName(null, oneUserId);
16977            }
16978        }
16979    }
16980
16981    @Override
16982    public void resetApplicationPreferences(int userId) {
16983        mContext.enforceCallingOrSelfPermission(
16984                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16985        final long identity = Binder.clearCallingIdentity();
16986        // writer
16987        try {
16988            synchronized (mPackages) {
16989                clearPackagePreferredActivitiesLPw(null, userId);
16990                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16991                // TODO: We have to reset the default SMS and Phone. This requires
16992                // significant refactoring to keep all default apps in the package
16993                // manager (cleaner but more work) or have the services provide
16994                // callbacks to the package manager to request a default app reset.
16995                applyFactoryDefaultBrowserLPw(userId);
16996                clearIntentFilterVerificationsLPw(userId);
16997                primeDomainVerificationsLPw(userId);
16998                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16999                scheduleWritePackageRestrictionsLocked(userId);
17000            }
17001            resetNetworkPolicies(userId);
17002        } finally {
17003            Binder.restoreCallingIdentity(identity);
17004        }
17005    }
17006
17007    @Override
17008    public int getPreferredActivities(List<IntentFilter> outFilters,
17009            List<ComponentName> outActivities, String packageName) {
17010
17011        int num = 0;
17012        final int userId = UserHandle.getCallingUserId();
17013        // reader
17014        synchronized (mPackages) {
17015            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17016            if (pir != null) {
17017                final Iterator<PreferredActivity> it = pir.filterIterator();
17018                while (it.hasNext()) {
17019                    final PreferredActivity pa = it.next();
17020                    if (packageName == null
17021                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17022                                    && pa.mPref.mAlways)) {
17023                        if (outFilters != null) {
17024                            outFilters.add(new IntentFilter(pa));
17025                        }
17026                        if (outActivities != null) {
17027                            outActivities.add(pa.mPref.mComponent);
17028                        }
17029                    }
17030                }
17031            }
17032        }
17033
17034        return num;
17035    }
17036
17037    @Override
17038    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17039            int userId) {
17040        int callingUid = Binder.getCallingUid();
17041        if (callingUid != Process.SYSTEM_UID) {
17042            throw new SecurityException(
17043                    "addPersistentPreferredActivity can only be run by the system");
17044        }
17045        if (filter.countActions() == 0) {
17046            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17047            return;
17048        }
17049        synchronized (mPackages) {
17050            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17051                    ":");
17052            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17053            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17054                    new PersistentPreferredActivity(filter, activity));
17055            scheduleWritePackageRestrictionsLocked(userId);
17056        }
17057    }
17058
17059    @Override
17060    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17061        int callingUid = Binder.getCallingUid();
17062        if (callingUid != Process.SYSTEM_UID) {
17063            throw new SecurityException(
17064                    "clearPackagePersistentPreferredActivities can only be run by the system");
17065        }
17066        ArrayList<PersistentPreferredActivity> removed = null;
17067        boolean changed = false;
17068        synchronized (mPackages) {
17069            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17070                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17071                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17072                        .valueAt(i);
17073                if (userId != thisUserId) {
17074                    continue;
17075                }
17076                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17077                while (it.hasNext()) {
17078                    PersistentPreferredActivity ppa = it.next();
17079                    // Mark entry for removal only if it matches the package name.
17080                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17081                        if (removed == null) {
17082                            removed = new ArrayList<PersistentPreferredActivity>();
17083                        }
17084                        removed.add(ppa);
17085                    }
17086                }
17087                if (removed != null) {
17088                    for (int j=0; j<removed.size(); j++) {
17089                        PersistentPreferredActivity ppa = removed.get(j);
17090                        ppir.removeFilter(ppa);
17091                    }
17092                    changed = true;
17093                }
17094            }
17095
17096            if (changed) {
17097                scheduleWritePackageRestrictionsLocked(userId);
17098            }
17099        }
17100    }
17101
17102    /**
17103     * Common machinery for picking apart a restored XML blob and passing
17104     * it to a caller-supplied functor to be applied to the running system.
17105     */
17106    private void restoreFromXml(XmlPullParser parser, int userId,
17107            String expectedStartTag, BlobXmlRestorer functor)
17108            throws IOException, XmlPullParserException {
17109        int type;
17110        while ((type = parser.next()) != XmlPullParser.START_TAG
17111                && type != XmlPullParser.END_DOCUMENT) {
17112        }
17113        if (type != XmlPullParser.START_TAG) {
17114            // oops didn't find a start tag?!
17115            if (DEBUG_BACKUP) {
17116                Slog.e(TAG, "Didn't find start tag during restore");
17117            }
17118            return;
17119        }
17120Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17121        // this is supposed to be TAG_PREFERRED_BACKUP
17122        if (!expectedStartTag.equals(parser.getName())) {
17123            if (DEBUG_BACKUP) {
17124                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17125            }
17126            return;
17127        }
17128
17129        // skip interfering stuff, then we're aligned with the backing implementation
17130        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17131Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17132        functor.apply(parser, userId);
17133    }
17134
17135    private interface BlobXmlRestorer {
17136        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17137    }
17138
17139    /**
17140     * Non-Binder method, support for the backup/restore mechanism: write the
17141     * full set of preferred activities in its canonical XML format.  Returns the
17142     * XML output as a byte array, or null if there is none.
17143     */
17144    @Override
17145    public byte[] getPreferredActivityBackup(int userId) {
17146        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17147            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17148        }
17149
17150        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17151        try {
17152            final XmlSerializer serializer = new FastXmlSerializer();
17153            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17154            serializer.startDocument(null, true);
17155            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17156
17157            synchronized (mPackages) {
17158                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17159            }
17160
17161            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17162            serializer.endDocument();
17163            serializer.flush();
17164        } catch (Exception e) {
17165            if (DEBUG_BACKUP) {
17166                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17167            }
17168            return null;
17169        }
17170
17171        return dataStream.toByteArray();
17172    }
17173
17174    @Override
17175    public void restorePreferredActivities(byte[] backup, int userId) {
17176        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17177            throw new SecurityException("Only the system may call restorePreferredActivities()");
17178        }
17179
17180        try {
17181            final XmlPullParser parser = Xml.newPullParser();
17182            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17183            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17184                    new BlobXmlRestorer() {
17185                        @Override
17186                        public void apply(XmlPullParser parser, int userId)
17187                                throws XmlPullParserException, IOException {
17188                            synchronized (mPackages) {
17189                                mSettings.readPreferredActivitiesLPw(parser, userId);
17190                            }
17191                        }
17192                    } );
17193        } catch (Exception e) {
17194            if (DEBUG_BACKUP) {
17195                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17196            }
17197        }
17198    }
17199
17200    /**
17201     * Non-Binder method, support for the backup/restore mechanism: write the
17202     * default browser (etc) settings in its canonical XML format.  Returns the default
17203     * browser XML representation as a byte array, or null if there is none.
17204     */
17205    @Override
17206    public byte[] getDefaultAppsBackup(int userId) {
17207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17208            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17209        }
17210
17211        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17212        try {
17213            final XmlSerializer serializer = new FastXmlSerializer();
17214            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17215            serializer.startDocument(null, true);
17216            serializer.startTag(null, TAG_DEFAULT_APPS);
17217
17218            synchronized (mPackages) {
17219                mSettings.writeDefaultAppsLPr(serializer, userId);
17220            }
17221
17222            serializer.endTag(null, TAG_DEFAULT_APPS);
17223            serializer.endDocument();
17224            serializer.flush();
17225        } catch (Exception e) {
17226            if (DEBUG_BACKUP) {
17227                Slog.e(TAG, "Unable to write default apps for backup", e);
17228            }
17229            return null;
17230        }
17231
17232        return dataStream.toByteArray();
17233    }
17234
17235    @Override
17236    public void restoreDefaultApps(byte[] backup, int userId) {
17237        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17238            throw new SecurityException("Only the system may call restoreDefaultApps()");
17239        }
17240
17241        try {
17242            final XmlPullParser parser = Xml.newPullParser();
17243            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17244            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17245                    new BlobXmlRestorer() {
17246                        @Override
17247                        public void apply(XmlPullParser parser, int userId)
17248                                throws XmlPullParserException, IOException {
17249                            synchronized (mPackages) {
17250                                mSettings.readDefaultAppsLPw(parser, userId);
17251                            }
17252                        }
17253                    } );
17254        } catch (Exception e) {
17255            if (DEBUG_BACKUP) {
17256                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17257            }
17258        }
17259    }
17260
17261    @Override
17262    public byte[] getIntentFilterVerificationBackup(int userId) {
17263        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17264            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17265        }
17266
17267        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17268        try {
17269            final XmlSerializer serializer = new FastXmlSerializer();
17270            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17271            serializer.startDocument(null, true);
17272            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17273
17274            synchronized (mPackages) {
17275                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17276            }
17277
17278            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17279            serializer.endDocument();
17280            serializer.flush();
17281        } catch (Exception e) {
17282            if (DEBUG_BACKUP) {
17283                Slog.e(TAG, "Unable to write default apps for backup", e);
17284            }
17285            return null;
17286        }
17287
17288        return dataStream.toByteArray();
17289    }
17290
17291    @Override
17292    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17293        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17294            throw new SecurityException("Only the system may call restorePreferredActivities()");
17295        }
17296
17297        try {
17298            final XmlPullParser parser = Xml.newPullParser();
17299            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17300            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17301                    new BlobXmlRestorer() {
17302                        @Override
17303                        public void apply(XmlPullParser parser, int userId)
17304                                throws XmlPullParserException, IOException {
17305                            synchronized (mPackages) {
17306                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17307                                mSettings.writeLPr();
17308                            }
17309                        }
17310                    } );
17311        } catch (Exception e) {
17312            if (DEBUG_BACKUP) {
17313                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17314            }
17315        }
17316    }
17317
17318    @Override
17319    public byte[] getPermissionGrantBackup(int userId) {
17320        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17321            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17322        }
17323
17324        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17325        try {
17326            final XmlSerializer serializer = new FastXmlSerializer();
17327            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17328            serializer.startDocument(null, true);
17329            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17330
17331            synchronized (mPackages) {
17332                serializeRuntimePermissionGrantsLPr(serializer, userId);
17333            }
17334
17335            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17336            serializer.endDocument();
17337            serializer.flush();
17338        } catch (Exception e) {
17339            if (DEBUG_BACKUP) {
17340                Slog.e(TAG, "Unable to write default apps for backup", e);
17341            }
17342            return null;
17343        }
17344
17345        return dataStream.toByteArray();
17346    }
17347
17348    @Override
17349    public void restorePermissionGrants(byte[] backup, int userId) {
17350        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17351            throw new SecurityException("Only the system may call restorePermissionGrants()");
17352        }
17353
17354        try {
17355            final XmlPullParser parser = Xml.newPullParser();
17356            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17357            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17358                    new BlobXmlRestorer() {
17359                        @Override
17360                        public void apply(XmlPullParser parser, int userId)
17361                                throws XmlPullParserException, IOException {
17362                            synchronized (mPackages) {
17363                                processRestoredPermissionGrantsLPr(parser, userId);
17364                            }
17365                        }
17366                    } );
17367        } catch (Exception e) {
17368            if (DEBUG_BACKUP) {
17369                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17370            }
17371        }
17372    }
17373
17374    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17375            throws IOException {
17376        serializer.startTag(null, TAG_ALL_GRANTS);
17377
17378        final int N = mSettings.mPackages.size();
17379        for (int i = 0; i < N; i++) {
17380            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17381            boolean pkgGrantsKnown = false;
17382
17383            PermissionsState packagePerms = ps.getPermissionsState();
17384
17385            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17386                final int grantFlags = state.getFlags();
17387                // only look at grants that are not system/policy fixed
17388                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17389                    final boolean isGranted = state.isGranted();
17390                    // And only back up the user-twiddled state bits
17391                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17392                        final String packageName = mSettings.mPackages.keyAt(i);
17393                        if (!pkgGrantsKnown) {
17394                            serializer.startTag(null, TAG_GRANT);
17395                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17396                            pkgGrantsKnown = true;
17397                        }
17398
17399                        final boolean userSet =
17400                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17401                        final boolean userFixed =
17402                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17403                        final boolean revoke =
17404                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17405
17406                        serializer.startTag(null, TAG_PERMISSION);
17407                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17408                        if (isGranted) {
17409                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17410                        }
17411                        if (userSet) {
17412                            serializer.attribute(null, ATTR_USER_SET, "true");
17413                        }
17414                        if (userFixed) {
17415                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17416                        }
17417                        if (revoke) {
17418                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17419                        }
17420                        serializer.endTag(null, TAG_PERMISSION);
17421                    }
17422                }
17423            }
17424
17425            if (pkgGrantsKnown) {
17426                serializer.endTag(null, TAG_GRANT);
17427            }
17428        }
17429
17430        serializer.endTag(null, TAG_ALL_GRANTS);
17431    }
17432
17433    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17434            throws XmlPullParserException, IOException {
17435        String pkgName = null;
17436        int outerDepth = parser.getDepth();
17437        int type;
17438        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17439                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17440            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17441                continue;
17442            }
17443
17444            final String tagName = parser.getName();
17445            if (tagName.equals(TAG_GRANT)) {
17446                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17447                if (DEBUG_BACKUP) {
17448                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17449                }
17450            } else if (tagName.equals(TAG_PERMISSION)) {
17451
17452                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17453                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17454
17455                int newFlagSet = 0;
17456                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17457                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17458                }
17459                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17460                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17461                }
17462                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17463                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17464                }
17465                if (DEBUG_BACKUP) {
17466                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17467                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17468                }
17469                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17470                if (ps != null) {
17471                    // Already installed so we apply the grant immediately
17472                    if (DEBUG_BACKUP) {
17473                        Slog.v(TAG, "        + already installed; applying");
17474                    }
17475                    PermissionsState perms = ps.getPermissionsState();
17476                    BasePermission bp = mSettings.mPermissions.get(permName);
17477                    if (bp != null) {
17478                        if (isGranted) {
17479                            perms.grantRuntimePermission(bp, userId);
17480                        }
17481                        if (newFlagSet != 0) {
17482                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17483                        }
17484                    }
17485                } else {
17486                    // Need to wait for post-restore install to apply the grant
17487                    if (DEBUG_BACKUP) {
17488                        Slog.v(TAG, "        - not yet installed; saving for later");
17489                    }
17490                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17491                            isGranted, newFlagSet, userId);
17492                }
17493            } else {
17494                PackageManagerService.reportSettingsProblem(Log.WARN,
17495                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17496                XmlUtils.skipCurrentTag(parser);
17497            }
17498        }
17499
17500        scheduleWriteSettingsLocked();
17501        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17502    }
17503
17504    @Override
17505    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17506            int sourceUserId, int targetUserId, int flags) {
17507        mContext.enforceCallingOrSelfPermission(
17508                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17509        int callingUid = Binder.getCallingUid();
17510        enforceOwnerRights(ownerPackage, callingUid);
17511        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17512        if (intentFilter.countActions() == 0) {
17513            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17514            return;
17515        }
17516        synchronized (mPackages) {
17517            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17518                    ownerPackage, targetUserId, flags);
17519            CrossProfileIntentResolver resolver =
17520                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17521            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17522            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17523            if (existing != null) {
17524                int size = existing.size();
17525                for (int i = 0; i < size; i++) {
17526                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17527                        return;
17528                    }
17529                }
17530            }
17531            resolver.addFilter(newFilter);
17532            scheduleWritePackageRestrictionsLocked(sourceUserId);
17533        }
17534    }
17535
17536    @Override
17537    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17538        mContext.enforceCallingOrSelfPermission(
17539                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17540        int callingUid = Binder.getCallingUid();
17541        enforceOwnerRights(ownerPackage, callingUid);
17542        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17543        synchronized (mPackages) {
17544            CrossProfileIntentResolver resolver =
17545                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17546            ArraySet<CrossProfileIntentFilter> set =
17547                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17548            for (CrossProfileIntentFilter filter : set) {
17549                if (filter.getOwnerPackage().equals(ownerPackage)) {
17550                    resolver.removeFilter(filter);
17551                }
17552            }
17553            scheduleWritePackageRestrictionsLocked(sourceUserId);
17554        }
17555    }
17556
17557    // Enforcing that callingUid is owning pkg on userId
17558    private void enforceOwnerRights(String pkg, int callingUid) {
17559        // The system owns everything.
17560        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17561            return;
17562        }
17563        int callingUserId = UserHandle.getUserId(callingUid);
17564        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17565        if (pi == null) {
17566            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17567                    + callingUserId);
17568        }
17569        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17570            throw new SecurityException("Calling uid " + callingUid
17571                    + " does not own package " + pkg);
17572        }
17573    }
17574
17575    @Override
17576    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17577        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17578    }
17579
17580    private Intent getHomeIntent() {
17581        Intent intent = new Intent(Intent.ACTION_MAIN);
17582        intent.addCategory(Intent.CATEGORY_HOME);
17583        return intent;
17584    }
17585
17586    private IntentFilter getHomeFilter() {
17587        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17588        filter.addCategory(Intent.CATEGORY_HOME);
17589        filter.addCategory(Intent.CATEGORY_DEFAULT);
17590        return filter;
17591    }
17592
17593    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17594            int userId) {
17595        Intent intent  = getHomeIntent();
17596        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17597                PackageManager.GET_META_DATA, userId);
17598        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17599                true, false, false, userId);
17600
17601        allHomeCandidates.clear();
17602        if (list != null) {
17603            for (ResolveInfo ri : list) {
17604                allHomeCandidates.add(ri);
17605            }
17606        }
17607        return (preferred == null || preferred.activityInfo == null)
17608                ? null
17609                : new ComponentName(preferred.activityInfo.packageName,
17610                        preferred.activityInfo.name);
17611    }
17612
17613    @Override
17614    public void setHomeActivity(ComponentName comp, int userId) {
17615        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17616        getHomeActivitiesAsUser(homeActivities, userId);
17617
17618        boolean found = false;
17619
17620        final int size = homeActivities.size();
17621        final ComponentName[] set = new ComponentName[size];
17622        for (int i = 0; i < size; i++) {
17623            final ResolveInfo candidate = homeActivities.get(i);
17624            final ActivityInfo info = candidate.activityInfo;
17625            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17626            set[i] = activityName;
17627            if (!found && activityName.equals(comp)) {
17628                found = true;
17629            }
17630        }
17631        if (!found) {
17632            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17633                    + userId);
17634        }
17635        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17636                set, comp, userId);
17637    }
17638
17639    private @Nullable String getSetupWizardPackageName() {
17640        final Intent intent = new Intent(Intent.ACTION_MAIN);
17641        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17642
17643        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17644                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17645                        | MATCH_DISABLED_COMPONENTS,
17646                UserHandle.myUserId());
17647        if (matches.size() == 1) {
17648            return matches.get(0).getComponentInfo().packageName;
17649        } else {
17650            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17651                    + ": matches=" + matches);
17652            return null;
17653        }
17654    }
17655
17656    @Override
17657    public void setApplicationEnabledSetting(String appPackageName,
17658            int newState, int flags, int userId, String callingPackage) {
17659        if (!sUserManager.exists(userId)) return;
17660        if (callingPackage == null) {
17661            callingPackage = Integer.toString(Binder.getCallingUid());
17662        }
17663        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17664    }
17665
17666    @Override
17667    public void setComponentEnabledSetting(ComponentName componentName,
17668            int newState, int flags, int userId) {
17669        if (!sUserManager.exists(userId)) return;
17670        setEnabledSetting(componentName.getPackageName(),
17671                componentName.getClassName(), newState, flags, userId, null);
17672    }
17673
17674    private void setEnabledSetting(final String packageName, String className, int newState,
17675            final int flags, int userId, String callingPackage) {
17676        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17677              || newState == COMPONENT_ENABLED_STATE_ENABLED
17678              || newState == COMPONENT_ENABLED_STATE_DISABLED
17679              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17680              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17681            throw new IllegalArgumentException("Invalid new component state: "
17682                    + newState);
17683        }
17684        PackageSetting pkgSetting;
17685        final int uid = Binder.getCallingUid();
17686        final int permission;
17687        if (uid == Process.SYSTEM_UID) {
17688            permission = PackageManager.PERMISSION_GRANTED;
17689        } else {
17690            permission = mContext.checkCallingOrSelfPermission(
17691                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17692        }
17693        enforceCrossUserPermission(uid, userId,
17694                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17695        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17696        boolean sendNow = false;
17697        boolean isApp = (className == null);
17698        String componentName = isApp ? packageName : className;
17699        int packageUid = -1;
17700        ArrayList<String> components;
17701
17702        // writer
17703        synchronized (mPackages) {
17704            pkgSetting = mSettings.mPackages.get(packageName);
17705            if (pkgSetting == null) {
17706                if (className == null) {
17707                    throw new IllegalArgumentException("Unknown package: " + packageName);
17708                }
17709                throw new IllegalArgumentException(
17710                        "Unknown component: " + packageName + "/" + className);
17711            }
17712        }
17713
17714        // Limit who can change which apps
17715        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17716            // Don't allow apps that don't have permission to modify other apps
17717            if (!allowedByPermission) {
17718                throw new SecurityException(
17719                        "Permission Denial: attempt to change component state from pid="
17720                        + Binder.getCallingPid()
17721                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17722            }
17723            // Don't allow changing profile and device owners.
17724            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17725                throw new SecurityException("Cannot disable a device owner or a profile owner");
17726            }
17727        }
17728
17729        synchronized (mPackages) {
17730            if (uid == Process.SHELL_UID) {
17731                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17732                int oldState = pkgSetting.getEnabled(userId);
17733                if (className == null
17734                    &&
17735                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17736                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17737                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17738                    &&
17739                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17740                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17741                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17742                    // ok
17743                } else {
17744                    throw new SecurityException(
17745                            "Shell cannot change component state for " + packageName + "/"
17746                            + className + " to " + newState);
17747                }
17748            }
17749            if (className == null) {
17750                // We're dealing with an application/package level state change
17751                if (pkgSetting.getEnabled(userId) == newState) {
17752                    // Nothing to do
17753                    return;
17754                }
17755                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17756                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17757                    // Don't care about who enables an app.
17758                    callingPackage = null;
17759                }
17760                pkgSetting.setEnabled(newState, userId, callingPackage);
17761                // pkgSetting.pkg.mSetEnabled = newState;
17762            } else {
17763                // We're dealing with a component level state change
17764                // First, verify that this is a valid class name.
17765                PackageParser.Package pkg = pkgSetting.pkg;
17766                if (pkg == null || !pkg.hasComponentClassName(className)) {
17767                    if (pkg != null &&
17768                            pkg.applicationInfo.targetSdkVersion >=
17769                                    Build.VERSION_CODES.JELLY_BEAN) {
17770                        throw new IllegalArgumentException("Component class " + className
17771                                + " does not exist in " + packageName);
17772                    } else {
17773                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17774                                + className + " does not exist in " + packageName);
17775                    }
17776                }
17777                switch (newState) {
17778                case COMPONENT_ENABLED_STATE_ENABLED:
17779                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17780                        return;
17781                    }
17782                    break;
17783                case COMPONENT_ENABLED_STATE_DISABLED:
17784                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17785                        return;
17786                    }
17787                    break;
17788                case COMPONENT_ENABLED_STATE_DEFAULT:
17789                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17790                        return;
17791                    }
17792                    break;
17793                default:
17794                    Slog.e(TAG, "Invalid new component state: " + newState);
17795                    return;
17796                }
17797            }
17798            scheduleWritePackageRestrictionsLocked(userId);
17799            components = mPendingBroadcasts.get(userId, packageName);
17800            final boolean newPackage = components == null;
17801            if (newPackage) {
17802                components = new ArrayList<String>();
17803            }
17804            if (!components.contains(componentName)) {
17805                components.add(componentName);
17806            }
17807            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17808                sendNow = true;
17809                // Purge entry from pending broadcast list if another one exists already
17810                // since we are sending one right away.
17811                mPendingBroadcasts.remove(userId, packageName);
17812            } else {
17813                if (newPackage) {
17814                    mPendingBroadcasts.put(userId, packageName, components);
17815                }
17816                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17817                    // Schedule a message
17818                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17819                }
17820            }
17821        }
17822
17823        long callingId = Binder.clearCallingIdentity();
17824        try {
17825            if (sendNow) {
17826                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17827                sendPackageChangedBroadcast(packageName,
17828                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17829            }
17830        } finally {
17831            Binder.restoreCallingIdentity(callingId);
17832        }
17833    }
17834
17835    @Override
17836    public void flushPackageRestrictionsAsUser(int userId) {
17837        if (!sUserManager.exists(userId)) {
17838            return;
17839        }
17840        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17841                false /* checkShell */, "flushPackageRestrictions");
17842        synchronized (mPackages) {
17843            mSettings.writePackageRestrictionsLPr(userId);
17844            mDirtyUsers.remove(userId);
17845            if (mDirtyUsers.isEmpty()) {
17846                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17847            }
17848        }
17849    }
17850
17851    private void sendPackageChangedBroadcast(String packageName,
17852            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17853        if (DEBUG_INSTALL)
17854            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17855                    + componentNames);
17856        Bundle extras = new Bundle(4);
17857        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17858        String nameList[] = new String[componentNames.size()];
17859        componentNames.toArray(nameList);
17860        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17861        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17862        extras.putInt(Intent.EXTRA_UID, packageUid);
17863        // If this is not reporting a change of the overall package, then only send it
17864        // to registered receivers.  We don't want to launch a swath of apps for every
17865        // little component state change.
17866        final int flags = !componentNames.contains(packageName)
17867                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17868        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17869                new int[] {UserHandle.getUserId(packageUid)});
17870    }
17871
17872    @Override
17873    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17874        if (!sUserManager.exists(userId)) return;
17875        final int uid = Binder.getCallingUid();
17876        final int permission = mContext.checkCallingOrSelfPermission(
17877                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17878        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17879        enforceCrossUserPermission(uid, userId,
17880                true /* requireFullPermission */, true /* checkShell */, "stop package");
17881        // writer
17882        synchronized (mPackages) {
17883            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17884                    allowedByPermission, uid, userId)) {
17885                scheduleWritePackageRestrictionsLocked(userId);
17886            }
17887        }
17888    }
17889
17890    @Override
17891    public String getInstallerPackageName(String packageName) {
17892        // reader
17893        synchronized (mPackages) {
17894            return mSettings.getInstallerPackageNameLPr(packageName);
17895        }
17896    }
17897
17898    public boolean isOrphaned(String packageName) {
17899        // reader
17900        synchronized (mPackages) {
17901            return mSettings.isOrphaned(packageName);
17902        }
17903    }
17904
17905    @Override
17906    public int getApplicationEnabledSetting(String packageName, int userId) {
17907        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17908        int uid = Binder.getCallingUid();
17909        enforceCrossUserPermission(uid, userId,
17910                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17911        // reader
17912        synchronized (mPackages) {
17913            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17914        }
17915    }
17916
17917    @Override
17918    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17919        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17920        int uid = Binder.getCallingUid();
17921        enforceCrossUserPermission(uid, userId,
17922                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17923        // reader
17924        synchronized (mPackages) {
17925            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17926        }
17927    }
17928
17929    @Override
17930    public void enterSafeMode() {
17931        enforceSystemOrRoot("Only the system can request entering safe mode");
17932
17933        if (!mSystemReady) {
17934            mSafeMode = true;
17935        }
17936    }
17937
17938    @Override
17939    public void systemReady() {
17940        mSystemReady = true;
17941
17942        // Read the compatibilty setting when the system is ready.
17943        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17944                mContext.getContentResolver(),
17945                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17946        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17947        if (DEBUG_SETTINGS) {
17948            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17949        }
17950
17951        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17952
17953        synchronized (mPackages) {
17954            // Verify that all of the preferred activity components actually
17955            // exist.  It is possible for applications to be updated and at
17956            // that point remove a previously declared activity component that
17957            // had been set as a preferred activity.  We try to clean this up
17958            // the next time we encounter that preferred activity, but it is
17959            // possible for the user flow to never be able to return to that
17960            // situation so here we do a sanity check to make sure we haven't
17961            // left any junk around.
17962            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17963            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17964                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17965                removed.clear();
17966                for (PreferredActivity pa : pir.filterSet()) {
17967                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17968                        removed.add(pa);
17969                    }
17970                }
17971                if (removed.size() > 0) {
17972                    for (int r=0; r<removed.size(); r++) {
17973                        PreferredActivity pa = removed.get(r);
17974                        Slog.w(TAG, "Removing dangling preferred activity: "
17975                                + pa.mPref.mComponent);
17976                        pir.removeFilter(pa);
17977                    }
17978                    mSettings.writePackageRestrictionsLPr(
17979                            mSettings.mPreferredActivities.keyAt(i));
17980                }
17981            }
17982
17983            for (int userId : UserManagerService.getInstance().getUserIds()) {
17984                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17985                    grantPermissionsUserIds = ArrayUtils.appendInt(
17986                            grantPermissionsUserIds, userId);
17987                }
17988            }
17989        }
17990        sUserManager.systemReady();
17991
17992        // If we upgraded grant all default permissions before kicking off.
17993        for (int userId : grantPermissionsUserIds) {
17994            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17995        }
17996
17997        // Kick off any messages waiting for system ready
17998        if (mPostSystemReadyMessages != null) {
17999            for (Message msg : mPostSystemReadyMessages) {
18000                msg.sendToTarget();
18001            }
18002            mPostSystemReadyMessages = null;
18003        }
18004
18005        // Watch for external volumes that come and go over time
18006        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18007        storage.registerListener(mStorageListener);
18008
18009        mInstallerService.systemReady();
18010        mPackageDexOptimizer.systemReady();
18011
18012        MountServiceInternal mountServiceInternal = LocalServices.getService(
18013                MountServiceInternal.class);
18014        mountServiceInternal.addExternalStoragePolicy(
18015                new MountServiceInternal.ExternalStorageMountPolicy() {
18016            @Override
18017            public int getMountMode(int uid, String packageName) {
18018                if (Process.isIsolated(uid)) {
18019                    return Zygote.MOUNT_EXTERNAL_NONE;
18020                }
18021                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18022                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18023                }
18024                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18025                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18026                }
18027                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18028                    return Zygote.MOUNT_EXTERNAL_READ;
18029                }
18030                return Zygote.MOUNT_EXTERNAL_WRITE;
18031            }
18032
18033            @Override
18034            public boolean hasExternalStorage(int uid, String packageName) {
18035                return true;
18036            }
18037        });
18038
18039        // Now that we're mostly running, clean up stale users and apps
18040        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18041        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18042    }
18043
18044    @Override
18045    public boolean isSafeMode() {
18046        return mSafeMode;
18047    }
18048
18049    @Override
18050    public boolean hasSystemUidErrors() {
18051        return mHasSystemUidErrors;
18052    }
18053
18054    static String arrayToString(int[] array) {
18055        StringBuffer buf = new StringBuffer(128);
18056        buf.append('[');
18057        if (array != null) {
18058            for (int i=0; i<array.length; i++) {
18059                if (i > 0) buf.append(", ");
18060                buf.append(array[i]);
18061            }
18062        }
18063        buf.append(']');
18064        return buf.toString();
18065    }
18066
18067    static class DumpState {
18068        public static final int DUMP_LIBS = 1 << 0;
18069        public static final int DUMP_FEATURES = 1 << 1;
18070        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18071        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18072        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18073        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18074        public static final int DUMP_PERMISSIONS = 1 << 6;
18075        public static final int DUMP_PACKAGES = 1 << 7;
18076        public static final int DUMP_SHARED_USERS = 1 << 8;
18077        public static final int DUMP_MESSAGES = 1 << 9;
18078        public static final int DUMP_PROVIDERS = 1 << 10;
18079        public static final int DUMP_VERIFIERS = 1 << 11;
18080        public static final int DUMP_PREFERRED = 1 << 12;
18081        public static final int DUMP_PREFERRED_XML = 1 << 13;
18082        public static final int DUMP_KEYSETS = 1 << 14;
18083        public static final int DUMP_VERSION = 1 << 15;
18084        public static final int DUMP_INSTALLS = 1 << 16;
18085        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18086        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18087        public static final int DUMP_FROZEN = 1 << 19;
18088        public static final int DUMP_DEXOPT = 1 << 20;
18089
18090        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18091
18092        private int mTypes;
18093
18094        private int mOptions;
18095
18096        private boolean mTitlePrinted;
18097
18098        private SharedUserSetting mSharedUser;
18099
18100        public boolean isDumping(int type) {
18101            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18102                return true;
18103            }
18104
18105            return (mTypes & type) != 0;
18106        }
18107
18108        public void setDump(int type) {
18109            mTypes |= type;
18110        }
18111
18112        public boolean isOptionEnabled(int option) {
18113            return (mOptions & option) != 0;
18114        }
18115
18116        public void setOptionEnabled(int option) {
18117            mOptions |= option;
18118        }
18119
18120        public boolean onTitlePrinted() {
18121            final boolean printed = mTitlePrinted;
18122            mTitlePrinted = true;
18123            return printed;
18124        }
18125
18126        public boolean getTitlePrinted() {
18127            return mTitlePrinted;
18128        }
18129
18130        public void setTitlePrinted(boolean enabled) {
18131            mTitlePrinted = enabled;
18132        }
18133
18134        public SharedUserSetting getSharedUser() {
18135            return mSharedUser;
18136        }
18137
18138        public void setSharedUser(SharedUserSetting user) {
18139            mSharedUser = user;
18140        }
18141    }
18142
18143    @Override
18144    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18145            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18146        (new PackageManagerShellCommand(this)).exec(
18147                this, in, out, err, args, resultReceiver);
18148    }
18149
18150    @Override
18151    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18152        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18153                != PackageManager.PERMISSION_GRANTED) {
18154            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18155                    + Binder.getCallingPid()
18156                    + ", uid=" + Binder.getCallingUid()
18157                    + " without permission "
18158                    + android.Manifest.permission.DUMP);
18159            return;
18160        }
18161
18162        DumpState dumpState = new DumpState();
18163        boolean fullPreferred = false;
18164        boolean checkin = false;
18165
18166        String packageName = null;
18167        ArraySet<String> permissionNames = null;
18168
18169        int opti = 0;
18170        while (opti < args.length) {
18171            String opt = args[opti];
18172            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18173                break;
18174            }
18175            opti++;
18176
18177            if ("-a".equals(opt)) {
18178                // Right now we only know how to print all.
18179            } else if ("-h".equals(opt)) {
18180                pw.println("Package manager dump options:");
18181                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18182                pw.println("    --checkin: dump for a checkin");
18183                pw.println("    -f: print details of intent filters");
18184                pw.println("    -h: print this help");
18185                pw.println("  cmd may be one of:");
18186                pw.println("    l[ibraries]: list known shared libraries");
18187                pw.println("    f[eatures]: list device features");
18188                pw.println("    k[eysets]: print known keysets");
18189                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18190                pw.println("    perm[issions]: dump permissions");
18191                pw.println("    permission [name ...]: dump declaration and use of given permission");
18192                pw.println("    pref[erred]: print preferred package settings");
18193                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18194                pw.println("    prov[iders]: dump content providers");
18195                pw.println("    p[ackages]: dump installed packages");
18196                pw.println("    s[hared-users]: dump shared user IDs");
18197                pw.println("    m[essages]: print collected runtime messages");
18198                pw.println("    v[erifiers]: print package verifier info");
18199                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18200                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18201                pw.println("    version: print database version info");
18202                pw.println("    write: write current settings now");
18203                pw.println("    installs: details about install sessions");
18204                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18205                pw.println("    dexopt: dump dexopt state");
18206                pw.println("    <package.name>: info about given package");
18207                return;
18208            } else if ("--checkin".equals(opt)) {
18209                checkin = true;
18210            } else if ("-f".equals(opt)) {
18211                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18212            } else {
18213                pw.println("Unknown argument: " + opt + "; use -h for help");
18214            }
18215        }
18216
18217        // Is the caller requesting to dump a particular piece of data?
18218        if (opti < args.length) {
18219            String cmd = args[opti];
18220            opti++;
18221            // Is this a package name?
18222            if ("android".equals(cmd) || cmd.contains(".")) {
18223                packageName = cmd;
18224                // When dumping a single package, we always dump all of its
18225                // filter information since the amount of data will be reasonable.
18226                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18227            } else if ("check-permission".equals(cmd)) {
18228                if (opti >= args.length) {
18229                    pw.println("Error: check-permission missing permission argument");
18230                    return;
18231                }
18232                String perm = args[opti];
18233                opti++;
18234                if (opti >= args.length) {
18235                    pw.println("Error: check-permission missing package argument");
18236                    return;
18237                }
18238                String pkg = args[opti];
18239                opti++;
18240                int user = UserHandle.getUserId(Binder.getCallingUid());
18241                if (opti < args.length) {
18242                    try {
18243                        user = Integer.parseInt(args[opti]);
18244                    } catch (NumberFormatException e) {
18245                        pw.println("Error: check-permission user argument is not a number: "
18246                                + args[opti]);
18247                        return;
18248                    }
18249                }
18250                pw.println(checkPermission(perm, pkg, user));
18251                return;
18252            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18253                dumpState.setDump(DumpState.DUMP_LIBS);
18254            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18255                dumpState.setDump(DumpState.DUMP_FEATURES);
18256            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18257                if (opti >= args.length) {
18258                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18259                            | DumpState.DUMP_SERVICE_RESOLVERS
18260                            | DumpState.DUMP_RECEIVER_RESOLVERS
18261                            | DumpState.DUMP_CONTENT_RESOLVERS);
18262                } else {
18263                    while (opti < args.length) {
18264                        String name = args[opti];
18265                        if ("a".equals(name) || "activity".equals(name)) {
18266                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18267                        } else if ("s".equals(name) || "service".equals(name)) {
18268                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18269                        } else if ("r".equals(name) || "receiver".equals(name)) {
18270                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18271                        } else if ("c".equals(name) || "content".equals(name)) {
18272                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18273                        } else {
18274                            pw.println("Error: unknown resolver table type: " + name);
18275                            return;
18276                        }
18277                        opti++;
18278                    }
18279                }
18280            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18281                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18282            } else if ("permission".equals(cmd)) {
18283                if (opti >= args.length) {
18284                    pw.println("Error: permission requires permission name");
18285                    return;
18286                }
18287                permissionNames = new ArraySet<>();
18288                while (opti < args.length) {
18289                    permissionNames.add(args[opti]);
18290                    opti++;
18291                }
18292                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18293                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18294            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18295                dumpState.setDump(DumpState.DUMP_PREFERRED);
18296            } else if ("preferred-xml".equals(cmd)) {
18297                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18298                if (opti < args.length && "--full".equals(args[opti])) {
18299                    fullPreferred = true;
18300                    opti++;
18301                }
18302            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18303                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18304            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18305                dumpState.setDump(DumpState.DUMP_PACKAGES);
18306            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18307                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18308            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18309                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18310            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18311                dumpState.setDump(DumpState.DUMP_MESSAGES);
18312            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18313                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18314            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18315                    || "intent-filter-verifiers".equals(cmd)) {
18316                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18317            } else if ("version".equals(cmd)) {
18318                dumpState.setDump(DumpState.DUMP_VERSION);
18319            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18320                dumpState.setDump(DumpState.DUMP_KEYSETS);
18321            } else if ("installs".equals(cmd)) {
18322                dumpState.setDump(DumpState.DUMP_INSTALLS);
18323            } else if ("frozen".equals(cmd)) {
18324                dumpState.setDump(DumpState.DUMP_FROZEN);
18325            } else if ("dexopt".equals(cmd)) {
18326                dumpState.setDump(DumpState.DUMP_DEXOPT);
18327            } else if ("write".equals(cmd)) {
18328                synchronized (mPackages) {
18329                    mSettings.writeLPr();
18330                    pw.println("Settings written.");
18331                    return;
18332                }
18333            }
18334        }
18335
18336        if (checkin) {
18337            pw.println("vers,1");
18338        }
18339
18340        // reader
18341        synchronized (mPackages) {
18342            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18343                if (!checkin) {
18344                    if (dumpState.onTitlePrinted())
18345                        pw.println();
18346                    pw.println("Database versions:");
18347                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18348                }
18349            }
18350
18351            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18352                if (!checkin) {
18353                    if (dumpState.onTitlePrinted())
18354                        pw.println();
18355                    pw.println("Verifiers:");
18356                    pw.print("  Required: ");
18357                    pw.print(mRequiredVerifierPackage);
18358                    pw.print(" (uid=");
18359                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18360                            UserHandle.USER_SYSTEM));
18361                    pw.println(")");
18362                } else if (mRequiredVerifierPackage != null) {
18363                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18364                    pw.print(",");
18365                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18366                            UserHandle.USER_SYSTEM));
18367                }
18368            }
18369
18370            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18371                    packageName == null) {
18372                if (mIntentFilterVerifierComponent != null) {
18373                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18374                    if (!checkin) {
18375                        if (dumpState.onTitlePrinted())
18376                            pw.println();
18377                        pw.println("Intent Filter Verifier:");
18378                        pw.print("  Using: ");
18379                        pw.print(verifierPackageName);
18380                        pw.print(" (uid=");
18381                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18382                                UserHandle.USER_SYSTEM));
18383                        pw.println(")");
18384                    } else if (verifierPackageName != null) {
18385                        pw.print("ifv,"); pw.print(verifierPackageName);
18386                        pw.print(",");
18387                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18388                                UserHandle.USER_SYSTEM));
18389                    }
18390                } else {
18391                    pw.println();
18392                    pw.println("No Intent Filter Verifier available!");
18393                }
18394            }
18395
18396            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18397                boolean printedHeader = false;
18398                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18399                while (it.hasNext()) {
18400                    String name = it.next();
18401                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18402                    if (!checkin) {
18403                        if (!printedHeader) {
18404                            if (dumpState.onTitlePrinted())
18405                                pw.println();
18406                            pw.println("Libraries:");
18407                            printedHeader = true;
18408                        }
18409                        pw.print("  ");
18410                    } else {
18411                        pw.print("lib,");
18412                    }
18413                    pw.print(name);
18414                    if (!checkin) {
18415                        pw.print(" -> ");
18416                    }
18417                    if (ent.path != null) {
18418                        if (!checkin) {
18419                            pw.print("(jar) ");
18420                            pw.print(ent.path);
18421                        } else {
18422                            pw.print(",jar,");
18423                            pw.print(ent.path);
18424                        }
18425                    } else {
18426                        if (!checkin) {
18427                            pw.print("(apk) ");
18428                            pw.print(ent.apk);
18429                        } else {
18430                            pw.print(",apk,");
18431                            pw.print(ent.apk);
18432                        }
18433                    }
18434                    pw.println();
18435                }
18436            }
18437
18438            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18439                if (dumpState.onTitlePrinted())
18440                    pw.println();
18441                if (!checkin) {
18442                    pw.println("Features:");
18443                }
18444
18445                for (FeatureInfo feat : mAvailableFeatures.values()) {
18446                    if (checkin) {
18447                        pw.print("feat,");
18448                        pw.print(feat.name);
18449                        pw.print(",");
18450                        pw.println(feat.version);
18451                    } else {
18452                        pw.print("  ");
18453                        pw.print(feat.name);
18454                        if (feat.version > 0) {
18455                            pw.print(" version=");
18456                            pw.print(feat.version);
18457                        }
18458                        pw.println();
18459                    }
18460                }
18461            }
18462
18463            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18464                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18465                        : "Activity Resolver Table:", "  ", packageName,
18466                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18467                    dumpState.setTitlePrinted(true);
18468                }
18469            }
18470            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18471                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18472                        : "Receiver Resolver Table:", "  ", packageName,
18473                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18474                    dumpState.setTitlePrinted(true);
18475                }
18476            }
18477            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18478                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18479                        : "Service Resolver Table:", "  ", packageName,
18480                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18481                    dumpState.setTitlePrinted(true);
18482                }
18483            }
18484            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18485                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18486                        : "Provider Resolver Table:", "  ", packageName,
18487                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18488                    dumpState.setTitlePrinted(true);
18489                }
18490            }
18491
18492            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18493                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18494                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18495                    int user = mSettings.mPreferredActivities.keyAt(i);
18496                    if (pir.dump(pw,
18497                            dumpState.getTitlePrinted()
18498                                ? "\nPreferred Activities User " + user + ":"
18499                                : "Preferred Activities User " + user + ":", "  ",
18500                            packageName, true, false)) {
18501                        dumpState.setTitlePrinted(true);
18502                    }
18503                }
18504            }
18505
18506            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18507                pw.flush();
18508                FileOutputStream fout = new FileOutputStream(fd);
18509                BufferedOutputStream str = new BufferedOutputStream(fout);
18510                XmlSerializer serializer = new FastXmlSerializer();
18511                try {
18512                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18513                    serializer.startDocument(null, true);
18514                    serializer.setFeature(
18515                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18516                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18517                    serializer.endDocument();
18518                    serializer.flush();
18519                } catch (IllegalArgumentException e) {
18520                    pw.println("Failed writing: " + e);
18521                } catch (IllegalStateException e) {
18522                    pw.println("Failed writing: " + e);
18523                } catch (IOException e) {
18524                    pw.println("Failed writing: " + e);
18525                }
18526            }
18527
18528            if (!checkin
18529                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18530                    && packageName == null) {
18531                pw.println();
18532                int count = mSettings.mPackages.size();
18533                if (count == 0) {
18534                    pw.println("No applications!");
18535                    pw.println();
18536                } else {
18537                    final String prefix = "  ";
18538                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18539                    if (allPackageSettings.size() == 0) {
18540                        pw.println("No domain preferred apps!");
18541                        pw.println();
18542                    } else {
18543                        pw.println("App verification status:");
18544                        pw.println();
18545                        count = 0;
18546                        for (PackageSetting ps : allPackageSettings) {
18547                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18548                            if (ivi == null || ivi.getPackageName() == null) continue;
18549                            pw.println(prefix + "Package: " + ivi.getPackageName());
18550                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18551                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18552                            pw.println();
18553                            count++;
18554                        }
18555                        if (count == 0) {
18556                            pw.println(prefix + "No app verification established.");
18557                            pw.println();
18558                        }
18559                        for (int userId : sUserManager.getUserIds()) {
18560                            pw.println("App linkages for user " + userId + ":");
18561                            pw.println();
18562                            count = 0;
18563                            for (PackageSetting ps : allPackageSettings) {
18564                                final long status = ps.getDomainVerificationStatusForUser(userId);
18565                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18566                                    continue;
18567                                }
18568                                pw.println(prefix + "Package: " + ps.name);
18569                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18570                                String statusStr = IntentFilterVerificationInfo.
18571                                        getStatusStringFromValue(status);
18572                                pw.println(prefix + "Status:  " + statusStr);
18573                                pw.println();
18574                                count++;
18575                            }
18576                            if (count == 0) {
18577                                pw.println(prefix + "No configured app linkages.");
18578                                pw.println();
18579                            }
18580                        }
18581                    }
18582                }
18583            }
18584
18585            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18586                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18587                if (packageName == null && permissionNames == null) {
18588                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18589                        if (iperm == 0) {
18590                            if (dumpState.onTitlePrinted())
18591                                pw.println();
18592                            pw.println("AppOp Permissions:");
18593                        }
18594                        pw.print("  AppOp Permission ");
18595                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18596                        pw.println(":");
18597                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18598                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18599                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18600                        }
18601                    }
18602                }
18603            }
18604
18605            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18606                boolean printedSomething = false;
18607                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18608                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18609                        continue;
18610                    }
18611                    if (!printedSomething) {
18612                        if (dumpState.onTitlePrinted())
18613                            pw.println();
18614                        pw.println("Registered ContentProviders:");
18615                        printedSomething = true;
18616                    }
18617                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18618                    pw.print("    "); pw.println(p.toString());
18619                }
18620                printedSomething = false;
18621                for (Map.Entry<String, PackageParser.Provider> entry :
18622                        mProvidersByAuthority.entrySet()) {
18623                    PackageParser.Provider p = entry.getValue();
18624                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18625                        continue;
18626                    }
18627                    if (!printedSomething) {
18628                        if (dumpState.onTitlePrinted())
18629                            pw.println();
18630                        pw.println("ContentProvider Authorities:");
18631                        printedSomething = true;
18632                    }
18633                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18634                    pw.print("    "); pw.println(p.toString());
18635                    if (p.info != null && p.info.applicationInfo != null) {
18636                        final String appInfo = p.info.applicationInfo.toString();
18637                        pw.print("      applicationInfo="); pw.println(appInfo);
18638                    }
18639                }
18640            }
18641
18642            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18643                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18644            }
18645
18646            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18647                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18648            }
18649
18650            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18651                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18652            }
18653
18654            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18655                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18656            }
18657
18658            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18659                // XXX should handle packageName != null by dumping only install data that
18660                // the given package is involved with.
18661                if (dumpState.onTitlePrinted()) pw.println();
18662                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18663            }
18664
18665            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18666                // XXX should handle packageName != null by dumping only install data that
18667                // the given package is involved with.
18668                if (dumpState.onTitlePrinted()) pw.println();
18669
18670                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18671                ipw.println();
18672                ipw.println("Frozen packages:");
18673                ipw.increaseIndent();
18674                if (mFrozenPackages.size() == 0) {
18675                    ipw.println("(none)");
18676                } else {
18677                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18678                        ipw.println(mFrozenPackages.valueAt(i));
18679                    }
18680                }
18681                ipw.decreaseIndent();
18682            }
18683
18684            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18685                if (dumpState.onTitlePrinted()) pw.println();
18686                dumpDexoptStateLPr(pw, packageName);
18687            }
18688
18689            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18690                if (dumpState.onTitlePrinted()) pw.println();
18691                mSettings.dumpReadMessagesLPr(pw, dumpState);
18692
18693                pw.println();
18694                pw.println("Package warning messages:");
18695                BufferedReader in = null;
18696                String line = null;
18697                try {
18698                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18699                    while ((line = in.readLine()) != null) {
18700                        if (line.contains("ignored: updated version")) continue;
18701                        pw.println(line);
18702                    }
18703                } catch (IOException ignored) {
18704                } finally {
18705                    IoUtils.closeQuietly(in);
18706                }
18707            }
18708
18709            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18710                BufferedReader in = null;
18711                String line = null;
18712                try {
18713                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18714                    while ((line = in.readLine()) != null) {
18715                        if (line.contains("ignored: updated version")) continue;
18716                        pw.print("msg,");
18717                        pw.println(line);
18718                    }
18719                } catch (IOException ignored) {
18720                } finally {
18721                    IoUtils.closeQuietly(in);
18722                }
18723            }
18724        }
18725    }
18726
18727    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18728        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18729        ipw.println();
18730        ipw.println("Dexopt state:");
18731        ipw.increaseIndent();
18732        Collection<PackageParser.Package> packages = null;
18733        if (packageName != null) {
18734            PackageParser.Package targetPackage = mPackages.get(packageName);
18735            if (targetPackage != null) {
18736                packages = Collections.singletonList(targetPackage);
18737            } else {
18738                ipw.println("Unable to find package: " + packageName);
18739                return;
18740            }
18741        } else {
18742            packages = mPackages.values();
18743        }
18744
18745        for (PackageParser.Package pkg : packages) {
18746            ipw.println("[" + pkg.packageName + "]");
18747            ipw.increaseIndent();
18748            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18749            ipw.decreaseIndent();
18750        }
18751    }
18752
18753    private String dumpDomainString(String packageName) {
18754        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18755                .getList();
18756        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18757
18758        ArraySet<String> result = new ArraySet<>();
18759        if (iviList.size() > 0) {
18760            for (IntentFilterVerificationInfo ivi : iviList) {
18761                for (String host : ivi.getDomains()) {
18762                    result.add(host);
18763                }
18764            }
18765        }
18766        if (filters != null && filters.size() > 0) {
18767            for (IntentFilter filter : filters) {
18768                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18769                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18770                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18771                    result.addAll(filter.getHostsList());
18772                }
18773            }
18774        }
18775
18776        StringBuilder sb = new StringBuilder(result.size() * 16);
18777        for (String domain : result) {
18778            if (sb.length() > 0) sb.append(" ");
18779            sb.append(domain);
18780        }
18781        return sb.toString();
18782    }
18783
18784    // ------- apps on sdcard specific code -------
18785    static final boolean DEBUG_SD_INSTALL = false;
18786
18787    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18788
18789    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18790
18791    private boolean mMediaMounted = false;
18792
18793    static String getEncryptKey() {
18794        try {
18795            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18796                    SD_ENCRYPTION_KEYSTORE_NAME);
18797            if (sdEncKey == null) {
18798                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18799                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18800                if (sdEncKey == null) {
18801                    Slog.e(TAG, "Failed to create encryption keys");
18802                    return null;
18803                }
18804            }
18805            return sdEncKey;
18806        } catch (NoSuchAlgorithmException nsae) {
18807            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18808            return null;
18809        } catch (IOException ioe) {
18810            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18811            return null;
18812        }
18813    }
18814
18815    /*
18816     * Update media status on PackageManager.
18817     */
18818    @Override
18819    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18820        int callingUid = Binder.getCallingUid();
18821        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18822            throw new SecurityException("Media status can only be updated by the system");
18823        }
18824        // reader; this apparently protects mMediaMounted, but should probably
18825        // be a different lock in that case.
18826        synchronized (mPackages) {
18827            Log.i(TAG, "Updating external media status from "
18828                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18829                    + (mediaStatus ? "mounted" : "unmounted"));
18830            if (DEBUG_SD_INSTALL)
18831                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18832                        + ", mMediaMounted=" + mMediaMounted);
18833            if (mediaStatus == mMediaMounted) {
18834                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18835                        : 0, -1);
18836                mHandler.sendMessage(msg);
18837                return;
18838            }
18839            mMediaMounted = mediaStatus;
18840        }
18841        // Queue up an async operation since the package installation may take a
18842        // little while.
18843        mHandler.post(new Runnable() {
18844            public void run() {
18845                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18846            }
18847        });
18848    }
18849
18850    /**
18851     * Called by MountService when the initial ASECs to scan are available.
18852     * Should block until all the ASEC containers are finished being scanned.
18853     */
18854    public void scanAvailableAsecs() {
18855        updateExternalMediaStatusInner(true, false, false);
18856    }
18857
18858    /*
18859     * Collect information of applications on external media, map them against
18860     * existing containers and update information based on current mount status.
18861     * Please note that we always have to report status if reportStatus has been
18862     * set to true especially when unloading packages.
18863     */
18864    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18865            boolean externalStorage) {
18866        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18867        int[] uidArr = EmptyArray.INT;
18868
18869        final String[] list = PackageHelper.getSecureContainerList();
18870        if (ArrayUtils.isEmpty(list)) {
18871            Log.i(TAG, "No secure containers found");
18872        } else {
18873            // Process list of secure containers and categorize them
18874            // as active or stale based on their package internal state.
18875
18876            // reader
18877            synchronized (mPackages) {
18878                for (String cid : list) {
18879                    // Leave stages untouched for now; installer service owns them
18880                    if (PackageInstallerService.isStageName(cid)) continue;
18881
18882                    if (DEBUG_SD_INSTALL)
18883                        Log.i(TAG, "Processing container " + cid);
18884                    String pkgName = getAsecPackageName(cid);
18885                    if (pkgName == null) {
18886                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18887                        continue;
18888                    }
18889                    if (DEBUG_SD_INSTALL)
18890                        Log.i(TAG, "Looking for pkg : " + pkgName);
18891
18892                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18893                    if (ps == null) {
18894                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18895                        continue;
18896                    }
18897
18898                    /*
18899                     * Skip packages that are not external if we're unmounting
18900                     * external storage.
18901                     */
18902                    if (externalStorage && !isMounted && !isExternal(ps)) {
18903                        continue;
18904                    }
18905
18906                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18907                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18908                    // The package status is changed only if the code path
18909                    // matches between settings and the container id.
18910                    if (ps.codePathString != null
18911                            && ps.codePathString.startsWith(args.getCodePath())) {
18912                        if (DEBUG_SD_INSTALL) {
18913                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18914                                    + " at code path: " + ps.codePathString);
18915                        }
18916
18917                        // We do have a valid package installed on sdcard
18918                        processCids.put(args, ps.codePathString);
18919                        final int uid = ps.appId;
18920                        if (uid != -1) {
18921                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18922                        }
18923                    } else {
18924                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18925                                + ps.codePathString);
18926                    }
18927                }
18928            }
18929
18930            Arrays.sort(uidArr);
18931        }
18932
18933        // Process packages with valid entries.
18934        if (isMounted) {
18935            if (DEBUG_SD_INSTALL)
18936                Log.i(TAG, "Loading packages");
18937            loadMediaPackages(processCids, uidArr, externalStorage);
18938            startCleaningPackages();
18939            mInstallerService.onSecureContainersAvailable();
18940        } else {
18941            if (DEBUG_SD_INSTALL)
18942                Log.i(TAG, "Unloading packages");
18943            unloadMediaPackages(processCids, uidArr, reportStatus);
18944        }
18945    }
18946
18947    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18948            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18949        final int size = infos.size();
18950        final String[] packageNames = new String[size];
18951        final int[] packageUids = new int[size];
18952        for (int i = 0; i < size; i++) {
18953            final ApplicationInfo info = infos.get(i);
18954            packageNames[i] = info.packageName;
18955            packageUids[i] = info.uid;
18956        }
18957        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18958                finishedReceiver);
18959    }
18960
18961    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18962            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18963        sendResourcesChangedBroadcast(mediaStatus, replacing,
18964                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18965    }
18966
18967    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18968            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18969        int size = pkgList.length;
18970        if (size > 0) {
18971            // Send broadcasts here
18972            Bundle extras = new Bundle();
18973            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18974            if (uidArr != null) {
18975                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18976            }
18977            if (replacing) {
18978                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18979            }
18980            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18981                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18982            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18983        }
18984    }
18985
18986   /*
18987     * Look at potentially valid container ids from processCids If package
18988     * information doesn't match the one on record or package scanning fails,
18989     * the cid is added to list of removeCids. We currently don't delete stale
18990     * containers.
18991     */
18992    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18993            boolean externalStorage) {
18994        ArrayList<String> pkgList = new ArrayList<String>();
18995        Set<AsecInstallArgs> keys = processCids.keySet();
18996
18997        for (AsecInstallArgs args : keys) {
18998            String codePath = processCids.get(args);
18999            if (DEBUG_SD_INSTALL)
19000                Log.i(TAG, "Loading container : " + args.cid);
19001            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19002            try {
19003                // Make sure there are no container errors first.
19004                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19005                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19006                            + " when installing from sdcard");
19007                    continue;
19008                }
19009                // Check code path here.
19010                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19011                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19012                            + " does not match one in settings " + codePath);
19013                    continue;
19014                }
19015                // Parse package
19016                int parseFlags = mDefParseFlags;
19017                if (args.isExternalAsec()) {
19018                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19019                }
19020                if (args.isFwdLocked()) {
19021                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19022                }
19023
19024                synchronized (mInstallLock) {
19025                    PackageParser.Package pkg = null;
19026                    try {
19027                        // Sadly we don't know the package name yet to freeze it
19028                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19029                                SCAN_IGNORE_FROZEN, 0, null);
19030                    } catch (PackageManagerException e) {
19031                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19032                    }
19033                    // Scan the package
19034                    if (pkg != null) {
19035                        /*
19036                         * TODO why is the lock being held? doPostInstall is
19037                         * called in other places without the lock. This needs
19038                         * to be straightened out.
19039                         */
19040                        // writer
19041                        synchronized (mPackages) {
19042                            retCode = PackageManager.INSTALL_SUCCEEDED;
19043                            pkgList.add(pkg.packageName);
19044                            // Post process args
19045                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19046                                    pkg.applicationInfo.uid);
19047                        }
19048                    } else {
19049                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19050                    }
19051                }
19052
19053            } finally {
19054                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19055                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19056                }
19057            }
19058        }
19059        // writer
19060        synchronized (mPackages) {
19061            // If the platform SDK has changed since the last time we booted,
19062            // we need to re-grant app permission to catch any new ones that
19063            // appear. This is really a hack, and means that apps can in some
19064            // cases get permissions that the user didn't initially explicitly
19065            // allow... it would be nice to have some better way to handle
19066            // this situation.
19067            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19068                    : mSettings.getInternalVersion();
19069            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19070                    : StorageManager.UUID_PRIVATE_INTERNAL;
19071
19072            int updateFlags = UPDATE_PERMISSIONS_ALL;
19073            if (ver.sdkVersion != mSdkVersion) {
19074                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19075                        + mSdkVersion + "; regranting permissions for external");
19076                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19077            }
19078            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19079
19080            // Yay, everything is now upgraded
19081            ver.forceCurrent();
19082
19083            // can downgrade to reader
19084            // Persist settings
19085            mSettings.writeLPr();
19086        }
19087        // Send a broadcast to let everyone know we are done processing
19088        if (pkgList.size() > 0) {
19089            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19090        }
19091    }
19092
19093   /*
19094     * Utility method to unload a list of specified containers
19095     */
19096    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19097        // Just unmount all valid containers.
19098        for (AsecInstallArgs arg : cidArgs) {
19099            synchronized (mInstallLock) {
19100                arg.doPostDeleteLI(false);
19101           }
19102       }
19103   }
19104
19105    /*
19106     * Unload packages mounted on external media. This involves deleting package
19107     * data from internal structures, sending broadcasts about disabled packages,
19108     * gc'ing to free up references, unmounting all secure containers
19109     * corresponding to packages on external media, and posting a
19110     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19111     * that we always have to post this message if status has been requested no
19112     * matter what.
19113     */
19114    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19115            final boolean reportStatus) {
19116        if (DEBUG_SD_INSTALL)
19117            Log.i(TAG, "unloading media packages");
19118        ArrayList<String> pkgList = new ArrayList<String>();
19119        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19120        final Set<AsecInstallArgs> keys = processCids.keySet();
19121        for (AsecInstallArgs args : keys) {
19122            String pkgName = args.getPackageName();
19123            if (DEBUG_SD_INSTALL)
19124                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19125            // Delete package internally
19126            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19127            synchronized (mInstallLock) {
19128                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19129                final boolean res;
19130                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19131                        "unloadMediaPackages")) {
19132                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19133                            null);
19134                }
19135                if (res) {
19136                    pkgList.add(pkgName);
19137                } else {
19138                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19139                    failedList.add(args);
19140                }
19141            }
19142        }
19143
19144        // reader
19145        synchronized (mPackages) {
19146            // We didn't update the settings after removing each package;
19147            // write them now for all packages.
19148            mSettings.writeLPr();
19149        }
19150
19151        // We have to absolutely send UPDATED_MEDIA_STATUS only
19152        // after confirming that all the receivers processed the ordered
19153        // broadcast when packages get disabled, force a gc to clean things up.
19154        // and unload all the containers.
19155        if (pkgList.size() > 0) {
19156            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19157                    new IIntentReceiver.Stub() {
19158                public void performReceive(Intent intent, int resultCode, String data,
19159                        Bundle extras, boolean ordered, boolean sticky,
19160                        int sendingUser) throws RemoteException {
19161                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19162                            reportStatus ? 1 : 0, 1, keys);
19163                    mHandler.sendMessage(msg);
19164                }
19165            });
19166        } else {
19167            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19168                    keys);
19169            mHandler.sendMessage(msg);
19170        }
19171    }
19172
19173    private void loadPrivatePackages(final VolumeInfo vol) {
19174        mHandler.post(new Runnable() {
19175            @Override
19176            public void run() {
19177                loadPrivatePackagesInner(vol);
19178            }
19179        });
19180    }
19181
19182    private void loadPrivatePackagesInner(VolumeInfo vol) {
19183        final String volumeUuid = vol.fsUuid;
19184        if (TextUtils.isEmpty(volumeUuid)) {
19185            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19186            return;
19187        }
19188
19189        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19190        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19191        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19192
19193        final VersionInfo ver;
19194        final List<PackageSetting> packages;
19195        synchronized (mPackages) {
19196            ver = mSettings.findOrCreateVersion(volumeUuid);
19197            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19198        }
19199
19200        for (PackageSetting ps : packages) {
19201            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19202            synchronized (mInstallLock) {
19203                final PackageParser.Package pkg;
19204                try {
19205                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19206                    loaded.add(pkg.applicationInfo);
19207
19208                } catch (PackageManagerException e) {
19209                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19210                }
19211
19212                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19213                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19214                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19215                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19216                }
19217            }
19218        }
19219
19220        // Reconcile app data for all started/unlocked users
19221        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19222        final UserManager um = mContext.getSystemService(UserManager.class);
19223        UserManagerInternal umInternal = getUserManagerInternal();
19224        for (UserInfo user : um.getUsers()) {
19225            final int flags;
19226            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19227                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19228            } else if (umInternal.isUserRunning(user.id)) {
19229                flags = StorageManager.FLAG_STORAGE_DE;
19230            } else {
19231                continue;
19232            }
19233
19234            try {
19235                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19236                synchronized (mInstallLock) {
19237                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19238                }
19239            } catch (IllegalStateException e) {
19240                // Device was probably ejected, and we'll process that event momentarily
19241                Slog.w(TAG, "Failed to prepare storage: " + e);
19242            }
19243        }
19244
19245        synchronized (mPackages) {
19246            int updateFlags = UPDATE_PERMISSIONS_ALL;
19247            if (ver.sdkVersion != mSdkVersion) {
19248                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19249                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19250                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19251            }
19252            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19253
19254            // Yay, everything is now upgraded
19255            ver.forceCurrent();
19256
19257            mSettings.writeLPr();
19258        }
19259
19260        for (PackageFreezer freezer : freezers) {
19261            freezer.close();
19262        }
19263
19264        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19265        sendResourcesChangedBroadcast(true, false, loaded, null);
19266    }
19267
19268    private void unloadPrivatePackages(final VolumeInfo vol) {
19269        mHandler.post(new Runnable() {
19270            @Override
19271            public void run() {
19272                unloadPrivatePackagesInner(vol);
19273            }
19274        });
19275    }
19276
19277    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19278        final String volumeUuid = vol.fsUuid;
19279        if (TextUtils.isEmpty(volumeUuid)) {
19280            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19281            return;
19282        }
19283
19284        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19285        synchronized (mInstallLock) {
19286        synchronized (mPackages) {
19287            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19288            for (PackageSetting ps : packages) {
19289                if (ps.pkg == null) continue;
19290
19291                final ApplicationInfo info = ps.pkg.applicationInfo;
19292                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19293                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19294
19295                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19296                        "unloadPrivatePackagesInner")) {
19297                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19298                            false, null)) {
19299                        unloaded.add(info);
19300                    } else {
19301                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19302                    }
19303                }
19304
19305                // Try very hard to release any references to this package
19306                // so we don't risk the system server being killed due to
19307                // open FDs
19308                AttributeCache.instance().removePackage(ps.name);
19309            }
19310
19311            mSettings.writeLPr();
19312        }
19313        }
19314
19315        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19316        sendResourcesChangedBroadcast(false, false, unloaded, null);
19317
19318        // Try very hard to release any references to this path so we don't risk
19319        // the system server being killed due to open FDs
19320        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19321
19322        for (int i = 0; i < 3; i++) {
19323            System.gc();
19324            System.runFinalization();
19325        }
19326    }
19327
19328    /**
19329     * Prepare storage areas for given user on all mounted devices.
19330     */
19331    void prepareUserData(int userId, int userSerial, int flags) {
19332        synchronized (mInstallLock) {
19333            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19334            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19335                final String volumeUuid = vol.getFsUuid();
19336                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19337            }
19338        }
19339    }
19340
19341    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19342            boolean allowRecover) {
19343        // Prepare storage and verify that serial numbers are consistent; if
19344        // there's a mismatch we need to destroy to avoid leaking data
19345        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19346        try {
19347            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19348
19349            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19350                UserManagerService.enforceSerialNumber(
19351                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19352                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19353                    UserManagerService.enforceSerialNumber(
19354                            Environment.getDataSystemDeDirectory(userId), userSerial);
19355                }
19356            }
19357            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19358                UserManagerService.enforceSerialNumber(
19359                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19360                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19361                    UserManagerService.enforceSerialNumber(
19362                            Environment.getDataSystemCeDirectory(userId), userSerial);
19363                }
19364            }
19365
19366            synchronized (mInstallLock) {
19367                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19368            }
19369        } catch (Exception e) {
19370            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19371                    + " because we failed to prepare: " + e);
19372            destroyUserDataLI(volumeUuid, userId,
19373                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19374
19375            if (allowRecover) {
19376                // Try one last time; if we fail again we're really in trouble
19377                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19378            }
19379        }
19380    }
19381
19382    /**
19383     * Destroy storage areas for given user on all mounted devices.
19384     */
19385    void destroyUserData(int userId, int flags) {
19386        synchronized (mInstallLock) {
19387            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19388            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19389                final String volumeUuid = vol.getFsUuid();
19390                destroyUserDataLI(volumeUuid, userId, flags);
19391            }
19392        }
19393    }
19394
19395    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19396        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19397        try {
19398            // Clean up app data, profile data, and media data
19399            mInstaller.destroyUserData(volumeUuid, userId, flags);
19400
19401            // Clean up system data
19402            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19403                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19404                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19405                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19406                }
19407                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19408                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19409                }
19410            }
19411
19412            // Data with special labels is now gone, so finish the job
19413            storage.destroyUserStorage(volumeUuid, userId, flags);
19414
19415        } catch (Exception e) {
19416            logCriticalInfo(Log.WARN,
19417                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19418        }
19419    }
19420
19421    /**
19422     * Examine all users present on given mounted volume, and destroy data
19423     * belonging to users that are no longer valid, or whose user ID has been
19424     * recycled.
19425     */
19426    private void reconcileUsers(String volumeUuid) {
19427        final List<File> files = new ArrayList<>();
19428        Collections.addAll(files, FileUtils
19429                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19430        Collections.addAll(files, FileUtils
19431                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19432        Collections.addAll(files, FileUtils
19433                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19434        Collections.addAll(files, FileUtils
19435                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19436        for (File file : files) {
19437            if (!file.isDirectory()) continue;
19438
19439            final int userId;
19440            final UserInfo info;
19441            try {
19442                userId = Integer.parseInt(file.getName());
19443                info = sUserManager.getUserInfo(userId);
19444            } catch (NumberFormatException e) {
19445                Slog.w(TAG, "Invalid user directory " + file);
19446                continue;
19447            }
19448
19449            boolean destroyUser = false;
19450            if (info == null) {
19451                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19452                        + " because no matching user was found");
19453                destroyUser = true;
19454            } else if (!mOnlyCore) {
19455                try {
19456                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19457                } catch (IOException e) {
19458                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19459                            + " because we failed to enforce serial number: " + e);
19460                    destroyUser = true;
19461                }
19462            }
19463
19464            if (destroyUser) {
19465                synchronized (mInstallLock) {
19466                    destroyUserDataLI(volumeUuid, userId,
19467                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19468                }
19469            }
19470        }
19471    }
19472
19473    private void assertPackageKnown(String volumeUuid, String packageName)
19474            throws PackageManagerException {
19475        synchronized (mPackages) {
19476            final PackageSetting ps = mSettings.mPackages.get(packageName);
19477            if (ps == null) {
19478                throw new PackageManagerException("Package " + packageName + " is unknown");
19479            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19480                throw new PackageManagerException(
19481                        "Package " + packageName + " found on unknown volume " + volumeUuid
19482                                + "; expected volume " + ps.volumeUuid);
19483            }
19484        }
19485    }
19486
19487    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19488            throws PackageManagerException {
19489        synchronized (mPackages) {
19490            final PackageSetting ps = mSettings.mPackages.get(packageName);
19491            if (ps == null) {
19492                throw new PackageManagerException("Package " + packageName + " is unknown");
19493            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19494                throw new PackageManagerException(
19495                        "Package " + packageName + " found on unknown volume " + volumeUuid
19496                                + "; expected volume " + ps.volumeUuid);
19497            } else if (!ps.getInstalled(userId)) {
19498                throw new PackageManagerException(
19499                        "Package " + packageName + " not installed for user " + userId);
19500            }
19501        }
19502    }
19503
19504    /**
19505     * Examine all apps present on given mounted volume, and destroy apps that
19506     * aren't expected, either due to uninstallation or reinstallation on
19507     * another volume.
19508     */
19509    private void reconcileApps(String volumeUuid) {
19510        final File[] files = FileUtils
19511                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19512        for (File file : files) {
19513            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19514                    && !PackageInstallerService.isStageName(file.getName());
19515            if (!isPackage) {
19516                // Ignore entries which are not packages
19517                continue;
19518            }
19519
19520            try {
19521                final PackageLite pkg = PackageParser.parsePackageLite(file,
19522                        PackageParser.PARSE_MUST_BE_APK);
19523                assertPackageKnown(volumeUuid, pkg.packageName);
19524
19525            } catch (PackageParserException | PackageManagerException e) {
19526                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19527                synchronized (mInstallLock) {
19528                    removeCodePathLI(file);
19529                }
19530            }
19531        }
19532    }
19533
19534    /**
19535     * Reconcile all app data for the given user.
19536     * <p>
19537     * Verifies that directories exist and that ownership and labeling is
19538     * correct for all installed apps on all mounted volumes.
19539     */
19540    void reconcileAppsData(int userId, int flags) {
19541        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19542        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19543            final String volumeUuid = vol.getFsUuid();
19544            synchronized (mInstallLock) {
19545                reconcileAppsDataLI(volumeUuid, userId, flags);
19546            }
19547        }
19548    }
19549
19550    /**
19551     * Reconcile all app data on given mounted volume.
19552     * <p>
19553     * Destroys app data that isn't expected, either due to uninstallation or
19554     * reinstallation on another volume.
19555     * <p>
19556     * Verifies that directories exist and that ownership and labeling is
19557     * correct for all installed apps.
19558     */
19559    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19560        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19561                + Integer.toHexString(flags));
19562
19563        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19564        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19565
19566        boolean restoreconNeeded = false;
19567
19568        // First look for stale data that doesn't belong, and check if things
19569        // have changed since we did our last restorecon
19570        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19571            if (StorageManager.isFileEncryptedNativeOrEmulated()
19572                    && !StorageManager.isUserKeyUnlocked(userId)) {
19573                throw new RuntimeException(
19574                        "Yikes, someone asked us to reconcile CE storage while " + userId
19575                                + " was still locked; this would have caused massive data loss!");
19576            }
19577
19578            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19579
19580            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19581            for (File file : files) {
19582                final String packageName = file.getName();
19583                try {
19584                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19585                } catch (PackageManagerException e) {
19586                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19587                    try {
19588                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19589                                StorageManager.FLAG_STORAGE_CE, 0);
19590                    } catch (InstallerException e2) {
19591                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19592                    }
19593                }
19594            }
19595        }
19596        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19597            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19598
19599            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19600            for (File file : files) {
19601                final String packageName = file.getName();
19602                try {
19603                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19604                } catch (PackageManagerException e) {
19605                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19606                    try {
19607                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19608                                StorageManager.FLAG_STORAGE_DE, 0);
19609                    } catch (InstallerException e2) {
19610                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19611                    }
19612                }
19613            }
19614        }
19615
19616        // Ensure that data directories are ready to roll for all packages
19617        // installed for this volume and user
19618        final List<PackageSetting> packages;
19619        synchronized (mPackages) {
19620            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19621        }
19622        int preparedCount = 0;
19623        for (PackageSetting ps : packages) {
19624            final String packageName = ps.name;
19625            if (ps.pkg == null) {
19626                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19627                // TODO: might be due to legacy ASEC apps; we should circle back
19628                // and reconcile again once they're scanned
19629                continue;
19630            }
19631
19632            if (ps.getInstalled(userId)) {
19633                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19634
19635                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19636                    // We may have just shuffled around app data directories, so
19637                    // prepare them one more time
19638                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19639                }
19640
19641                preparedCount++;
19642            }
19643        }
19644
19645        if (restoreconNeeded) {
19646            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19647                SELinuxMMAC.setRestoreconDone(ceDir);
19648            }
19649            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19650                SELinuxMMAC.setRestoreconDone(deDir);
19651            }
19652        }
19653
19654        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19655                + " packages; restoreconNeeded was " + restoreconNeeded);
19656    }
19657
19658    /**
19659     * Prepare app data for the given app just after it was installed or
19660     * upgraded. This method carefully only touches users that it's installed
19661     * for, and it forces a restorecon to handle any seinfo changes.
19662     * <p>
19663     * Verifies that directories exist and that ownership and labeling is
19664     * correct for all installed apps. If there is an ownership mismatch, it
19665     * will try recovering system apps by wiping data; third-party app data is
19666     * left intact.
19667     * <p>
19668     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19669     */
19670    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19671        final PackageSetting ps;
19672        synchronized (mPackages) {
19673            ps = mSettings.mPackages.get(pkg.packageName);
19674            mSettings.writeKernelMappingLPr(ps);
19675        }
19676
19677        final UserManager um = mContext.getSystemService(UserManager.class);
19678        UserManagerInternal umInternal = getUserManagerInternal();
19679        for (UserInfo user : um.getUsers()) {
19680            final int flags;
19681            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19682                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19683            } else if (umInternal.isUserRunning(user.id)) {
19684                flags = StorageManager.FLAG_STORAGE_DE;
19685            } else {
19686                continue;
19687            }
19688
19689            if (ps.getInstalled(user.id)) {
19690                // Whenever an app changes, force a restorecon of its data
19691                // TODO: when user data is locked, mark that we're still dirty
19692                prepareAppDataLIF(pkg, user.id, flags, true);
19693            }
19694        }
19695    }
19696
19697    /**
19698     * Prepare app data for the given app.
19699     * <p>
19700     * Verifies that directories exist and that ownership and labeling is
19701     * correct for all installed apps. If there is an ownership mismatch, this
19702     * will try recovering system apps by wiping data; third-party app data is
19703     * left intact.
19704     */
19705    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19706            boolean restoreconNeeded) {
19707        if (pkg == null) {
19708            Slog.wtf(TAG, "Package was null!", new Throwable());
19709            return;
19710        }
19711        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19712        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19713        for (int i = 0; i < childCount; i++) {
19714            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19715        }
19716    }
19717
19718    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19719            boolean restoreconNeeded) {
19720        if (DEBUG_APP_DATA) {
19721            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19722                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19723        }
19724
19725        final String volumeUuid = pkg.volumeUuid;
19726        final String packageName = pkg.packageName;
19727        final ApplicationInfo app = pkg.applicationInfo;
19728        final int appId = UserHandle.getAppId(app.uid);
19729
19730        Preconditions.checkNotNull(app.seinfo);
19731
19732        try {
19733            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19734                    appId, app.seinfo, app.targetSdkVersion);
19735        } catch (InstallerException e) {
19736            if (app.isSystemApp()) {
19737                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19738                        + ", but trying to recover: " + e);
19739                destroyAppDataLeafLIF(pkg, userId, flags);
19740                try {
19741                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19742                            appId, app.seinfo, app.targetSdkVersion);
19743                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19744                } catch (InstallerException e2) {
19745                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19746                }
19747            } else {
19748                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19749            }
19750        }
19751
19752        if (restoreconNeeded) {
19753            try {
19754                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19755                        app.seinfo);
19756            } catch (InstallerException e) {
19757                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19758            }
19759        }
19760
19761        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19762            try {
19763                // CE storage is unlocked right now, so read out the inode and
19764                // remember for use later when it's locked
19765                // TODO: mark this structure as dirty so we persist it!
19766                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19767                        StorageManager.FLAG_STORAGE_CE);
19768                synchronized (mPackages) {
19769                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19770                    if (ps != null) {
19771                        ps.setCeDataInode(ceDataInode, userId);
19772                    }
19773                }
19774            } catch (InstallerException e) {
19775                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19776            }
19777        }
19778
19779        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19780    }
19781
19782    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19783        if (pkg == null) {
19784            Slog.wtf(TAG, "Package was null!", new Throwable());
19785            return;
19786        }
19787        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19788        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19789        for (int i = 0; i < childCount; i++) {
19790            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19791        }
19792    }
19793
19794    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19795        final String volumeUuid = pkg.volumeUuid;
19796        final String packageName = pkg.packageName;
19797        final ApplicationInfo app = pkg.applicationInfo;
19798
19799        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19800            // Create a native library symlink only if we have native libraries
19801            // and if the native libraries are 32 bit libraries. We do not provide
19802            // this symlink for 64 bit libraries.
19803            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19804                final String nativeLibPath = app.nativeLibraryDir;
19805                try {
19806                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19807                            nativeLibPath, userId);
19808                } catch (InstallerException e) {
19809                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19810                }
19811            }
19812        }
19813    }
19814
19815    /**
19816     * For system apps on non-FBE devices, this method migrates any existing
19817     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19818     * requested by the app.
19819     */
19820    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19821        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19822                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19823            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19824                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19825            try {
19826                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19827                        storageTarget);
19828            } catch (InstallerException e) {
19829                logCriticalInfo(Log.WARN,
19830                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19831            }
19832            return true;
19833        } else {
19834            return false;
19835        }
19836    }
19837
19838    public PackageFreezer freezePackage(String packageName, String killReason) {
19839        return new PackageFreezer(packageName, killReason);
19840    }
19841
19842    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19843            String killReason) {
19844        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19845            return new PackageFreezer();
19846        } else {
19847            return freezePackage(packageName, killReason);
19848        }
19849    }
19850
19851    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19852            String killReason) {
19853        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19854            return new PackageFreezer();
19855        } else {
19856            return freezePackage(packageName, killReason);
19857        }
19858    }
19859
19860    /**
19861     * Class that freezes and kills the given package upon creation, and
19862     * unfreezes it upon closing. This is typically used when doing surgery on
19863     * app code/data to prevent the app from running while you're working.
19864     */
19865    private class PackageFreezer implements AutoCloseable {
19866        private final String mPackageName;
19867        private final PackageFreezer[] mChildren;
19868
19869        private final boolean mWeFroze;
19870
19871        private final AtomicBoolean mClosed = new AtomicBoolean();
19872        private final CloseGuard mCloseGuard = CloseGuard.get();
19873
19874        /**
19875         * Create and return a stub freezer that doesn't actually do anything,
19876         * typically used when someone requested
19877         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19878         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19879         */
19880        public PackageFreezer() {
19881            mPackageName = null;
19882            mChildren = null;
19883            mWeFroze = false;
19884            mCloseGuard.open("close");
19885        }
19886
19887        public PackageFreezer(String packageName, String killReason) {
19888            synchronized (mPackages) {
19889                mPackageName = packageName;
19890                mWeFroze = mFrozenPackages.add(mPackageName);
19891
19892                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19893                if (ps != null) {
19894                    killApplication(ps.name, ps.appId, killReason);
19895                }
19896
19897                final PackageParser.Package p = mPackages.get(packageName);
19898                if (p != null && p.childPackages != null) {
19899                    final int N = p.childPackages.size();
19900                    mChildren = new PackageFreezer[N];
19901                    for (int i = 0; i < N; i++) {
19902                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19903                                killReason);
19904                    }
19905                } else {
19906                    mChildren = null;
19907                }
19908            }
19909            mCloseGuard.open("close");
19910        }
19911
19912        @Override
19913        protected void finalize() throws Throwable {
19914            try {
19915                mCloseGuard.warnIfOpen();
19916                close();
19917            } finally {
19918                super.finalize();
19919            }
19920        }
19921
19922        @Override
19923        public void close() {
19924            mCloseGuard.close();
19925            if (mClosed.compareAndSet(false, true)) {
19926                synchronized (mPackages) {
19927                    if (mWeFroze) {
19928                        mFrozenPackages.remove(mPackageName);
19929                    }
19930
19931                    if (mChildren != null) {
19932                        for (PackageFreezer freezer : mChildren) {
19933                            freezer.close();
19934                        }
19935                    }
19936                }
19937            }
19938        }
19939    }
19940
19941    /**
19942     * Verify that given package is currently frozen.
19943     */
19944    private void checkPackageFrozen(String packageName) {
19945        synchronized (mPackages) {
19946            if (!mFrozenPackages.contains(packageName)) {
19947                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19948            }
19949        }
19950    }
19951
19952    @Override
19953    public int movePackage(final String packageName, final String volumeUuid) {
19954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19955
19956        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19957        final int moveId = mNextMoveId.getAndIncrement();
19958        mHandler.post(new Runnable() {
19959            @Override
19960            public void run() {
19961                try {
19962                    movePackageInternal(packageName, volumeUuid, moveId, user);
19963                } catch (PackageManagerException e) {
19964                    Slog.w(TAG, "Failed to move " + packageName, e);
19965                    mMoveCallbacks.notifyStatusChanged(moveId,
19966                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19967                }
19968            }
19969        });
19970        return moveId;
19971    }
19972
19973    private void movePackageInternal(final String packageName, final String volumeUuid,
19974            final int moveId, UserHandle user) throws PackageManagerException {
19975        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19976        final PackageManager pm = mContext.getPackageManager();
19977
19978        final boolean currentAsec;
19979        final String currentVolumeUuid;
19980        final File codeFile;
19981        final String installerPackageName;
19982        final String packageAbiOverride;
19983        final int appId;
19984        final String seinfo;
19985        final String label;
19986        final int targetSdkVersion;
19987        final PackageFreezer freezer;
19988        final int[] installedUserIds;
19989
19990        // reader
19991        synchronized (mPackages) {
19992            final PackageParser.Package pkg = mPackages.get(packageName);
19993            final PackageSetting ps = mSettings.mPackages.get(packageName);
19994            if (pkg == null || ps == null) {
19995                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19996            }
19997
19998            if (pkg.applicationInfo.isSystemApp()) {
19999                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20000                        "Cannot move system application");
20001            }
20002
20003            if (pkg.applicationInfo.isExternalAsec()) {
20004                currentAsec = true;
20005                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20006            } else if (pkg.applicationInfo.isForwardLocked()) {
20007                currentAsec = true;
20008                currentVolumeUuid = "forward_locked";
20009            } else {
20010                currentAsec = false;
20011                currentVolumeUuid = ps.volumeUuid;
20012
20013                final File probe = new File(pkg.codePath);
20014                final File probeOat = new File(probe, "oat");
20015                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20016                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20017                            "Move only supported for modern cluster style installs");
20018                }
20019            }
20020
20021            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20022                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20023                        "Package already moved to " + volumeUuid);
20024            }
20025            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20026                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20027                        "Device admin cannot be moved");
20028            }
20029
20030            if (mFrozenPackages.contains(packageName)) {
20031                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20032                        "Failed to move already frozen package");
20033            }
20034
20035            codeFile = new File(pkg.codePath);
20036            installerPackageName = ps.installerPackageName;
20037            packageAbiOverride = ps.cpuAbiOverrideString;
20038            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20039            seinfo = pkg.applicationInfo.seinfo;
20040            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20041            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20042            freezer = new PackageFreezer(packageName, "movePackageInternal");
20043            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20044        }
20045
20046        final Bundle extras = new Bundle();
20047        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20048        extras.putString(Intent.EXTRA_TITLE, label);
20049        mMoveCallbacks.notifyCreated(moveId, extras);
20050
20051        int installFlags;
20052        final boolean moveCompleteApp;
20053        final File measurePath;
20054
20055        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20056            installFlags = INSTALL_INTERNAL;
20057            moveCompleteApp = !currentAsec;
20058            measurePath = Environment.getDataAppDirectory(volumeUuid);
20059        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20060            installFlags = INSTALL_EXTERNAL;
20061            moveCompleteApp = false;
20062            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20063        } else {
20064            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20065            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20066                    || !volume.isMountedWritable()) {
20067                freezer.close();
20068                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20069                        "Move location not mounted private volume");
20070            }
20071
20072            Preconditions.checkState(!currentAsec);
20073
20074            installFlags = INSTALL_INTERNAL;
20075            moveCompleteApp = true;
20076            measurePath = Environment.getDataAppDirectory(volumeUuid);
20077        }
20078
20079        final PackageStats stats = new PackageStats(null, -1);
20080        synchronized (mInstaller) {
20081            for (int userId : installedUserIds) {
20082                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20083                    freezer.close();
20084                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20085                            "Failed to measure package size");
20086                }
20087            }
20088        }
20089
20090        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20091                + stats.dataSize);
20092
20093        final long startFreeBytes = measurePath.getFreeSpace();
20094        final long sizeBytes;
20095        if (moveCompleteApp) {
20096            sizeBytes = stats.codeSize + stats.dataSize;
20097        } else {
20098            sizeBytes = stats.codeSize;
20099        }
20100
20101        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20102            freezer.close();
20103            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20104                    "Not enough free space to move");
20105        }
20106
20107        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20108
20109        final CountDownLatch installedLatch = new CountDownLatch(1);
20110        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20111            @Override
20112            public void onUserActionRequired(Intent intent) throws RemoteException {
20113                throw new IllegalStateException();
20114            }
20115
20116            @Override
20117            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20118                    Bundle extras) throws RemoteException {
20119                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20120                        + PackageManager.installStatusToString(returnCode, msg));
20121
20122                installedLatch.countDown();
20123                freezer.close();
20124
20125                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20126                switch (status) {
20127                    case PackageInstaller.STATUS_SUCCESS:
20128                        mMoveCallbacks.notifyStatusChanged(moveId,
20129                                PackageManager.MOVE_SUCCEEDED);
20130                        break;
20131                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20132                        mMoveCallbacks.notifyStatusChanged(moveId,
20133                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20134                        break;
20135                    default:
20136                        mMoveCallbacks.notifyStatusChanged(moveId,
20137                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20138                        break;
20139                }
20140            }
20141        };
20142
20143        final MoveInfo move;
20144        if (moveCompleteApp) {
20145            // Kick off a thread to report progress estimates
20146            new Thread() {
20147                @Override
20148                public void run() {
20149                    while (true) {
20150                        try {
20151                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20152                                break;
20153                            }
20154                        } catch (InterruptedException ignored) {
20155                        }
20156
20157                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20158                        final int progress = 10 + (int) MathUtils.constrain(
20159                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20160                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20161                    }
20162                }
20163            }.start();
20164
20165            final String dataAppName = codeFile.getName();
20166            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20167                    dataAppName, appId, seinfo, targetSdkVersion);
20168        } else {
20169            move = null;
20170        }
20171
20172        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20173
20174        final Message msg = mHandler.obtainMessage(INIT_COPY);
20175        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20176        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20177                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20178                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20179        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20180        msg.obj = params;
20181
20182        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20183                System.identityHashCode(msg.obj));
20184        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20185                System.identityHashCode(msg.obj));
20186
20187        mHandler.sendMessage(msg);
20188    }
20189
20190    @Override
20191    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20193
20194        final int realMoveId = mNextMoveId.getAndIncrement();
20195        final Bundle extras = new Bundle();
20196        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20197        mMoveCallbacks.notifyCreated(realMoveId, extras);
20198
20199        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20200            @Override
20201            public void onCreated(int moveId, Bundle extras) {
20202                // Ignored
20203            }
20204
20205            @Override
20206            public void onStatusChanged(int moveId, int status, long estMillis) {
20207                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20208            }
20209        };
20210
20211        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20212        storage.setPrimaryStorageUuid(volumeUuid, callback);
20213        return realMoveId;
20214    }
20215
20216    @Override
20217    public int getMoveStatus(int moveId) {
20218        mContext.enforceCallingOrSelfPermission(
20219                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20220        return mMoveCallbacks.mLastStatus.get(moveId);
20221    }
20222
20223    @Override
20224    public void registerMoveCallback(IPackageMoveObserver callback) {
20225        mContext.enforceCallingOrSelfPermission(
20226                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20227        mMoveCallbacks.register(callback);
20228    }
20229
20230    @Override
20231    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20232        mContext.enforceCallingOrSelfPermission(
20233                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20234        mMoveCallbacks.unregister(callback);
20235    }
20236
20237    @Override
20238    public boolean setInstallLocation(int loc) {
20239        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20240                null);
20241        if (getInstallLocation() == loc) {
20242            return true;
20243        }
20244        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20245                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20246            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20247                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20248            return true;
20249        }
20250        return false;
20251   }
20252
20253    @Override
20254    public int getInstallLocation() {
20255        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20256                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20257                PackageHelper.APP_INSTALL_AUTO);
20258    }
20259
20260    /** Called by UserManagerService */
20261    void cleanUpUser(UserManagerService userManager, int userHandle) {
20262        synchronized (mPackages) {
20263            mDirtyUsers.remove(userHandle);
20264            mUserNeedsBadging.delete(userHandle);
20265            mSettings.removeUserLPw(userHandle);
20266            mPendingBroadcasts.remove(userHandle);
20267            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20268            removeUnusedPackagesLPw(userManager, userHandle);
20269        }
20270    }
20271
20272    /**
20273     * We're removing userHandle and would like to remove any downloaded packages
20274     * that are no longer in use by any other user.
20275     * @param userHandle the user being removed
20276     */
20277    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20278        final boolean DEBUG_CLEAN_APKS = false;
20279        int [] users = userManager.getUserIds();
20280        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20281        while (psit.hasNext()) {
20282            PackageSetting ps = psit.next();
20283            if (ps.pkg == null) {
20284                continue;
20285            }
20286            final String packageName = ps.pkg.packageName;
20287            // Skip over if system app
20288            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20289                continue;
20290            }
20291            if (DEBUG_CLEAN_APKS) {
20292                Slog.i(TAG, "Checking package " + packageName);
20293            }
20294            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20295            if (keep) {
20296                if (DEBUG_CLEAN_APKS) {
20297                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20298                }
20299            } else {
20300                for (int i = 0; i < users.length; i++) {
20301                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20302                        keep = true;
20303                        if (DEBUG_CLEAN_APKS) {
20304                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20305                                    + users[i]);
20306                        }
20307                        break;
20308                    }
20309                }
20310            }
20311            if (!keep) {
20312                if (DEBUG_CLEAN_APKS) {
20313                    Slog.i(TAG, "  Removing package " + packageName);
20314                }
20315                mHandler.post(new Runnable() {
20316                    public void run() {
20317                        deletePackageX(packageName, userHandle, 0);
20318                    } //end run
20319                });
20320            }
20321        }
20322    }
20323
20324    /** Called by UserManagerService */
20325    void createNewUser(int userId) {
20326        synchronized (mInstallLock) {
20327            mSettings.createNewUserLI(this, mInstaller, userId);
20328        }
20329        synchronized (mPackages) {
20330            scheduleWritePackageRestrictionsLocked(userId);
20331            scheduleWritePackageListLocked(userId);
20332            applyFactoryDefaultBrowserLPw(userId);
20333            primeDomainVerificationsLPw(userId);
20334        }
20335    }
20336
20337    void onBeforeUserStartUninitialized(final int userId) {
20338        synchronized (mPackages) {
20339            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20340                return;
20341            }
20342        }
20343        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20344        // If permission review for legacy apps is required, we represent
20345        // dagerous permissions for such apps as always granted runtime
20346        // permissions to keep per user flag state whether review is needed.
20347        // Hence, if a new user is added we have to propagate dangerous
20348        // permission grants for these legacy apps.
20349        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20350            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20351                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20352        }
20353    }
20354
20355    @Override
20356    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20357        mContext.enforceCallingOrSelfPermission(
20358                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20359                "Only package verification agents can read the verifier device identity");
20360
20361        synchronized (mPackages) {
20362            return mSettings.getVerifierDeviceIdentityLPw();
20363        }
20364    }
20365
20366    @Override
20367    public void setPermissionEnforced(String permission, boolean enforced) {
20368        // TODO: Now that we no longer change GID for storage, this should to away.
20369        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20370                "setPermissionEnforced");
20371        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20372            synchronized (mPackages) {
20373                if (mSettings.mReadExternalStorageEnforced == null
20374                        || mSettings.mReadExternalStorageEnforced != enforced) {
20375                    mSettings.mReadExternalStorageEnforced = enforced;
20376                    mSettings.writeLPr();
20377                }
20378            }
20379            // kill any non-foreground processes so we restart them and
20380            // grant/revoke the GID.
20381            final IActivityManager am = ActivityManagerNative.getDefault();
20382            if (am != null) {
20383                final long token = Binder.clearCallingIdentity();
20384                try {
20385                    am.killProcessesBelowForeground("setPermissionEnforcement");
20386                } catch (RemoteException e) {
20387                } finally {
20388                    Binder.restoreCallingIdentity(token);
20389                }
20390            }
20391        } else {
20392            throw new IllegalArgumentException("No selective enforcement for " + permission);
20393        }
20394    }
20395
20396    @Override
20397    @Deprecated
20398    public boolean isPermissionEnforced(String permission) {
20399        return true;
20400    }
20401
20402    @Override
20403    public boolean isStorageLow() {
20404        final long token = Binder.clearCallingIdentity();
20405        try {
20406            final DeviceStorageMonitorInternal
20407                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20408            if (dsm != null) {
20409                return dsm.isMemoryLow();
20410            } else {
20411                return false;
20412            }
20413        } finally {
20414            Binder.restoreCallingIdentity(token);
20415        }
20416    }
20417
20418    @Override
20419    public IPackageInstaller getPackageInstaller() {
20420        return mInstallerService;
20421    }
20422
20423    private boolean userNeedsBadging(int userId) {
20424        int index = mUserNeedsBadging.indexOfKey(userId);
20425        if (index < 0) {
20426            final UserInfo userInfo;
20427            final long token = Binder.clearCallingIdentity();
20428            try {
20429                userInfo = sUserManager.getUserInfo(userId);
20430            } finally {
20431                Binder.restoreCallingIdentity(token);
20432            }
20433            final boolean b;
20434            if (userInfo != null && userInfo.isManagedProfile()) {
20435                b = true;
20436            } else {
20437                b = false;
20438            }
20439            mUserNeedsBadging.put(userId, b);
20440            return b;
20441        }
20442        return mUserNeedsBadging.valueAt(index);
20443    }
20444
20445    @Override
20446    public KeySet getKeySetByAlias(String packageName, String alias) {
20447        if (packageName == null || alias == null) {
20448            return null;
20449        }
20450        synchronized(mPackages) {
20451            final PackageParser.Package pkg = mPackages.get(packageName);
20452            if (pkg == null) {
20453                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20454                throw new IllegalArgumentException("Unknown package: " + packageName);
20455            }
20456            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20457            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20458        }
20459    }
20460
20461    @Override
20462    public KeySet getSigningKeySet(String packageName) {
20463        if (packageName == null) {
20464            return null;
20465        }
20466        synchronized(mPackages) {
20467            final PackageParser.Package pkg = mPackages.get(packageName);
20468            if (pkg == null) {
20469                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20470                throw new IllegalArgumentException("Unknown package: " + packageName);
20471            }
20472            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20473                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20474                throw new SecurityException("May not access signing KeySet of other apps.");
20475            }
20476            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20477            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20478        }
20479    }
20480
20481    @Override
20482    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20483        if (packageName == null || ks == null) {
20484            return false;
20485        }
20486        synchronized(mPackages) {
20487            final PackageParser.Package pkg = mPackages.get(packageName);
20488            if (pkg == null) {
20489                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20490                throw new IllegalArgumentException("Unknown package: " + packageName);
20491            }
20492            IBinder ksh = ks.getToken();
20493            if (ksh instanceof KeySetHandle) {
20494                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20495                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20496            }
20497            return false;
20498        }
20499    }
20500
20501    @Override
20502    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20503        if (packageName == null || ks == null) {
20504            return false;
20505        }
20506        synchronized(mPackages) {
20507            final PackageParser.Package pkg = mPackages.get(packageName);
20508            if (pkg == null) {
20509                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20510                throw new IllegalArgumentException("Unknown package: " + packageName);
20511            }
20512            IBinder ksh = ks.getToken();
20513            if (ksh instanceof KeySetHandle) {
20514                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20515                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20516            }
20517            return false;
20518        }
20519    }
20520
20521    private void deletePackageIfUnusedLPr(final String packageName) {
20522        PackageSetting ps = mSettings.mPackages.get(packageName);
20523        if (ps == null) {
20524            return;
20525        }
20526        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20527            // TODO Implement atomic delete if package is unused
20528            // It is currently possible that the package will be deleted even if it is installed
20529            // after this method returns.
20530            mHandler.post(new Runnable() {
20531                public void run() {
20532                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20533                }
20534            });
20535        }
20536    }
20537
20538    /**
20539     * Check and throw if the given before/after packages would be considered a
20540     * downgrade.
20541     */
20542    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20543            throws PackageManagerException {
20544        if (after.versionCode < before.mVersionCode) {
20545            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20546                    "Update version code " + after.versionCode + " is older than current "
20547                    + before.mVersionCode);
20548        } else if (after.versionCode == before.mVersionCode) {
20549            if (after.baseRevisionCode < before.baseRevisionCode) {
20550                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20551                        "Update base revision code " + after.baseRevisionCode
20552                        + " is older than current " + before.baseRevisionCode);
20553            }
20554
20555            if (!ArrayUtils.isEmpty(after.splitNames)) {
20556                for (int i = 0; i < after.splitNames.length; i++) {
20557                    final String splitName = after.splitNames[i];
20558                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20559                    if (j != -1) {
20560                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20561                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20562                                    "Update split " + splitName + " revision code "
20563                                    + after.splitRevisionCodes[i] + " is older than current "
20564                                    + before.splitRevisionCodes[j]);
20565                        }
20566                    }
20567                }
20568            }
20569        }
20570    }
20571
20572    private static class MoveCallbacks extends Handler {
20573        private static final int MSG_CREATED = 1;
20574        private static final int MSG_STATUS_CHANGED = 2;
20575
20576        private final RemoteCallbackList<IPackageMoveObserver>
20577                mCallbacks = new RemoteCallbackList<>();
20578
20579        private final SparseIntArray mLastStatus = new SparseIntArray();
20580
20581        public MoveCallbacks(Looper looper) {
20582            super(looper);
20583        }
20584
20585        public void register(IPackageMoveObserver callback) {
20586            mCallbacks.register(callback);
20587        }
20588
20589        public void unregister(IPackageMoveObserver callback) {
20590            mCallbacks.unregister(callback);
20591        }
20592
20593        @Override
20594        public void handleMessage(Message msg) {
20595            final SomeArgs args = (SomeArgs) msg.obj;
20596            final int n = mCallbacks.beginBroadcast();
20597            for (int i = 0; i < n; i++) {
20598                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20599                try {
20600                    invokeCallback(callback, msg.what, args);
20601                } catch (RemoteException ignored) {
20602                }
20603            }
20604            mCallbacks.finishBroadcast();
20605            args.recycle();
20606        }
20607
20608        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20609                throws RemoteException {
20610            switch (what) {
20611                case MSG_CREATED: {
20612                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20613                    break;
20614                }
20615                case MSG_STATUS_CHANGED: {
20616                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20617                    break;
20618                }
20619            }
20620        }
20621
20622        private void notifyCreated(int moveId, Bundle extras) {
20623            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20624
20625            final SomeArgs args = SomeArgs.obtain();
20626            args.argi1 = moveId;
20627            args.arg2 = extras;
20628            obtainMessage(MSG_CREATED, args).sendToTarget();
20629        }
20630
20631        private void notifyStatusChanged(int moveId, int status) {
20632            notifyStatusChanged(moveId, status, -1);
20633        }
20634
20635        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20636            Slog.v(TAG, "Move " + moveId + " status " + status);
20637
20638            final SomeArgs args = SomeArgs.obtain();
20639            args.argi1 = moveId;
20640            args.argi2 = status;
20641            args.arg3 = estMillis;
20642            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20643
20644            synchronized (mLastStatus) {
20645                mLastStatus.put(moveId, status);
20646            }
20647        }
20648    }
20649
20650    private final static class OnPermissionChangeListeners extends Handler {
20651        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20652
20653        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20654                new RemoteCallbackList<>();
20655
20656        public OnPermissionChangeListeners(Looper looper) {
20657            super(looper);
20658        }
20659
20660        @Override
20661        public void handleMessage(Message msg) {
20662            switch (msg.what) {
20663                case MSG_ON_PERMISSIONS_CHANGED: {
20664                    final int uid = msg.arg1;
20665                    handleOnPermissionsChanged(uid);
20666                } break;
20667            }
20668        }
20669
20670        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20671            mPermissionListeners.register(listener);
20672
20673        }
20674
20675        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20676            mPermissionListeners.unregister(listener);
20677        }
20678
20679        public void onPermissionsChanged(int uid) {
20680            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20681                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20682            }
20683        }
20684
20685        private void handleOnPermissionsChanged(int uid) {
20686            final int count = mPermissionListeners.beginBroadcast();
20687            try {
20688                for (int i = 0; i < count; i++) {
20689                    IOnPermissionsChangeListener callback = mPermissionListeners
20690                            .getBroadcastItem(i);
20691                    try {
20692                        callback.onPermissionsChanged(uid);
20693                    } catch (RemoteException e) {
20694                        Log.e(TAG, "Permission listener is dead", e);
20695                    }
20696                }
20697            } finally {
20698                mPermissionListeners.finishBroadcast();
20699            }
20700        }
20701    }
20702
20703    private class PackageManagerInternalImpl extends PackageManagerInternal {
20704        @Override
20705        public void setLocationPackagesProvider(PackagesProvider provider) {
20706            synchronized (mPackages) {
20707                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20708            }
20709        }
20710
20711        @Override
20712        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20713            synchronized (mPackages) {
20714                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20715            }
20716        }
20717
20718        @Override
20719        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20720            synchronized (mPackages) {
20721                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20722            }
20723        }
20724
20725        @Override
20726        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20727            synchronized (mPackages) {
20728                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20729            }
20730        }
20731
20732        @Override
20733        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20734            synchronized (mPackages) {
20735                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20736            }
20737        }
20738
20739        @Override
20740        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20741            synchronized (mPackages) {
20742                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20743            }
20744        }
20745
20746        @Override
20747        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20748            synchronized (mPackages) {
20749                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20750                        packageName, userId);
20751            }
20752        }
20753
20754        @Override
20755        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20756            synchronized (mPackages) {
20757                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20758                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20759                        packageName, userId);
20760            }
20761        }
20762
20763        @Override
20764        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20765            synchronized (mPackages) {
20766                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20767                        packageName, userId);
20768            }
20769        }
20770
20771        @Override
20772        public void setKeepUninstalledPackages(final List<String> packageList) {
20773            Preconditions.checkNotNull(packageList);
20774            List<String> removedFromList = null;
20775            synchronized (mPackages) {
20776                if (mKeepUninstalledPackages != null) {
20777                    final int packagesCount = mKeepUninstalledPackages.size();
20778                    for (int i = 0; i < packagesCount; i++) {
20779                        String oldPackage = mKeepUninstalledPackages.get(i);
20780                        if (packageList != null && packageList.contains(oldPackage)) {
20781                            continue;
20782                        }
20783                        if (removedFromList == null) {
20784                            removedFromList = new ArrayList<>();
20785                        }
20786                        removedFromList.add(oldPackage);
20787                    }
20788                }
20789                mKeepUninstalledPackages = new ArrayList<>(packageList);
20790                if (removedFromList != null) {
20791                    final int removedCount = removedFromList.size();
20792                    for (int i = 0; i < removedCount; i++) {
20793                        deletePackageIfUnusedLPr(removedFromList.get(i));
20794                    }
20795                }
20796            }
20797        }
20798
20799        @Override
20800        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20801            synchronized (mPackages) {
20802                // If we do not support permission review, done.
20803                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20804                    return false;
20805                }
20806
20807                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20808                if (packageSetting == null) {
20809                    return false;
20810                }
20811
20812                // Permission review applies only to apps not supporting the new permission model.
20813                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20814                    return false;
20815                }
20816
20817                // Legacy apps have the permission and get user consent on launch.
20818                PermissionsState permissionsState = packageSetting.getPermissionsState();
20819                return permissionsState.isPermissionReviewRequired(userId);
20820            }
20821        }
20822
20823        @Override
20824        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20825            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20826        }
20827
20828        @Override
20829        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20830                int userId) {
20831            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20832        }
20833
20834        @Override
20835        public void setDeviceAndProfileOwnerPackages(
20836                int deviceOwnerUserId, String deviceOwnerPackage,
20837                SparseArray<String> profileOwnerPackages) {
20838            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20839                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20840        }
20841
20842        @Override
20843        public boolean canPackageBeWiped(int userId, String packageName) {
20844            return mProtectedPackages.canPackageBeWiped(userId,
20845                    packageName);
20846        }
20847    }
20848
20849    @Override
20850    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20851        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20852        synchronized (mPackages) {
20853            final long identity = Binder.clearCallingIdentity();
20854            try {
20855                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20856                        packageNames, userId);
20857            } finally {
20858                Binder.restoreCallingIdentity(identity);
20859            }
20860        }
20861    }
20862
20863    private static void enforceSystemOrPhoneCaller(String tag) {
20864        int callingUid = Binder.getCallingUid();
20865        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20866            throw new SecurityException(
20867                    "Cannot call " + tag + " from UID " + callingUid);
20868        }
20869    }
20870
20871    boolean isHistoricalPackageUsageAvailable() {
20872        return mPackageUsage.isHistoricalPackageUsageAvailable();
20873    }
20874
20875    /**
20876     * Return a <b>copy</b> of the collection of packages known to the package manager.
20877     * @return A copy of the values of mPackages.
20878     */
20879    Collection<PackageParser.Package> getPackages() {
20880        synchronized (mPackages) {
20881            return new ArrayList<>(mPackages.values());
20882        }
20883    }
20884
20885    /**
20886     * Logs process start information (including base APK hash) to the security log.
20887     * @hide
20888     */
20889    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20890            String apkFile, int pid) {
20891        if (!SecurityLog.isLoggingEnabled()) {
20892            return;
20893        }
20894        Bundle data = new Bundle();
20895        data.putLong("startTimestamp", System.currentTimeMillis());
20896        data.putString("processName", processName);
20897        data.putInt("uid", uid);
20898        data.putString("seinfo", seinfo);
20899        data.putString("apkFile", apkFile);
20900        data.putInt("pid", pid);
20901        Message msg = mProcessLoggingHandler.obtainMessage(
20902                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20903        msg.setData(data);
20904        mProcessLoggingHandler.sendMessage(msg);
20905    }
20906}
20907