PackageManagerService.java revision 4288419787120ce85a241a4b315d7d2123aa2d4a
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.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.app.usage.UsageStatsManager;
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.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.AtomicFile;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.os.IParcelFileDescriptorFactory;
229import com.android.internal.os.InstallerConnection.InstallerException;
230import com.android.internal.os.SomeArgs;
231import com.android.internal.os.Zygote;
232import com.android.internal.util.ArrayUtils;
233import com.android.internal.util.FastPrintWriter;
234import com.android.internal.util.FastXmlSerializer;
235import com.android.internal.util.IndentingPrintWriter;
236import com.android.internal.util.Preconditions;
237import com.android.internal.util.XmlUtils;
238import com.android.server.EventLogTags;
239import com.android.server.FgThread;
240import com.android.server.IntentResolver;
241import com.android.server.LocalServices;
242import com.android.server.ServiceThread;
243import com.android.server.SystemConfig;
244import com.android.server.Watchdog;
245import com.android.server.pm.PermissionsState.PermissionState;
246import com.android.server.pm.Settings.DatabaseVersion;
247import com.android.server.pm.Settings.VersionInfo;
248import com.android.server.storage.DeviceStorageMonitorInternal;
249
250import dalvik.system.CloseGuard;
251import dalvik.system.DexFile;
252import dalvik.system.VMRuntime;
253
254import libcore.io.IoUtils;
255import libcore.util.EmptyArray;
256
257import org.xmlpull.v1.XmlPullParser;
258import org.xmlpull.v1.XmlPullParserException;
259import org.xmlpull.v1.XmlSerializer;
260
261import java.io.BufferedInputStream;
262import java.io.BufferedOutputStream;
263import java.io.BufferedReader;
264import java.io.ByteArrayInputStream;
265import java.io.ByteArrayOutputStream;
266import java.io.File;
267import java.io.FileDescriptor;
268import java.io.FileNotFoundException;
269import java.io.FileOutputStream;
270import java.io.FileReader;
271import java.io.FilenameFilter;
272import java.io.IOException;
273import java.io.InputStream;
274import java.io.PrintWriter;
275import java.nio.charset.StandardCharsets;
276import java.security.MessageDigest;
277import java.security.NoSuchAlgorithmException;
278import java.security.PublicKey;
279import java.security.cert.Certificate;
280import java.security.cert.CertificateEncodingException;
281import java.security.cert.CertificateException;
282import java.text.SimpleDateFormat;
283import java.util.ArrayList;
284import java.util.Arrays;
285import java.util.Collection;
286import java.util.Collections;
287import java.util.Comparator;
288import java.util.Date;
289import java.util.HashSet;
290import java.util.Iterator;
291import java.util.List;
292import java.util.Map;
293import java.util.Objects;
294import java.util.Set;
295import java.util.concurrent.CountDownLatch;
296import java.util.concurrent.TimeUnit;
297import java.util.concurrent.atomic.AtomicBoolean;
298import java.util.concurrent.atomic.AtomicInteger;
299import java.util.concurrent.atomic.AtomicLong;
300
301/**
302 * Keep track of all those APKs everywhere.
303 * <p>
304 * Internally there are two important locks:
305 * <ul>
306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
307 * and other related state. It is a fine-grained lock that should only be held
308 * momentarily, as it's one of the most contended locks in the system.
309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
310 * operations typically involve heavy lifting of application data on disk. Since
311 * {@code installd} is single-threaded, and it's operations can often be slow,
312 * this lock should never be acquired while already holding {@link #mPackages}.
313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
314 * holding {@link #mInstallLock}.
315 * </ul>
316 * Many internal methods rely on the caller to hold the appropriate locks, and
317 * this contract is expressed through method name suffixes:
318 * <ul>
319 * <li>fooLI(): the caller must hold {@link #mInstallLock}
320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
321 * being modified must be frozen
322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
324 * </ul>
325 * <p>
326 * Because this class is very central to the platform's security; please run all
327 * CTS and unit tests whenever making modifications:
328 *
329 * <pre>
330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
332 * </pre>
333 */
334public class PackageManagerService extends IPackageManager.Stub {
335    static final String TAG = "PackageManager";
336    static final boolean DEBUG_SETTINGS = false;
337    static final boolean DEBUG_PREFERRED = false;
338    static final boolean DEBUG_UPGRADE = false;
339    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
340    private static final boolean DEBUG_BACKUP = false;
341    private static final boolean DEBUG_INSTALL = false;
342    private static final boolean DEBUG_REMOVE = false;
343    private static final boolean DEBUG_BROADCASTS = false;
344    private static final boolean DEBUG_SHOW_INFO = false;
345    private static final boolean DEBUG_PACKAGE_INFO = false;
346    private static final boolean DEBUG_INTENT_MATCHING = false;
347    private static final boolean DEBUG_PACKAGE_SCANNING = false;
348    private static final boolean DEBUG_VERIFY = false;
349    private static final boolean DEBUG_FILTERS = false;
350
351    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
352    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
353    // user, but by default initialize to this.
354    static final boolean DEBUG_DEXOPT = false;
355
356    private static final boolean DEBUG_ABI_SELECTION = false;
357    private static final boolean DEBUG_EPHEMERAL = false;
358    private static final boolean DEBUG_TRIAGED_MISSING = false;
359    private static final boolean DEBUG_APP_DATA = false;
360
361    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
362
363    private static final boolean DISABLE_EPHEMERAL_APPS = true;
364
365    private static final int RADIO_UID = Process.PHONE_UID;
366    private static final int LOG_UID = Process.LOG_UID;
367    private static final int NFC_UID = Process.NFC_UID;
368    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
369    private static final int SHELL_UID = Process.SHELL_UID;
370
371    // Cap the size of permission trees that 3rd party apps can define
372    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
373
374    // Suffix used during package installation when copying/moving
375    // package apks to install directory.
376    private static final String INSTALL_PACKAGE_SUFFIX = "-";
377
378    static final int SCAN_NO_DEX = 1<<1;
379    static final int SCAN_FORCE_DEX = 1<<2;
380    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
381    static final int SCAN_NEW_INSTALL = 1<<4;
382    static final int SCAN_NO_PATHS = 1<<5;
383    static final int SCAN_UPDATE_TIME = 1<<6;
384    static final int SCAN_DEFER_DEX = 1<<7;
385    static final int SCAN_BOOTING = 1<<8;
386    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
387    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
388    static final int SCAN_REPLACING = 1<<11;
389    static final int SCAN_REQUIRE_KNOWN = 1<<12;
390    static final int SCAN_MOVE = 1<<13;
391    static final int SCAN_INITIAL = 1<<14;
392    static final int SCAN_CHECK_ONLY = 1<<15;
393    static final int SCAN_DONT_KILL_APP = 1<<17;
394    static final int SCAN_IGNORE_FROZEN = 1<<18;
395
396    static final int REMOVE_CHATTY = 1<<16;
397
398    private static final int[] EMPTY_INT_ARRAY = new int[0];
399
400    /**
401     * Timeout (in milliseconds) after which the watchdog should declare that
402     * our handler thread is wedged.  The usual default for such things is one
403     * minute but we sometimes do very lengthy I/O operations on this thread,
404     * such as installing multi-gigabyte applications, so ours needs to be longer.
405     */
406    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
407
408    /**
409     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
410     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
411     * settings entry if available, otherwise we use the hardcoded default.  If it's been
412     * more than this long since the last fstrim, we force one during the boot sequence.
413     *
414     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
415     * one gets run at the next available charging+idle time.  This final mandatory
416     * no-fstrim check kicks in only of the other scheduling criteria is never met.
417     */
418    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
419
420    /**
421     * Whether verification is enabled by default.
422     */
423    private static final boolean DEFAULT_VERIFY_ENABLE = true;
424
425    /**
426     * The default maximum time to wait for the verification agent to return in
427     * milliseconds.
428     */
429    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
430
431    /**
432     * The default response for package verification timeout.
433     *
434     * This can be either PackageManager.VERIFICATION_ALLOW or
435     * PackageManager.VERIFICATION_REJECT.
436     */
437    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
438
439    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
440
441    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
442            DEFAULT_CONTAINER_PACKAGE,
443            "com.android.defcontainer.DefaultContainerService");
444
445    private static final String KILL_APP_REASON_GIDS_CHANGED =
446            "permission grant or revoke changed gids";
447
448    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
449            "permissions revoked";
450
451    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
452
453    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
454
455    /** Permission grant: not grant the permission. */
456    private static final int GRANT_DENIED = 1;
457
458    /** Permission grant: grant the permission as an install permission. */
459    private static final int GRANT_INSTALL = 2;
460
461    /** Permission grant: grant the permission as a runtime one. */
462    private static final int GRANT_RUNTIME = 3;
463
464    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
465    private static final int GRANT_UPGRADE = 4;
466
467    /** Canonical intent used to identify what counts as a "web browser" app */
468    private static final Intent sBrowserIntent;
469    static {
470        sBrowserIntent = new Intent();
471        sBrowserIntent.setAction(Intent.ACTION_VIEW);
472        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
473        sBrowserIntent.setData(Uri.parse("http:"));
474    }
475
476    /**
477     * The set of all protected actions [i.e. those actions for which a high priority
478     * intent filter is disallowed].
479     */
480    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
481    static {
482        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
483        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
485        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
486    }
487
488    // Compilation reasons.
489    public static final int REASON_FIRST_BOOT = 0;
490    public static final int REASON_BOOT = 1;
491    public static final int REASON_INSTALL = 2;
492    public static final int REASON_BACKGROUND_DEXOPT = 3;
493    public static final int REASON_AB_OTA = 4;
494    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
495    public static final int REASON_SHARED_APK = 6;
496    public static final int REASON_FORCED_DEXOPT = 7;
497
498    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
499
500    final ServiceThread mHandlerThread;
501
502    final PackageHandler mHandler;
503
504    private final ProcessLoggingHandler mProcessLoggingHandler;
505
506    /**
507     * Messages for {@link #mHandler} that need to wait for system ready before
508     * being dispatched.
509     */
510    private ArrayList<Message> mPostSystemReadyMessages;
511
512    final int mSdkVersion = Build.VERSION.SDK_INT;
513
514    final Context mContext;
515    final boolean mFactoryTest;
516    final boolean mOnlyCore;
517    final DisplayMetrics mMetrics;
518    final int mDefParseFlags;
519    final String[] mSeparateProcesses;
520    final boolean mIsUpgrade;
521    final boolean mIsPreNUpgrade;
522
523    /** The location for ASEC container files on internal storage. */
524    final String mAsecInternalPath;
525
526    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
527    // LOCK HELD.  Can be called with mInstallLock held.
528    @GuardedBy("mInstallLock")
529    final Installer mInstaller;
530
531    /** Directory where installed third-party apps stored */
532    final File mAppInstallDir;
533    final File mEphemeralInstallDir;
534
535    /**
536     * Directory to which applications installed internally have their
537     * 32 bit native libraries copied.
538     */
539    private File mAppLib32InstallDir;
540
541    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
542    // apps.
543    final File mDrmAppPrivateInstallDir;
544
545    // ----------------------------------------------------------------
546
547    // Lock for state used when installing and doing other long running
548    // operations.  Methods that must be called with this lock held have
549    // the suffix "LI".
550    final Object mInstallLock = new Object();
551
552    // ----------------------------------------------------------------
553
554    // Keys are String (package name), values are Package.  This also serves
555    // as the lock for the global state.  Methods that must be called with
556    // this lock held have the prefix "LP".
557    @GuardedBy("mPackages")
558    final ArrayMap<String, PackageParser.Package> mPackages =
559            new ArrayMap<String, PackageParser.Package>();
560
561    final ArrayMap<String, Set<String>> mKnownCodebase =
562            new ArrayMap<String, Set<String>>();
563
564    // Tracks available target package names -> overlay package paths.
565    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
566        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
567
568    /**
569     * Tracks new system packages [received in an OTA] that we expect to
570     * find updated user-installed versions. Keys are package name, values
571     * are package location.
572     */
573    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
574    /**
575     * Tracks high priority intent filters for protected actions. During boot, certain
576     * filter actions are protected and should never be allowed to have a high priority
577     * intent filter for them. However, there is one, and only one exception -- the
578     * setup wizard. It must be able to define a high priority intent filter for these
579     * actions to ensure there are no escapes from the wizard. We need to delay processing
580     * of these during boot as we need to look at all of the system packages in order
581     * to know which component is the setup wizard.
582     */
583    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
584    /**
585     * Whether or not processing protected filters should be deferred.
586     */
587    private boolean mDeferProtectedFilters = true;
588
589    /**
590     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
591     */
592    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
593    /**
594     * Whether or not system app permissions should be promoted from install to runtime.
595     */
596    boolean mPromoteSystemApps;
597
598    @GuardedBy("mPackages")
599    final Settings mSettings;
600
601    /**
602     * Set of package names that are currently "frozen", which means active
603     * surgery is being done on the code/data for that package. The platform
604     * will refuse to launch frozen packages to avoid race conditions.
605     *
606     * @see PackageFreezer
607     */
608    @GuardedBy("mPackages")
609    final ArraySet<String> mFrozenPackages = new ArraySet<>();
610
611    boolean mRestoredSettings;
612
613    // System configuration read by SystemConfig.
614    final int[] mGlobalGids;
615    final SparseArray<ArraySet<String>> mSystemPermissions;
616    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
617
618    // If mac_permissions.xml was found for seinfo labeling.
619    boolean mFoundPolicyFile;
620
621    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
622
623    public static final class SharedLibraryEntry {
624        public final String path;
625        public final String apk;
626
627        SharedLibraryEntry(String _path, String _apk) {
628            path = _path;
629            apk = _apk;
630        }
631    }
632
633    // Currently known shared libraries.
634    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
635            new ArrayMap<String, SharedLibraryEntry>();
636
637    // All available activities, for your resolving pleasure.
638    final ActivityIntentResolver mActivities =
639            new ActivityIntentResolver();
640
641    // All available receivers, for your resolving pleasure.
642    final ActivityIntentResolver mReceivers =
643            new ActivityIntentResolver();
644
645    // All available services, for your resolving pleasure.
646    final ServiceIntentResolver mServices = new ServiceIntentResolver();
647
648    // All available providers, for your resolving pleasure.
649    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
650
651    // Mapping from provider base names (first directory in content URI codePath)
652    // to the provider information.
653    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
654            new ArrayMap<String, PackageParser.Provider>();
655
656    // Mapping from instrumentation class names to info about them.
657    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
658            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
659
660    // Mapping from permission names to info about them.
661    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
662            new ArrayMap<String, PackageParser.PermissionGroup>();
663
664    // Packages whose data we have transfered into another package, thus
665    // should no longer exist.
666    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
667
668    // Broadcast actions that are only available to the system.
669    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
670
671    /** List of packages waiting for verification. */
672    final SparseArray<PackageVerificationState> mPendingVerification
673            = new SparseArray<PackageVerificationState>();
674
675    /** Set of packages associated with each app op permission. */
676    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
677
678    final PackageInstallerService mInstallerService;
679
680    private final PackageDexOptimizer mPackageDexOptimizer;
681
682    private AtomicInteger mNextMoveId = new AtomicInteger();
683    private final MoveCallbacks mMoveCallbacks;
684
685    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
686
687    // Cache of users who need badging.
688    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
689
690    /** Token for keys in mPendingVerification. */
691    private int mPendingVerificationToken = 0;
692
693    volatile boolean mSystemReady;
694    volatile boolean mSafeMode;
695    volatile boolean mHasSystemUidErrors;
696
697    ApplicationInfo mAndroidApplication;
698    final ActivityInfo mResolveActivity = new ActivityInfo();
699    final ResolveInfo mResolveInfo = new ResolveInfo();
700    ComponentName mResolveComponentName;
701    PackageParser.Package mPlatformPackage;
702    ComponentName mCustomResolverComponentName;
703
704    boolean mResolverReplaced = false;
705
706    private final @Nullable ComponentName mIntentFilterVerifierComponent;
707    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
708
709    private int mIntentFilterVerificationToken = 0;
710
711    /** Component that knows whether or not an ephemeral application exists */
712    final ComponentName mEphemeralResolverComponent;
713    /** The service connection to the ephemeral resolver */
714    final EphemeralResolverConnection mEphemeralResolverConnection;
715
716    /** Component used to install ephemeral applications */
717    final ComponentName mEphemeralInstallerComponent;
718    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
719    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
720
721    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
722            = new SparseArray<IntentFilterVerificationState>();
723
724    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
725            new DefaultPermissionGrantPolicy(this);
726
727    // List of packages names to keep cached, even if they are uninstalled for all users
728    private List<String> mKeepUninstalledPackages;
729
730    private static class IFVerificationParams {
731        PackageParser.Package pkg;
732        boolean replacing;
733        int userId;
734        int verifierUid;
735
736        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
737                int _userId, int _verifierUid) {
738            pkg = _pkg;
739            replacing = _replacing;
740            userId = _userId;
741            replacing = _replacing;
742            verifierUid = _verifierUid;
743        }
744    }
745
746    private interface IntentFilterVerifier<T extends IntentFilter> {
747        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
748                                               T filter, String packageName);
749        void startVerifications(int userId);
750        void receiveVerificationResponse(int verificationId);
751    }
752
753    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
754        private Context mContext;
755        private ComponentName mIntentFilterVerifierComponent;
756        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
757
758        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
759            mContext = context;
760            mIntentFilterVerifierComponent = verifierComponent;
761        }
762
763        private String getDefaultScheme() {
764            return IntentFilter.SCHEME_HTTPS;
765        }
766
767        @Override
768        public void startVerifications(int userId) {
769            // Launch verifications requests
770            int count = mCurrentIntentFilterVerifications.size();
771            for (int n=0; n<count; n++) {
772                int verificationId = mCurrentIntentFilterVerifications.get(n);
773                final IntentFilterVerificationState ivs =
774                        mIntentFilterVerificationStates.get(verificationId);
775
776                String packageName = ivs.getPackageName();
777
778                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
779                final int filterCount = filters.size();
780                ArraySet<String> domainsSet = new ArraySet<>();
781                for (int m=0; m<filterCount; m++) {
782                    PackageParser.ActivityIntentInfo filter = filters.get(m);
783                    domainsSet.addAll(filter.getHostsList());
784                }
785                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
786                synchronized (mPackages) {
787                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
788                            packageName, domainsList) != null) {
789                        scheduleWriteSettingsLocked();
790                    }
791                }
792                sendVerificationRequest(userId, verificationId, ivs);
793            }
794            mCurrentIntentFilterVerifications.clear();
795        }
796
797        private void sendVerificationRequest(int userId, int verificationId,
798                IntentFilterVerificationState ivs) {
799
800            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
801            verificationIntent.putExtra(
802                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
803                    verificationId);
804            verificationIntent.putExtra(
805                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
806                    getDefaultScheme());
807            verificationIntent.putExtra(
808                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
809                    ivs.getHostsString());
810            verificationIntent.putExtra(
811                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
812                    ivs.getPackageName());
813            verificationIntent.setComponent(mIntentFilterVerifierComponent);
814            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
815
816            UserHandle user = new UserHandle(userId);
817            mContext.sendBroadcastAsUser(verificationIntent, user);
818            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
819                    "Sending IntentFilter verification broadcast");
820        }
821
822        public void receiveVerificationResponse(int verificationId) {
823            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
824
825            final boolean verified = ivs.isVerified();
826
827            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
828            final int count = filters.size();
829            if (DEBUG_DOMAIN_VERIFICATION) {
830                Slog.i(TAG, "Received verification response " + verificationId
831                        + " for " + count + " filters, verified=" + verified);
832            }
833            for (int n=0; n<count; n++) {
834                PackageParser.ActivityIntentInfo filter = filters.get(n);
835                filter.setVerified(verified);
836
837                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
838                        + " verified with result:" + verified + " and hosts:"
839                        + ivs.getHostsString());
840            }
841
842            mIntentFilterVerificationStates.remove(verificationId);
843
844            final String packageName = ivs.getPackageName();
845            IntentFilterVerificationInfo ivi = null;
846
847            synchronized (mPackages) {
848                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
849            }
850            if (ivi == null) {
851                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
852                        + verificationId + " packageName:" + packageName);
853                return;
854            }
855            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
856                    "Updating IntentFilterVerificationInfo for package " + packageName
857                            +" verificationId:" + verificationId);
858
859            synchronized (mPackages) {
860                if (verified) {
861                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
862                } else {
863                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
864                }
865                scheduleWriteSettingsLocked();
866
867                final int userId = ivs.getUserId();
868                if (userId != UserHandle.USER_ALL) {
869                    final int userStatus =
870                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
871
872                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
873                    boolean needUpdate = false;
874
875                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
876                    // already been set by the User thru the Disambiguation dialog
877                    switch (userStatus) {
878                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
879                            if (verified) {
880                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
881                            } else {
882                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
883                            }
884                            needUpdate = true;
885                            break;
886
887                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
888                            if (verified) {
889                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
890                                needUpdate = true;
891                            }
892                            break;
893
894                        default:
895                            // Nothing to do
896                    }
897
898                    if (needUpdate) {
899                        mSettings.updateIntentFilterVerificationStatusLPw(
900                                packageName, updatedStatus, userId);
901                        scheduleWritePackageRestrictionsLocked(userId);
902                    }
903                }
904            }
905        }
906
907        @Override
908        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
909                    ActivityIntentInfo filter, String packageName) {
910            if (!hasValidDomains(filter)) {
911                return false;
912            }
913            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
914            if (ivs == null) {
915                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
916                        packageName);
917            }
918            if (DEBUG_DOMAIN_VERIFICATION) {
919                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
920            }
921            ivs.addFilter(filter);
922            return true;
923        }
924
925        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
926                int userId, int verificationId, String packageName) {
927            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
928                    verifierUid, userId, packageName);
929            ivs.setPendingState();
930            synchronized (mPackages) {
931                mIntentFilterVerificationStates.append(verificationId, ivs);
932                mCurrentIntentFilterVerifications.add(verificationId);
933            }
934            return ivs;
935        }
936    }
937
938    private static boolean hasValidDomains(ActivityIntentInfo filter) {
939        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
940                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
941                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
942    }
943
944    // Set of pending broadcasts for aggregating enable/disable of components.
945    static class PendingPackageBroadcasts {
946        // for each user id, a map of <package name -> components within that package>
947        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
948
949        public PendingPackageBroadcasts() {
950            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
951        }
952
953        public ArrayList<String> get(int userId, String packageName) {
954            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
955            return packages.get(packageName);
956        }
957
958        public void put(int userId, String packageName, ArrayList<String> components) {
959            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
960            packages.put(packageName, components);
961        }
962
963        public void remove(int userId, String packageName) {
964            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
965            if (packages != null) {
966                packages.remove(packageName);
967            }
968        }
969
970        public void remove(int userId) {
971            mUidMap.remove(userId);
972        }
973
974        public int userIdCount() {
975            return mUidMap.size();
976        }
977
978        public int userIdAt(int n) {
979            return mUidMap.keyAt(n);
980        }
981
982        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
983            return mUidMap.get(userId);
984        }
985
986        public int size() {
987            // total number of pending broadcast entries across all userIds
988            int num = 0;
989            for (int i = 0; i< mUidMap.size(); i++) {
990                num += mUidMap.valueAt(i).size();
991            }
992            return num;
993        }
994
995        public void clear() {
996            mUidMap.clear();
997        }
998
999        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1000            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1001            if (map == null) {
1002                map = new ArrayMap<String, ArrayList<String>>();
1003                mUidMap.put(userId, map);
1004            }
1005            return map;
1006        }
1007    }
1008    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1009
1010    // Service Connection to remote media container service to copy
1011    // package uri's from external media onto secure containers
1012    // or internal storage.
1013    private IMediaContainerService mContainerService = null;
1014
1015    static final int SEND_PENDING_BROADCAST = 1;
1016    static final int MCS_BOUND = 3;
1017    static final int END_COPY = 4;
1018    static final int INIT_COPY = 5;
1019    static final int MCS_UNBIND = 6;
1020    static final int START_CLEANING_PACKAGE = 7;
1021    static final int FIND_INSTALL_LOC = 8;
1022    static final int POST_INSTALL = 9;
1023    static final int MCS_RECONNECT = 10;
1024    static final int MCS_GIVE_UP = 11;
1025    static final int UPDATED_MEDIA_STATUS = 12;
1026    static final int WRITE_SETTINGS = 13;
1027    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1028    static final int PACKAGE_VERIFIED = 15;
1029    static final int CHECK_PENDING_VERIFICATION = 16;
1030    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1031    static final int INTENT_FILTER_VERIFIED = 18;
1032
1033    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1034
1035    // Delay time in millisecs
1036    static final int BROADCAST_DELAY = 10 * 1000;
1037
1038    static UserManagerService sUserManager;
1039
1040    // Stores a list of users whose package restrictions file needs to be updated
1041    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1042
1043    final private DefaultContainerConnection mDefContainerConn =
1044            new DefaultContainerConnection();
1045    class DefaultContainerConnection implements ServiceConnection {
1046        public void onServiceConnected(ComponentName name, IBinder service) {
1047            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1048            IMediaContainerService imcs =
1049                IMediaContainerService.Stub.asInterface(service);
1050            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1051        }
1052
1053        public void onServiceDisconnected(ComponentName name) {
1054            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1055        }
1056    }
1057
1058    // Recordkeeping of restore-after-install operations that are currently in flight
1059    // between the Package Manager and the Backup Manager
1060    static class PostInstallData {
1061        public InstallArgs args;
1062        public PackageInstalledInfo res;
1063
1064        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1065            args = _a;
1066            res = _r;
1067        }
1068    }
1069
1070    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1071    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1072
1073    // XML tags for backup/restore of various bits of state
1074    private static final String TAG_PREFERRED_BACKUP = "pa";
1075    private static final String TAG_DEFAULT_APPS = "da";
1076    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1077
1078    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1079    private static final String TAG_ALL_GRANTS = "rt-grants";
1080    private static final String TAG_GRANT = "grant";
1081    private static final String ATTR_PACKAGE_NAME = "pkg";
1082
1083    private static final String TAG_PERMISSION = "perm";
1084    private static final String ATTR_PERMISSION_NAME = "name";
1085    private static final String ATTR_IS_GRANTED = "g";
1086    private static final String ATTR_USER_SET = "set";
1087    private static final String ATTR_USER_FIXED = "fixed";
1088    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1089
1090    // System/policy permission grants are not backed up
1091    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1092            FLAG_PERMISSION_POLICY_FIXED
1093            | FLAG_PERMISSION_SYSTEM_FIXED
1094            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1095
1096    // And we back up these user-adjusted states
1097    private static final int USER_RUNTIME_GRANT_MASK =
1098            FLAG_PERMISSION_USER_SET
1099            | FLAG_PERMISSION_USER_FIXED
1100            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1101
1102    final @Nullable String mRequiredVerifierPackage;
1103    final @NonNull String mRequiredInstallerPackage;
1104    final @Nullable String mSetupWizardPackage;
1105    final @NonNull String mServicesSystemSharedLibraryPackageName;
1106
1107    private final PackageUsage mPackageUsage = new PackageUsage();
1108
1109    private class PackageUsage {
1110        private static final int WRITE_INTERVAL
1111            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1112
1113        private final Object mFileLock = new Object();
1114        private final AtomicLong mLastWritten = new AtomicLong(0);
1115        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1116
1117        private boolean mIsHistoricalPackageUsageAvailable = true;
1118
1119        boolean isHistoricalPackageUsageAvailable() {
1120            return mIsHistoricalPackageUsageAvailable;
1121        }
1122
1123        void write(boolean force) {
1124            if (force) {
1125                writeInternal();
1126                return;
1127            }
1128            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1129                && !DEBUG_DEXOPT) {
1130                return;
1131            }
1132            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1133                new Thread("PackageUsage_DiskWriter") {
1134                    @Override
1135                    public void run() {
1136                        try {
1137                            writeInternal();
1138                        } finally {
1139                            mBackgroundWriteRunning.set(false);
1140                        }
1141                    }
1142                }.start();
1143            }
1144        }
1145
1146        private void writeInternal() {
1147            synchronized (mPackages) {
1148                synchronized (mFileLock) {
1149                    AtomicFile file = getFile();
1150                    FileOutputStream f = null;
1151                    try {
1152                        f = file.startWrite();
1153                        BufferedOutputStream out = new BufferedOutputStream(f);
1154                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1155                        StringBuilder sb = new StringBuilder();
1156                        for (PackageParser.Package pkg : mPackages.values()) {
1157                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1158                                continue;
1159                            }
1160                            sb.setLength(0);
1161                            sb.append(pkg.packageName);
1162                            sb.append(' ');
1163                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1164                            sb.append('\n');
1165                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1166                        }
1167                        out.flush();
1168                        file.finishWrite(f);
1169                    } catch (IOException e) {
1170                        if (f != null) {
1171                            file.failWrite(f);
1172                        }
1173                        Log.e(TAG, "Failed to write package usage times", e);
1174                    }
1175                }
1176            }
1177            mLastWritten.set(SystemClock.elapsedRealtime());
1178        }
1179
1180        void readLP() {
1181            synchronized (mFileLock) {
1182                AtomicFile file = getFile();
1183                BufferedInputStream in = null;
1184                try {
1185                    in = new BufferedInputStream(file.openRead());
1186                    StringBuffer sb = new StringBuffer();
1187                    while (true) {
1188                        String packageName = readToken(in, sb, ' ');
1189                        if (packageName == null) {
1190                            break;
1191                        }
1192                        String timeInMillisString = readToken(in, sb, '\n');
1193                        if (timeInMillisString == null) {
1194                            throw new IOException("Failed to find last usage time for package "
1195                                                  + packageName);
1196                        }
1197                        PackageParser.Package pkg = mPackages.get(packageName);
1198                        if (pkg == null) {
1199                            continue;
1200                        }
1201                        long timeInMillis;
1202                        try {
1203                            timeInMillis = Long.parseLong(timeInMillisString);
1204                        } catch (NumberFormatException e) {
1205                            throw new IOException("Failed to parse " + timeInMillisString
1206                                                  + " as a long.", e);
1207                        }
1208                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1209                    }
1210                } catch (FileNotFoundException expected) {
1211                    mIsHistoricalPackageUsageAvailable = false;
1212                } catch (IOException e) {
1213                    Log.w(TAG, "Failed to read package usage times", e);
1214                } finally {
1215                    IoUtils.closeQuietly(in);
1216                }
1217            }
1218            mLastWritten.set(SystemClock.elapsedRealtime());
1219        }
1220
1221        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1222                throws IOException {
1223            sb.setLength(0);
1224            while (true) {
1225                int ch = in.read();
1226                if (ch == -1) {
1227                    if (sb.length() == 0) {
1228                        return null;
1229                    }
1230                    throw new IOException("Unexpected EOF");
1231                }
1232                if (ch == endOfToken) {
1233                    return sb.toString();
1234                }
1235                sb.append((char)ch);
1236            }
1237        }
1238
1239        private AtomicFile getFile() {
1240            File dataDir = Environment.getDataDirectory();
1241            File systemDir = new File(dataDir, "system");
1242            File fname = new File(systemDir, "package-usage.list");
1243            return new AtomicFile(fname);
1244        }
1245    }
1246
1247    class PackageHandler extends Handler {
1248        private boolean mBound = false;
1249        final ArrayList<HandlerParams> mPendingInstalls =
1250            new ArrayList<HandlerParams>();
1251
1252        private boolean connectToService() {
1253            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1254                    " DefaultContainerService");
1255            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1256            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1257            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1258                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1259                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1260                mBound = true;
1261                return true;
1262            }
1263            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1264            return false;
1265        }
1266
1267        private void disconnectService() {
1268            mContainerService = null;
1269            mBound = false;
1270            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1271            mContext.unbindService(mDefContainerConn);
1272            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1273        }
1274
1275        PackageHandler(Looper looper) {
1276            super(looper);
1277        }
1278
1279        public void handleMessage(Message msg) {
1280            try {
1281                doHandleMessage(msg);
1282            } finally {
1283                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284            }
1285        }
1286
1287        void doHandleMessage(Message msg) {
1288            switch (msg.what) {
1289                case INIT_COPY: {
1290                    HandlerParams params = (HandlerParams) msg.obj;
1291                    int idx = mPendingInstalls.size();
1292                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1293                    // If a bind was already initiated we dont really
1294                    // need to do anything. The pending install
1295                    // will be processed later on.
1296                    if (!mBound) {
1297                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1298                                System.identityHashCode(mHandler));
1299                        // If this is the only one pending we might
1300                        // have to bind to the service again.
1301                        if (!connectToService()) {
1302                            Slog.e(TAG, "Failed to bind to media container service");
1303                            params.serviceError();
1304                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1305                                    System.identityHashCode(mHandler));
1306                            if (params.traceMethod != null) {
1307                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1308                                        params.traceCookie);
1309                            }
1310                            return;
1311                        } else {
1312                            // Once we bind to the service, the first
1313                            // pending request will be processed.
1314                            mPendingInstalls.add(idx, params);
1315                        }
1316                    } else {
1317                        mPendingInstalls.add(idx, params);
1318                        // Already bound to the service. Just make
1319                        // sure we trigger off processing the first request.
1320                        if (idx == 0) {
1321                            mHandler.sendEmptyMessage(MCS_BOUND);
1322                        }
1323                    }
1324                    break;
1325                }
1326                case MCS_BOUND: {
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1328                    if (msg.obj != null) {
1329                        mContainerService = (IMediaContainerService) msg.obj;
1330                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1331                                System.identityHashCode(mHandler));
1332                    }
1333                    if (mContainerService == null) {
1334                        if (!mBound) {
1335                            // Something seriously wrong since we are not bound and we are not
1336                            // waiting for connection. Bail out.
1337                            Slog.e(TAG, "Cannot bind to media container service");
1338                            for (HandlerParams params : mPendingInstalls) {
1339                                // Indicate service bind error
1340                                params.serviceError();
1341                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1342                                        System.identityHashCode(params));
1343                                if (params.traceMethod != null) {
1344                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1345                                            params.traceMethod, params.traceCookie);
1346                                }
1347                                return;
1348                            }
1349                            mPendingInstalls.clear();
1350                        } else {
1351                            Slog.w(TAG, "Waiting to connect to media container service");
1352                        }
1353                    } else if (mPendingInstalls.size() > 0) {
1354                        HandlerParams params = mPendingInstalls.get(0);
1355                        if (params != null) {
1356                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1357                                    System.identityHashCode(params));
1358                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1359                            if (params.startCopy()) {
1360                                // We are done...  look for more work or to
1361                                // go idle.
1362                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1363                                        "Checking for more work or unbind...");
1364                                // Delete pending install
1365                                if (mPendingInstalls.size() > 0) {
1366                                    mPendingInstalls.remove(0);
1367                                }
1368                                if (mPendingInstalls.size() == 0) {
1369                                    if (mBound) {
1370                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1371                                                "Posting delayed MCS_UNBIND");
1372                                        removeMessages(MCS_UNBIND);
1373                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1374                                        // Unbind after a little delay, to avoid
1375                                        // continual thrashing.
1376                                        sendMessageDelayed(ubmsg, 10000);
1377                                    }
1378                                } else {
1379                                    // There are more pending requests in queue.
1380                                    // Just post MCS_BOUND message to trigger processing
1381                                    // of next pending install.
1382                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1383                                            "Posting MCS_BOUND for next work");
1384                                    mHandler.sendEmptyMessage(MCS_BOUND);
1385                                }
1386                            }
1387                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1388                        }
1389                    } else {
1390                        // Should never happen ideally.
1391                        Slog.w(TAG, "Empty queue");
1392                    }
1393                    break;
1394                }
1395                case MCS_RECONNECT: {
1396                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1397                    if (mPendingInstalls.size() > 0) {
1398                        if (mBound) {
1399                            disconnectService();
1400                        }
1401                        if (!connectToService()) {
1402                            Slog.e(TAG, "Failed to bind to media container service");
1403                            for (HandlerParams params : mPendingInstalls) {
1404                                // Indicate service bind error
1405                                params.serviceError();
1406                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1407                                        System.identityHashCode(params));
1408                            }
1409                            mPendingInstalls.clear();
1410                        }
1411                    }
1412                    break;
1413                }
1414                case MCS_UNBIND: {
1415                    // If there is no actual work left, then time to unbind.
1416                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1417
1418                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1419                        if (mBound) {
1420                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1421
1422                            disconnectService();
1423                        }
1424                    } else if (mPendingInstalls.size() > 0) {
1425                        // There are more pending requests in queue.
1426                        // Just post MCS_BOUND message to trigger processing
1427                        // of next pending install.
1428                        mHandler.sendEmptyMessage(MCS_BOUND);
1429                    }
1430
1431                    break;
1432                }
1433                case MCS_GIVE_UP: {
1434                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1435                    HandlerParams params = mPendingInstalls.remove(0);
1436                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1437                            System.identityHashCode(params));
1438                    break;
1439                }
1440                case SEND_PENDING_BROADCAST: {
1441                    String packages[];
1442                    ArrayList<String> components[];
1443                    int size = 0;
1444                    int uids[];
1445                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1446                    synchronized (mPackages) {
1447                        if (mPendingBroadcasts == null) {
1448                            return;
1449                        }
1450                        size = mPendingBroadcasts.size();
1451                        if (size <= 0) {
1452                            // Nothing to be done. Just return
1453                            return;
1454                        }
1455                        packages = new String[size];
1456                        components = new ArrayList[size];
1457                        uids = new int[size];
1458                        int i = 0;  // filling out the above arrays
1459
1460                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1461                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1462                            Iterator<Map.Entry<String, ArrayList<String>>> it
1463                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1464                                            .entrySet().iterator();
1465                            while (it.hasNext() && i < size) {
1466                                Map.Entry<String, ArrayList<String>> ent = it.next();
1467                                packages[i] = ent.getKey();
1468                                components[i] = ent.getValue();
1469                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1470                                uids[i] = (ps != null)
1471                                        ? UserHandle.getUid(packageUserId, ps.appId)
1472                                        : -1;
1473                                i++;
1474                            }
1475                        }
1476                        size = i;
1477                        mPendingBroadcasts.clear();
1478                    }
1479                    // Send broadcasts
1480                    for (int i = 0; i < size; i++) {
1481                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1482                    }
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                    break;
1485                }
1486                case START_CLEANING_PACKAGE: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    final String packageName = (String)msg.obj;
1489                    final int userId = msg.arg1;
1490                    final boolean andCode = msg.arg2 != 0;
1491                    synchronized (mPackages) {
1492                        if (userId == UserHandle.USER_ALL) {
1493                            int[] users = sUserManager.getUserIds();
1494                            for (int user : users) {
1495                                mSettings.addPackageToCleanLPw(
1496                                        new PackageCleanItem(user, packageName, andCode));
1497                            }
1498                        } else {
1499                            mSettings.addPackageToCleanLPw(
1500                                    new PackageCleanItem(userId, packageName, andCode));
1501                        }
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                    startCleaningPackages();
1505                } break;
1506                case POST_INSTALL: {
1507                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1508
1509                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1510                    mRunningInstalls.delete(msg.arg1);
1511
1512                    if (data != null) {
1513                        InstallArgs args = data.args;
1514                        PackageInstalledInfo parentRes = data.res;
1515
1516                        final boolean grantPermissions = (args.installFlags
1517                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1518                        final boolean killApp = (args.installFlags
1519                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1520                        final String[] grantedPermissions = args.installGrantPermissions;
1521
1522                        // Handle the parent package
1523                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1524                                grantedPermissions, args.observer);
1525
1526                        // Handle the child packages
1527                        final int childCount = (parentRes.addedChildPackages != null)
1528                                ? parentRes.addedChildPackages.size() : 0;
1529                        for (int i = 0; i < childCount; i++) {
1530                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1531                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1532                                    grantedPermissions, args.observer);
1533                        }
1534
1535                        // Log tracing if needed
1536                        if (args.traceMethod != null) {
1537                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1538                                    args.traceCookie);
1539                        }
1540                    } else {
1541                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1542                    }
1543
1544                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1545                } break;
1546                case UPDATED_MEDIA_STATUS: {
1547                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1548                    boolean reportStatus = msg.arg1 == 1;
1549                    boolean doGc = msg.arg2 == 1;
1550                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1551                    if (doGc) {
1552                        // Force a gc to clear up stale containers.
1553                        Runtime.getRuntime().gc();
1554                    }
1555                    if (msg.obj != null) {
1556                        @SuppressWarnings("unchecked")
1557                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1558                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1559                        // Unload containers
1560                        unloadAllContainers(args);
1561                    }
1562                    if (reportStatus) {
1563                        try {
1564                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1565                            PackageHelper.getMountService().finishMediaUpdate();
1566                        } catch (RemoteException e) {
1567                            Log.e(TAG, "MountService not running?");
1568                        }
1569                    }
1570                } break;
1571                case WRITE_SETTINGS: {
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    synchronized (mPackages) {
1574                        removeMessages(WRITE_SETTINGS);
1575                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1576                        mSettings.writeLPr();
1577                        mDirtyUsers.clear();
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                } break;
1581                case WRITE_PACKAGE_RESTRICTIONS: {
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1583                    synchronized (mPackages) {
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        for (int userId : mDirtyUsers) {
1586                            mSettings.writePackageRestrictionsLPr(userId);
1587                        }
1588                        mDirtyUsers.clear();
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                } break;
1592                case CHECK_PENDING_VERIFICATION: {
1593                    final int verificationId = msg.arg1;
1594                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1595
1596                    if ((state != null) && !state.timeoutExtended()) {
1597                        final InstallArgs args = state.getInstallArgs();
1598                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1599
1600                        Slog.i(TAG, "Verification timed out for " + originUri);
1601                        mPendingVerification.remove(verificationId);
1602
1603                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1604
1605                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1606                            Slog.i(TAG, "Continuing with installation of " + originUri);
1607                            state.setVerifierResponse(Binder.getCallingUid(),
1608                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1609                            broadcastPackageVerified(verificationId, originUri,
1610                                    PackageManager.VERIFICATION_ALLOW,
1611                                    state.getInstallArgs().getUser());
1612                            try {
1613                                ret = args.copyApk(mContainerService, true);
1614                            } catch (RemoteException e) {
1615                                Slog.e(TAG, "Could not contact the ContainerService");
1616                            }
1617                        } else {
1618                            broadcastPackageVerified(verificationId, originUri,
1619                                    PackageManager.VERIFICATION_REJECT,
1620                                    state.getInstallArgs().getUser());
1621                        }
1622
1623                        Trace.asyncTraceEnd(
1624                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1625
1626                        processPendingInstall(args, ret);
1627                        mHandler.sendEmptyMessage(MCS_UNBIND);
1628                    }
1629                    break;
1630                }
1631                case PACKAGE_VERIFIED: {
1632                    final int verificationId = msg.arg1;
1633
1634                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1635                    if (state == null) {
1636                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1637                        break;
1638                    }
1639
1640                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1641
1642                    state.setVerifierResponse(response.callerUid, response.code);
1643
1644                    if (state.isVerificationComplete()) {
1645                        mPendingVerification.remove(verificationId);
1646
1647                        final InstallArgs args = state.getInstallArgs();
1648                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1649
1650                        int ret;
1651                        if (state.isInstallAllowed()) {
1652                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1653                            broadcastPackageVerified(verificationId, originUri,
1654                                    response.code, state.getInstallArgs().getUser());
1655                            try {
1656                                ret = args.copyApk(mContainerService, true);
1657                            } catch (RemoteException e) {
1658                                Slog.e(TAG, "Could not contact the ContainerService");
1659                            }
1660                        } else {
1661                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1662                        }
1663
1664                        Trace.asyncTraceEnd(
1665                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1666
1667                        processPendingInstall(args, ret);
1668                        mHandler.sendEmptyMessage(MCS_UNBIND);
1669                    }
1670
1671                    break;
1672                }
1673                case START_INTENT_FILTER_VERIFICATIONS: {
1674                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1675                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1676                            params.replacing, params.pkg);
1677                    break;
1678                }
1679                case INTENT_FILTER_VERIFIED: {
1680                    final int verificationId = msg.arg1;
1681
1682                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1683                            verificationId);
1684                    if (state == null) {
1685                        Slog.w(TAG, "Invalid IntentFilter verification token "
1686                                + verificationId + " received");
1687                        break;
1688                    }
1689
1690                    final int userId = state.getUserId();
1691
1692                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1693                            "Processing IntentFilter verification with token:"
1694                            + verificationId + " and userId:" + userId);
1695
1696                    final IntentFilterVerificationResponse response =
1697                            (IntentFilterVerificationResponse) msg.obj;
1698
1699                    state.setVerifierResponse(response.callerUid, response.code);
1700
1701                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1702                            "IntentFilter verification with token:" + verificationId
1703                            + " and userId:" + userId
1704                            + " is settings verifier response with response code:"
1705                            + response.code);
1706
1707                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1708                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1709                                + response.getFailedDomainsString());
1710                    }
1711
1712                    if (state.isVerificationComplete()) {
1713                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1714                    } else {
1715                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1716                                "IntentFilter verification with token:" + verificationId
1717                                + " was not said to be complete");
1718                    }
1719
1720                    break;
1721                }
1722            }
1723        }
1724    }
1725
1726    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1727            boolean killApp, String[] grantedPermissions,
1728            IPackageInstallObserver2 installObserver) {
1729        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1730            // Send the removed broadcasts
1731            if (res.removedInfo != null) {
1732                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1733            }
1734
1735            // Now that we successfully installed the package, grant runtime
1736            // permissions if requested before broadcasting the install.
1737            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1738                    >= Build.VERSION_CODES.M) {
1739                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1740            }
1741
1742            final boolean update = res.removedInfo != null
1743                    && res.removedInfo.removedPackage != null;
1744
1745            // If this is the first time we have child packages for a disabled privileged
1746            // app that had no children, we grant requested runtime permissions to the new
1747            // children if the parent on the system image had them already granted.
1748            if (res.pkg.parentPackage != null) {
1749                synchronized (mPackages) {
1750                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1751                }
1752            }
1753
1754            synchronized (mPackages) {
1755                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1756            }
1757
1758            final String packageName = res.pkg.applicationInfo.packageName;
1759            Bundle extras = new Bundle(1);
1760            extras.putInt(Intent.EXTRA_UID, res.uid);
1761
1762            // Determine the set of users who are adding this package for
1763            // the first time vs. those who are seeing an update.
1764            int[] firstUsers = EMPTY_INT_ARRAY;
1765            int[] updateUsers = EMPTY_INT_ARRAY;
1766            if (res.origUsers == null || res.origUsers.length == 0) {
1767                firstUsers = res.newUsers;
1768            } else {
1769                for (int newUser : res.newUsers) {
1770                    boolean isNew = true;
1771                    for (int origUser : res.origUsers) {
1772                        if (origUser == newUser) {
1773                            isNew = false;
1774                            break;
1775                        }
1776                    }
1777                    if (isNew) {
1778                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1779                    } else {
1780                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1781                    }
1782                }
1783            }
1784
1785            // Send installed broadcasts if the install/update is not ephemeral
1786            if (!isEphemeral(res.pkg)) {
1787                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1788
1789                // Send added for users that see the package for the first time
1790                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1791                        extras, 0 /*flags*/, null /*targetPackage*/,
1792                        null /*finishedReceiver*/, firstUsers);
1793
1794                // Send added for users that don't see the package for the first time
1795                if (update) {
1796                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1797                }
1798                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1799                        extras, 0 /*flags*/, null /*targetPackage*/,
1800                        null /*finishedReceiver*/, updateUsers);
1801
1802                // Send replaced for users that don't see the package for the first time
1803                if (update) {
1804                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1805                            packageName, extras, 0 /*flags*/,
1806                            null /*targetPackage*/, null /*finishedReceiver*/,
1807                            updateUsers);
1808                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1809                            null /*package*/, null /*extras*/, 0 /*flags*/,
1810                            packageName /*targetPackage*/,
1811                            null /*finishedReceiver*/, updateUsers);
1812                }
1813
1814                // Send broadcast package appeared if forward locked/external for all users
1815                // treat asec-hosted packages like removable media on upgrade
1816                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1817                    if (DEBUG_INSTALL) {
1818                        Slog.i(TAG, "upgrading pkg " + res.pkg
1819                                + " is ASEC-hosted -> AVAILABLE");
1820                    }
1821                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1822                    ArrayList<String> pkgList = new ArrayList<>(1);
1823                    pkgList.add(packageName);
1824                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1825                }
1826            }
1827
1828            // Work that needs to happen on first install within each user
1829            if (firstUsers != null && firstUsers.length > 0) {
1830                synchronized (mPackages) {
1831                    for (int userId : firstUsers) {
1832                        // If this app is a browser and it's newly-installed for some
1833                        // users, clear any default-browser state in those users. The
1834                        // app's nature doesn't depend on the user, so we can just check
1835                        // its browser nature in any user and generalize.
1836                        if (packageIsBrowser(packageName, userId)) {
1837                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1838                        }
1839
1840                        // We may also need to apply pending (restored) runtime
1841                        // permission grants within these users.
1842                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1843                    }
1844                }
1845            }
1846
1847            // Log current value of "unknown sources" setting
1848            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1849                    getUnknownSourcesSettings());
1850
1851            // Force a gc to clear up things
1852            Runtime.getRuntime().gc();
1853
1854            // Remove the replaced package's older resources safely now
1855            // We delete after a gc for applications  on sdcard.
1856            if (res.removedInfo != null && res.removedInfo.args != null) {
1857                synchronized (mInstallLock) {
1858                    res.removedInfo.args.doPostDeleteLI(true);
1859                }
1860            }
1861        }
1862
1863        // If someone is watching installs - notify them
1864        if (installObserver != null) {
1865            try {
1866                Bundle extras = extrasForInstallResult(res);
1867                installObserver.onPackageInstalled(res.name, res.returnCode,
1868                        res.returnMsg, extras);
1869            } catch (RemoteException e) {
1870                Slog.i(TAG, "Observer no longer exists.");
1871            }
1872        }
1873    }
1874
1875    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1876            PackageParser.Package pkg) {
1877        if (pkg.parentPackage == null) {
1878            return;
1879        }
1880        if (pkg.requestedPermissions == null) {
1881            return;
1882        }
1883        final PackageSetting disabledSysParentPs = mSettings
1884                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1885        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1886                || !disabledSysParentPs.isPrivileged()
1887                || (disabledSysParentPs.childPackageNames != null
1888                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1889            return;
1890        }
1891        final int[] allUserIds = sUserManager.getUserIds();
1892        final int permCount = pkg.requestedPermissions.size();
1893        for (int i = 0; i < permCount; i++) {
1894            String permission = pkg.requestedPermissions.get(i);
1895            BasePermission bp = mSettings.mPermissions.get(permission);
1896            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1897                continue;
1898            }
1899            for (int userId : allUserIds) {
1900                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1901                        permission, userId)) {
1902                    grantRuntimePermission(pkg.packageName, permission, userId);
1903                }
1904            }
1905        }
1906    }
1907
1908    private StorageEventListener mStorageListener = new StorageEventListener() {
1909        @Override
1910        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1911            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1912                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1913                    final String volumeUuid = vol.getFsUuid();
1914
1915                    // Clean up any users or apps that were removed or recreated
1916                    // while this volume was missing
1917                    reconcileUsers(volumeUuid);
1918                    reconcileApps(volumeUuid);
1919
1920                    // Clean up any install sessions that expired or were
1921                    // cancelled while this volume was missing
1922                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1923
1924                    loadPrivatePackages(vol);
1925
1926                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1927                    unloadPrivatePackages(vol);
1928                }
1929            }
1930
1931            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1932                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1933                    updateExternalMediaStatus(true, false);
1934                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1935                    updateExternalMediaStatus(false, false);
1936                }
1937            }
1938        }
1939
1940        @Override
1941        public void onVolumeForgotten(String fsUuid) {
1942            if (TextUtils.isEmpty(fsUuid)) {
1943                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1944                return;
1945            }
1946
1947            // Remove any apps installed on the forgotten volume
1948            synchronized (mPackages) {
1949                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1950                for (PackageSetting ps : packages) {
1951                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1952                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1953                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1954                }
1955
1956                mSettings.onVolumeForgotten(fsUuid);
1957                mSettings.writeLPr();
1958            }
1959        }
1960    };
1961
1962    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1963            String[] grantedPermissions) {
1964        for (int userId : userIds) {
1965            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1966        }
1967
1968        // We could have touched GID membership, so flush out packages.list
1969        synchronized (mPackages) {
1970            mSettings.writePackageListLPr();
1971        }
1972    }
1973
1974    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1975            String[] grantedPermissions) {
1976        SettingBase sb = (SettingBase) pkg.mExtras;
1977        if (sb == null) {
1978            return;
1979        }
1980
1981        PermissionsState permissionsState = sb.getPermissionsState();
1982
1983        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1984                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1985
1986        synchronized (mPackages) {
1987            for (String permission : pkg.requestedPermissions) {
1988                BasePermission bp = mSettings.mPermissions.get(permission);
1989                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1990                        && (grantedPermissions == null
1991                               || ArrayUtils.contains(grantedPermissions, permission))) {
1992                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1993                    // Installer cannot change immutable permissions.
1994                    if ((flags & immutableFlags) == 0) {
1995                        grantRuntimePermission(pkg.packageName, permission, userId);
1996                    }
1997                }
1998            }
1999        }
2000    }
2001
2002    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2003        Bundle extras = null;
2004        switch (res.returnCode) {
2005            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2006                extras = new Bundle();
2007                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2008                        res.origPermission);
2009                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2010                        res.origPackage);
2011                break;
2012            }
2013            case PackageManager.INSTALL_SUCCEEDED: {
2014                extras = new Bundle();
2015                extras.putBoolean(Intent.EXTRA_REPLACING,
2016                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2017                break;
2018            }
2019        }
2020        return extras;
2021    }
2022
2023    void scheduleWriteSettingsLocked() {
2024        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2025            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2026        }
2027    }
2028
2029    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2030        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2031        scheduleWritePackageRestrictionsLocked(userId);
2032    }
2033
2034    void scheduleWritePackageRestrictionsLocked(int userId) {
2035        final int[] userIds = (userId == UserHandle.USER_ALL)
2036                ? sUserManager.getUserIds() : new int[]{userId};
2037        for (int nextUserId : userIds) {
2038            if (!sUserManager.exists(nextUserId)) return;
2039            mDirtyUsers.add(nextUserId);
2040            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2041                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2042            }
2043        }
2044    }
2045
2046    public static PackageManagerService main(Context context, Installer installer,
2047            boolean factoryTest, boolean onlyCore) {
2048        // Self-check for initial settings.
2049        PackageManagerServiceCompilerMapping.checkProperties();
2050
2051        PackageManagerService m = new PackageManagerService(context, installer,
2052                factoryTest, onlyCore);
2053        m.enableSystemUserPackages();
2054        ServiceManager.addService("package", m);
2055        return m;
2056    }
2057
2058    private void enableSystemUserPackages() {
2059        if (!UserManager.isSplitSystemUser()) {
2060            return;
2061        }
2062        // For system user, enable apps based on the following conditions:
2063        // - app is whitelisted or belong to one of these groups:
2064        //   -- system app which has no launcher icons
2065        //   -- system app which has INTERACT_ACROSS_USERS permission
2066        //   -- system IME app
2067        // - app is not in the blacklist
2068        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2069        Set<String> enableApps = new ArraySet<>();
2070        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2071                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2072                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2073        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2074        enableApps.addAll(wlApps);
2075        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2076                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2077        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2078        enableApps.removeAll(blApps);
2079        Log.i(TAG, "Applications installed for system user: " + enableApps);
2080        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2081                UserHandle.SYSTEM);
2082        final int allAppsSize = allAps.size();
2083        synchronized (mPackages) {
2084            for (int i = 0; i < allAppsSize; i++) {
2085                String pName = allAps.get(i);
2086                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2087                // Should not happen, but we shouldn't be failing if it does
2088                if (pkgSetting == null) {
2089                    continue;
2090                }
2091                boolean install = enableApps.contains(pName);
2092                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2093                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2094                            + " for system user");
2095                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2096                }
2097            }
2098        }
2099    }
2100
2101    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2102        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2103                Context.DISPLAY_SERVICE);
2104        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2105    }
2106
2107    public PackageManagerService(Context context, Installer installer,
2108            boolean factoryTest, boolean onlyCore) {
2109        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2110                SystemClock.uptimeMillis());
2111
2112        if (mSdkVersion <= 0) {
2113            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2114        }
2115
2116        mContext = context;
2117        mFactoryTest = factoryTest;
2118        mOnlyCore = onlyCore;
2119        mMetrics = new DisplayMetrics();
2120        mSettings = new Settings(mPackages);
2121        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2122                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2123        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2124                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2125        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2126                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2127        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2128                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2129        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2130                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2131        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2132                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2133
2134        String separateProcesses = SystemProperties.get("debug.separate_processes");
2135        if (separateProcesses != null && separateProcesses.length() > 0) {
2136            if ("*".equals(separateProcesses)) {
2137                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2138                mSeparateProcesses = null;
2139                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2140            } else {
2141                mDefParseFlags = 0;
2142                mSeparateProcesses = separateProcesses.split(",");
2143                Slog.w(TAG, "Running with debug.separate_processes: "
2144                        + separateProcesses);
2145            }
2146        } else {
2147            mDefParseFlags = 0;
2148            mSeparateProcesses = null;
2149        }
2150
2151        mInstaller = installer;
2152        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2153                "*dexopt*");
2154        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2155
2156        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2157                FgThread.get().getLooper());
2158
2159        getDefaultDisplayMetrics(context, mMetrics);
2160
2161        SystemConfig systemConfig = SystemConfig.getInstance();
2162        mGlobalGids = systemConfig.getGlobalGids();
2163        mSystemPermissions = systemConfig.getSystemPermissions();
2164        mAvailableFeatures = systemConfig.getAvailableFeatures();
2165
2166        synchronized (mInstallLock) {
2167        // writer
2168        synchronized (mPackages) {
2169            mHandlerThread = new ServiceThread(TAG,
2170                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2171            mHandlerThread.start();
2172            mHandler = new PackageHandler(mHandlerThread.getLooper());
2173            mProcessLoggingHandler = new ProcessLoggingHandler();
2174            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2175
2176            File dataDir = Environment.getDataDirectory();
2177            mAppInstallDir = new File(dataDir, "app");
2178            mAppLib32InstallDir = new File(dataDir, "app-lib");
2179            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2180            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2181            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2182
2183            sUserManager = new UserManagerService(context, this, mPackages);
2184
2185            // Propagate permission configuration in to package manager.
2186            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2187                    = systemConfig.getPermissions();
2188            for (int i=0; i<permConfig.size(); i++) {
2189                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2190                BasePermission bp = mSettings.mPermissions.get(perm.name);
2191                if (bp == null) {
2192                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2193                    mSettings.mPermissions.put(perm.name, bp);
2194                }
2195                if (perm.gids != null) {
2196                    bp.setGids(perm.gids, perm.perUser);
2197                }
2198            }
2199
2200            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2201            for (int i=0; i<libConfig.size(); i++) {
2202                mSharedLibraries.put(libConfig.keyAt(i),
2203                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2204            }
2205
2206            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2207
2208            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2209
2210            String customResolverActivity = Resources.getSystem().getString(
2211                    R.string.config_customResolverActivity);
2212            if (TextUtils.isEmpty(customResolverActivity)) {
2213                customResolverActivity = null;
2214            } else {
2215                mCustomResolverComponentName = ComponentName.unflattenFromString(
2216                        customResolverActivity);
2217            }
2218
2219            long startTime = SystemClock.uptimeMillis();
2220
2221            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2222                    startTime);
2223
2224            // Set flag to monitor and not change apk file paths when
2225            // scanning install directories.
2226            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2227
2228            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2229            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2230
2231            if (bootClassPath == null) {
2232                Slog.w(TAG, "No BOOTCLASSPATH found!");
2233            }
2234
2235            if (systemServerClassPath == null) {
2236                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2237            }
2238
2239            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2240            final String[] dexCodeInstructionSets =
2241                    getDexCodeInstructionSets(
2242                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2243
2244            /**
2245             * Ensure all external libraries have had dexopt run on them.
2246             */
2247            if (mSharedLibraries.size() > 0) {
2248                // NOTE: For now, we're compiling these system "shared libraries"
2249                // (and framework jars) into all available architectures. It's possible
2250                // to compile them only when we come across an app that uses them (there's
2251                // already logic for that in scanPackageLI) but that adds some complexity.
2252                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2253                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2254                        final String lib = libEntry.path;
2255                        if (lib == null) {
2256                            continue;
2257                        }
2258
2259                        try {
2260                            // Shared libraries do not have profiles so we perform a full
2261                            // AOT compilation (if needed).
2262                            int dexoptNeeded = DexFile.getDexOptNeeded(
2263                                    lib, dexCodeInstructionSet,
2264                                    getCompilerFilterForReason(REASON_SHARED_APK),
2265                                    false /* newProfile */);
2266                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2267                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2268                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2269                                        getCompilerFilterForReason(REASON_SHARED_APK),
2270                                        StorageManager.UUID_PRIVATE_INTERNAL);
2271                            }
2272                        } catch (FileNotFoundException e) {
2273                            Slog.w(TAG, "Library not found: " + lib);
2274                        } catch (IOException | InstallerException e) {
2275                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2276                                    + e.getMessage());
2277                        }
2278                    }
2279                }
2280            }
2281
2282            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2283
2284            final VersionInfo ver = mSettings.getInternalVersion();
2285            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2286
2287            // when upgrading from pre-M, promote system app permissions from install to runtime
2288            mPromoteSystemApps =
2289                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2290
2291            // save off the names of pre-existing system packages prior to scanning; we don't
2292            // want to automatically grant runtime permissions for new system apps
2293            if (mPromoteSystemApps) {
2294                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2295                while (pkgSettingIter.hasNext()) {
2296                    PackageSetting ps = pkgSettingIter.next();
2297                    if (isSystemApp(ps)) {
2298                        mExistingSystemPackages.add(ps.name);
2299                    }
2300                }
2301            }
2302
2303            // When upgrading from pre-N, we need to handle package extraction like first boot,
2304            // as there is no profiling data available.
2305            mIsPreNUpgrade = !mSettings.isNWorkDone();
2306            mSettings.setNWorkDone();
2307
2308            // Collect vendor overlay packages.
2309            // (Do this before scanning any apps.)
2310            // For security and version matching reason, only consider
2311            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2312            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2313            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2314                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2315
2316            // Find base frameworks (resource packages without code).
2317            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2318                    | PackageParser.PARSE_IS_SYSTEM_DIR
2319                    | PackageParser.PARSE_IS_PRIVILEGED,
2320                    scanFlags | SCAN_NO_DEX, 0);
2321
2322            // Collected privileged system packages.
2323            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2324            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2325                    | PackageParser.PARSE_IS_SYSTEM_DIR
2326                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2327
2328            // Collect ordinary system packages.
2329            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2330            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2331                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2332
2333            // Collect all vendor packages.
2334            File vendorAppDir = new File("/vendor/app");
2335            try {
2336                vendorAppDir = vendorAppDir.getCanonicalFile();
2337            } catch (IOException e) {
2338                // failed to look up canonical path, continue with original one
2339            }
2340            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2341                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2342
2343            // Collect all OEM packages.
2344            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2345            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2346                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2347
2348            // Prune any system packages that no longer exist.
2349            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2350            if (!mOnlyCore) {
2351                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2352                while (psit.hasNext()) {
2353                    PackageSetting ps = psit.next();
2354
2355                    /*
2356                     * If this is not a system app, it can't be a
2357                     * disable system app.
2358                     */
2359                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2360                        continue;
2361                    }
2362
2363                    /*
2364                     * If the package is scanned, it's not erased.
2365                     */
2366                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2367                    if (scannedPkg != null) {
2368                        /*
2369                         * If the system app is both scanned and in the
2370                         * disabled packages list, then it must have been
2371                         * added via OTA. Remove it from the currently
2372                         * scanned package so the previously user-installed
2373                         * application can be scanned.
2374                         */
2375                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2376                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2377                                    + ps.name + "; removing system app.  Last known codePath="
2378                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2379                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2380                                    + scannedPkg.mVersionCode);
2381                            removePackageLI(scannedPkg, true);
2382                            mExpectingBetter.put(ps.name, ps.codePath);
2383                        }
2384
2385                        continue;
2386                    }
2387
2388                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2389                        psit.remove();
2390                        logCriticalInfo(Log.WARN, "System package " + ps.name
2391                                + " no longer exists; it's data will be wiped");
2392                        // Actual deletion of code and data will be handled by later
2393                        // reconciliation step
2394                    } else {
2395                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2396                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2397                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2398                        }
2399                    }
2400                }
2401            }
2402
2403            //look for any incomplete package installations
2404            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2405            for (int i = 0; i < deletePkgsList.size(); i++) {
2406                // Actual deletion of code and data will be handled by later
2407                // reconciliation step
2408                final String packageName = deletePkgsList.get(i).name;
2409                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2410                synchronized (mPackages) {
2411                    mSettings.removePackageLPw(packageName);
2412                }
2413            }
2414
2415            //delete tmp files
2416            deleteTempPackageFiles();
2417
2418            // Remove any shared userIDs that have no associated packages
2419            mSettings.pruneSharedUsersLPw();
2420
2421            if (!mOnlyCore) {
2422                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2423                        SystemClock.uptimeMillis());
2424                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2425
2426                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2427                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2428
2429                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2430                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2431
2432                /**
2433                 * Remove disable package settings for any updated system
2434                 * apps that were removed via an OTA. If they're not a
2435                 * previously-updated app, remove them completely.
2436                 * Otherwise, just revoke their system-level permissions.
2437                 */
2438                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2439                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2440                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2441
2442                    String msg;
2443                    if (deletedPkg == null) {
2444                        msg = "Updated system package " + deletedAppName
2445                                + " no longer exists; it's data will be wiped";
2446                        // Actual deletion of code and data will be handled by later
2447                        // reconciliation step
2448                    } else {
2449                        msg = "Updated system app + " + deletedAppName
2450                                + " no longer present; removing system privileges for "
2451                                + deletedAppName;
2452
2453                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2454
2455                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2456                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2457                    }
2458                    logCriticalInfo(Log.WARN, msg);
2459                }
2460
2461                /**
2462                 * Make sure all system apps that we expected to appear on
2463                 * the userdata partition actually showed up. If they never
2464                 * appeared, crawl back and revive the system version.
2465                 */
2466                for (int i = 0; i < mExpectingBetter.size(); i++) {
2467                    final String packageName = mExpectingBetter.keyAt(i);
2468                    if (!mPackages.containsKey(packageName)) {
2469                        final File scanFile = mExpectingBetter.valueAt(i);
2470
2471                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2472                                + " but never showed up; reverting to system");
2473
2474                        final int reparseFlags;
2475                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2476                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2477                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2478                                    | PackageParser.PARSE_IS_PRIVILEGED;
2479                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2480                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2481                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2482                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2483                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2484                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2485                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2486                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2487                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2488                        } else {
2489                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2490                            continue;
2491                        }
2492
2493                        mSettings.enableSystemPackageLPw(packageName);
2494
2495                        try {
2496                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2497                        } catch (PackageManagerException e) {
2498                            Slog.e(TAG, "Failed to parse original system package: "
2499                                    + e.getMessage());
2500                        }
2501                    }
2502                }
2503            }
2504            mExpectingBetter.clear();
2505
2506            // Resolve protected action filters. Only the setup wizard is allowed to
2507            // have a high priority filter for these actions.
2508            mSetupWizardPackage = getSetupWizardPackageName();
2509            if (mProtectedFilters.size() > 0) {
2510                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2511                    Slog.i(TAG, "No setup wizard;"
2512                        + " All protected intents capped to priority 0");
2513                }
2514                for (ActivityIntentInfo filter : mProtectedFilters) {
2515                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2516                        if (DEBUG_FILTERS) {
2517                            Slog.i(TAG, "Found setup wizard;"
2518                                + " allow priority " + filter.getPriority() + ";"
2519                                + " package: " + filter.activity.info.packageName
2520                                + " activity: " + filter.activity.className
2521                                + " priority: " + filter.getPriority());
2522                        }
2523                        // skip setup wizard; allow it to keep the high priority filter
2524                        continue;
2525                    }
2526                    Slog.w(TAG, "Protected action; cap priority to 0;"
2527                            + " package: " + filter.activity.info.packageName
2528                            + " activity: " + filter.activity.className
2529                            + " origPrio: " + filter.getPriority());
2530                    filter.setPriority(0);
2531                }
2532            }
2533            mDeferProtectedFilters = false;
2534            mProtectedFilters.clear();
2535
2536            // Now that we know all of the shared libraries, update all clients to have
2537            // the correct library paths.
2538            updateAllSharedLibrariesLPw();
2539
2540            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2541                // NOTE: We ignore potential failures here during a system scan (like
2542                // the rest of the commands above) because there's precious little we
2543                // can do about it. A settings error is reported, though.
2544                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2545                        false /* boot complete */);
2546            }
2547
2548            // Now that we know all the packages we are keeping,
2549            // read and update their last usage times.
2550            mPackageUsage.readLP();
2551
2552            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2553                    SystemClock.uptimeMillis());
2554            Slog.i(TAG, "Time to scan packages: "
2555                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2556                    + " seconds");
2557
2558            // If the platform SDK has changed since the last time we booted,
2559            // we need to re-grant app permission to catch any new ones that
2560            // appear.  This is really a hack, and means that apps can in some
2561            // cases get permissions that the user didn't initially explicitly
2562            // allow...  it would be nice to have some better way to handle
2563            // this situation.
2564            int updateFlags = UPDATE_PERMISSIONS_ALL;
2565            if (ver.sdkVersion != mSdkVersion) {
2566                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2567                        + mSdkVersion + "; regranting permissions for internal storage");
2568                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2569            }
2570            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2571            ver.sdkVersion = mSdkVersion;
2572
2573            // If this is the first boot or an update from pre-M, and it is a normal
2574            // boot, then we need to initialize the default preferred apps across
2575            // all defined users.
2576            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2577                for (UserInfo user : sUserManager.getUsers(true)) {
2578                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2579                    applyFactoryDefaultBrowserLPw(user.id);
2580                    primeDomainVerificationsLPw(user.id);
2581                }
2582            }
2583
2584            // Prepare storage for system user really early during boot,
2585            // since core system apps like SettingsProvider and SystemUI
2586            // can't wait for user to start
2587            final int storageFlags;
2588            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2589                storageFlags = StorageManager.FLAG_STORAGE_DE;
2590            } else {
2591                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2592            }
2593            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2594                    storageFlags);
2595
2596            // If this is first boot after an OTA, and a normal boot, then
2597            // we need to clear code cache directories.
2598            if (mIsUpgrade && !onlyCore) {
2599                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2600                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2601                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2602                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2603                        // No apps are running this early, so no need to freeze
2604                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2605                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2606                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2607                    }
2608                    clearAppProfilesLIF(ps.pkg);
2609                }
2610                ver.fingerprint = Build.FINGERPRINT;
2611            }
2612
2613            checkDefaultBrowser();
2614
2615            // clear only after permissions and other defaults have been updated
2616            mExistingSystemPackages.clear();
2617            mPromoteSystemApps = false;
2618
2619            // All the changes are done during package scanning.
2620            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2621
2622            // can downgrade to reader
2623            mSettings.writeLPr();
2624
2625            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2626                    SystemClock.uptimeMillis());
2627
2628            if (!mOnlyCore) {
2629                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2630                mRequiredInstallerPackage = getRequiredInstallerLPr();
2631                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2632                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2633                        mIntentFilterVerifierComponent);
2634                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2635                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2636                getRequiredSharedLibraryLPr(
2637                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2638            } else {
2639                mRequiredVerifierPackage = null;
2640                mRequiredInstallerPackage = null;
2641                mIntentFilterVerifierComponent = null;
2642                mIntentFilterVerifier = null;
2643                mServicesSystemSharedLibraryPackageName = null;
2644            }
2645
2646            mInstallerService = new PackageInstallerService(context, this);
2647
2648            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2649            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2650            // both the installer and resolver must be present to enable ephemeral
2651            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2652                if (DEBUG_EPHEMERAL) {
2653                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2654                            + " installer:" + ephemeralInstallerComponent);
2655                }
2656                mEphemeralResolverComponent = ephemeralResolverComponent;
2657                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2658                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2659                mEphemeralResolverConnection =
2660                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2661            } else {
2662                if (DEBUG_EPHEMERAL) {
2663                    final String missingComponent =
2664                            (ephemeralResolverComponent == null)
2665                            ? (ephemeralInstallerComponent == null)
2666                                    ? "resolver and installer"
2667                                    : "resolver"
2668                            : "installer";
2669                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2670                }
2671                mEphemeralResolverComponent = null;
2672                mEphemeralInstallerComponent = null;
2673                mEphemeralResolverConnection = null;
2674            }
2675
2676            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2677        } // synchronized (mPackages)
2678        } // synchronized (mInstallLock)
2679
2680        // Now after opening every single application zip, make sure they
2681        // are all flushed.  Not really needed, but keeps things nice and
2682        // tidy.
2683        Runtime.getRuntime().gc();
2684
2685        // The initial scanning above does many calls into installd while
2686        // holding the mPackages lock, but we're mostly interested in yelling
2687        // once we have a booted system.
2688        mInstaller.setWarnIfHeld(mPackages);
2689
2690        // Expose private service for system components to use.
2691        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2692    }
2693
2694    @Override
2695    public boolean isFirstBoot() {
2696        return !mRestoredSettings;
2697    }
2698
2699    @Override
2700    public boolean isOnlyCoreApps() {
2701        return mOnlyCore;
2702    }
2703
2704    @Override
2705    public boolean isUpgrade() {
2706        return mIsUpgrade;
2707    }
2708
2709    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2710        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2711
2712        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2713                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2714                UserHandle.USER_SYSTEM);
2715        if (matches.size() == 1) {
2716            return matches.get(0).getComponentInfo().packageName;
2717        } else {
2718            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2719            return null;
2720        }
2721    }
2722
2723    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2724        synchronized (mPackages) {
2725            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2726            if (libraryEntry == null) {
2727                throw new IllegalStateException("Missing required shared library:" + libraryName);
2728            }
2729            return libraryEntry.apk;
2730        }
2731    }
2732
2733    private @NonNull String getRequiredInstallerLPr() {
2734        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2735        intent.addCategory(Intent.CATEGORY_DEFAULT);
2736        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2737
2738        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2739                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2740                UserHandle.USER_SYSTEM);
2741        if (matches.size() == 1) {
2742            ResolveInfo resolveInfo = matches.get(0);
2743            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2744                throw new RuntimeException("The installer must be a privileged app");
2745            }
2746            return matches.get(0).getComponentInfo().packageName;
2747        } else {
2748            throw new RuntimeException("There must be exactly one installer; found " + matches);
2749        }
2750    }
2751
2752    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2753        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2754
2755        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757                UserHandle.USER_SYSTEM);
2758        ResolveInfo best = null;
2759        final int N = matches.size();
2760        for (int i = 0; i < N; i++) {
2761            final ResolveInfo cur = matches.get(i);
2762            final String packageName = cur.getComponentInfo().packageName;
2763            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2764                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2765                continue;
2766            }
2767
2768            if (best == null || cur.priority > best.priority) {
2769                best = cur;
2770            }
2771        }
2772
2773        if (best != null) {
2774            return best.getComponentInfo().getComponentName();
2775        } else {
2776            throw new RuntimeException("There must be at least one intent filter verifier");
2777        }
2778    }
2779
2780    private @Nullable ComponentName getEphemeralResolverLPr() {
2781        final String[] packageArray =
2782                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2783        if (packageArray.length == 0) {
2784            if (DEBUG_EPHEMERAL) {
2785                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2786            }
2787            return null;
2788        }
2789
2790        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2791        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2792                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2793                UserHandle.USER_SYSTEM);
2794
2795        final int N = resolvers.size();
2796        if (N == 0) {
2797            if (DEBUG_EPHEMERAL) {
2798                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2799            }
2800            return null;
2801        }
2802
2803        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2804        for (int i = 0; i < N; i++) {
2805            final ResolveInfo info = resolvers.get(i);
2806
2807            if (info.serviceInfo == null) {
2808                continue;
2809            }
2810
2811            final String packageName = info.serviceInfo.packageName;
2812            if (!possiblePackages.contains(packageName)) {
2813                if (DEBUG_EPHEMERAL) {
2814                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2815                            + " pkg: " + packageName + ", info:" + info);
2816                }
2817                continue;
2818            }
2819
2820            if (DEBUG_EPHEMERAL) {
2821                Slog.v(TAG, "Ephemeral resolver found;"
2822                        + " pkg: " + packageName + ", info:" + info);
2823            }
2824            return new ComponentName(packageName, info.serviceInfo.name);
2825        }
2826        if (DEBUG_EPHEMERAL) {
2827            Slog.v(TAG, "Ephemeral resolver NOT found");
2828        }
2829        return null;
2830    }
2831
2832    private @Nullable ComponentName getEphemeralInstallerLPr() {
2833        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2834        intent.addCategory(Intent.CATEGORY_DEFAULT);
2835        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2836
2837        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2838                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2839                UserHandle.USER_SYSTEM);
2840        if (matches.size() == 0) {
2841            return null;
2842        } else if (matches.size() == 1) {
2843            return matches.get(0).getComponentInfo().getComponentName();
2844        } else {
2845            throw new RuntimeException(
2846                    "There must be at most one ephemeral installer; found " + matches);
2847        }
2848    }
2849
2850    private void primeDomainVerificationsLPw(int userId) {
2851        if (DEBUG_DOMAIN_VERIFICATION) {
2852            Slog.d(TAG, "Priming domain verifications in user " + userId);
2853        }
2854
2855        SystemConfig systemConfig = SystemConfig.getInstance();
2856        ArraySet<String> packages = systemConfig.getLinkedApps();
2857        ArraySet<String> domains = new ArraySet<String>();
2858
2859        for (String packageName : packages) {
2860            PackageParser.Package pkg = mPackages.get(packageName);
2861            if (pkg != null) {
2862                if (!pkg.isSystemApp()) {
2863                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2864                    continue;
2865                }
2866
2867                domains.clear();
2868                for (PackageParser.Activity a : pkg.activities) {
2869                    for (ActivityIntentInfo filter : a.intents) {
2870                        if (hasValidDomains(filter)) {
2871                            domains.addAll(filter.getHostsList());
2872                        }
2873                    }
2874                }
2875
2876                if (domains.size() > 0) {
2877                    if (DEBUG_DOMAIN_VERIFICATION) {
2878                        Slog.v(TAG, "      + " + packageName);
2879                    }
2880                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2881                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2882                    // and then 'always' in the per-user state actually used for intent resolution.
2883                    final IntentFilterVerificationInfo ivi;
2884                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2885                            new ArrayList<String>(domains));
2886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2887                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2888                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2889                } else {
2890                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2891                            + "' does not handle web links");
2892                }
2893            } else {
2894                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2895            }
2896        }
2897
2898        scheduleWritePackageRestrictionsLocked(userId);
2899        scheduleWriteSettingsLocked();
2900    }
2901
2902    private void applyFactoryDefaultBrowserLPw(int userId) {
2903        // The default browser app's package name is stored in a string resource,
2904        // with a product-specific overlay used for vendor customization.
2905        String browserPkg = mContext.getResources().getString(
2906                com.android.internal.R.string.default_browser);
2907        if (!TextUtils.isEmpty(browserPkg)) {
2908            // non-empty string => required to be a known package
2909            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2910            if (ps == null) {
2911                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2912                browserPkg = null;
2913            } else {
2914                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2915            }
2916        }
2917
2918        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2919        // default.  If there's more than one, just leave everything alone.
2920        if (browserPkg == null) {
2921            calculateDefaultBrowserLPw(userId);
2922        }
2923    }
2924
2925    private void calculateDefaultBrowserLPw(int userId) {
2926        List<String> allBrowsers = resolveAllBrowserApps(userId);
2927        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2928        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2929    }
2930
2931    private List<String> resolveAllBrowserApps(int userId) {
2932        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2933        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2934                PackageManager.MATCH_ALL, userId);
2935
2936        final int count = list.size();
2937        List<String> result = new ArrayList<String>(count);
2938        for (int i=0; i<count; i++) {
2939            ResolveInfo info = list.get(i);
2940            if (info.activityInfo == null
2941                    || !info.handleAllWebDataURI
2942                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2943                    || result.contains(info.activityInfo.packageName)) {
2944                continue;
2945            }
2946            result.add(info.activityInfo.packageName);
2947        }
2948
2949        return result;
2950    }
2951
2952    private boolean packageIsBrowser(String packageName, int userId) {
2953        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2954                PackageManager.MATCH_ALL, userId);
2955        final int N = list.size();
2956        for (int i = 0; i < N; i++) {
2957            ResolveInfo info = list.get(i);
2958            if (packageName.equals(info.activityInfo.packageName)) {
2959                return true;
2960            }
2961        }
2962        return false;
2963    }
2964
2965    private void checkDefaultBrowser() {
2966        final int myUserId = UserHandle.myUserId();
2967        final String packageName = getDefaultBrowserPackageName(myUserId);
2968        if (packageName != null) {
2969            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2970            if (info == null) {
2971                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2972                synchronized (mPackages) {
2973                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2974                }
2975            }
2976        }
2977    }
2978
2979    @Override
2980    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2981            throws RemoteException {
2982        try {
2983            return super.onTransact(code, data, reply, flags);
2984        } catch (RuntimeException e) {
2985            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2986                Slog.wtf(TAG, "Package Manager Crash", e);
2987            }
2988            throw e;
2989        }
2990    }
2991
2992    static int[] appendInts(int[] cur, int[] add) {
2993        if (add == null) return cur;
2994        if (cur == null) return add;
2995        final int N = add.length;
2996        for (int i=0; i<N; i++) {
2997            cur = appendInt(cur, add[i]);
2998        }
2999        return cur;
3000    }
3001
3002    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3003        if (!sUserManager.exists(userId)) return null;
3004        if (ps == null) {
3005            return null;
3006        }
3007        final PackageParser.Package p = ps.pkg;
3008        if (p == null) {
3009            return null;
3010        }
3011
3012        final PermissionsState permissionsState = ps.getPermissionsState();
3013
3014        final int[] gids = permissionsState.computeGids(userId);
3015        final Set<String> permissions = permissionsState.getPermissions(userId);
3016        final PackageUserState state = ps.readUserState(userId);
3017
3018        return PackageParser.generatePackageInfo(p, gids, flags,
3019                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3020    }
3021
3022    @Override
3023    public void checkPackageStartable(String packageName, int userId) {
3024        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3025
3026        synchronized (mPackages) {
3027            final PackageSetting ps = mSettings.mPackages.get(packageName);
3028            if (ps == null) {
3029                throw new SecurityException("Package " + packageName + " was not found!");
3030            }
3031
3032            if (!ps.getInstalled(userId)) {
3033                throw new SecurityException(
3034                        "Package " + packageName + " was not installed for user " + userId + "!");
3035            }
3036
3037            if (mSafeMode && !ps.isSystem()) {
3038                throw new SecurityException("Package " + packageName + " not a system app!");
3039            }
3040
3041            if (mFrozenPackages.contains(packageName)) {
3042                throw new SecurityException("Package " + packageName + " is currently frozen!");
3043            }
3044
3045            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3046                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3047                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3048            }
3049        }
3050    }
3051
3052    @Override
3053    public boolean isPackageAvailable(String packageName, int userId) {
3054        if (!sUserManager.exists(userId)) return false;
3055        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3056                false /* requireFullPermission */, false /* checkShell */, "is package available");
3057        synchronized (mPackages) {
3058            PackageParser.Package p = mPackages.get(packageName);
3059            if (p != null) {
3060                final PackageSetting ps = (PackageSetting) p.mExtras;
3061                if (ps != null) {
3062                    final PackageUserState state = ps.readUserState(userId);
3063                    if (state != null) {
3064                        return PackageParser.isAvailable(state);
3065                    }
3066                }
3067            }
3068        }
3069        return false;
3070    }
3071
3072    @Override
3073    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3074        if (!sUserManager.exists(userId)) return null;
3075        flags = updateFlagsForPackage(flags, userId, packageName);
3076        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3077                false /* requireFullPermission */, false /* checkShell */, "get package info");
3078        // reader
3079        synchronized (mPackages) {
3080            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3081            PackageParser.Package p = null;
3082            if (matchFactoryOnly) {
3083                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3084                if (ps != null) {
3085                    return generatePackageInfo(ps, flags, userId);
3086                }
3087            }
3088            if (p == null) {
3089                p = mPackages.get(packageName);
3090                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3091                    return null;
3092                }
3093            }
3094            if (DEBUG_PACKAGE_INFO)
3095                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3096            if (p != null) {
3097                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3098            }
3099            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3100                final PackageSetting ps = mSettings.mPackages.get(packageName);
3101                return generatePackageInfo(ps, flags, userId);
3102            }
3103        }
3104        return null;
3105    }
3106
3107    @Override
3108    public String[] currentToCanonicalPackageNames(String[] names) {
3109        String[] out = new String[names.length];
3110        // reader
3111        synchronized (mPackages) {
3112            for (int i=names.length-1; i>=0; i--) {
3113                PackageSetting ps = mSettings.mPackages.get(names[i]);
3114                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3115            }
3116        }
3117        return out;
3118    }
3119
3120    @Override
3121    public String[] canonicalToCurrentPackageNames(String[] names) {
3122        String[] out = new String[names.length];
3123        // reader
3124        synchronized (mPackages) {
3125            for (int i=names.length-1; i>=0; i--) {
3126                String cur = mSettings.mRenamedPackages.get(names[i]);
3127                out[i] = cur != null ? cur : names[i];
3128            }
3129        }
3130        return out;
3131    }
3132
3133    @Override
3134    public int getPackageUid(String packageName, int flags, int userId) {
3135        if (!sUserManager.exists(userId)) return -1;
3136        flags = updateFlagsForPackage(flags, userId, packageName);
3137        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3138                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3139
3140        // reader
3141        synchronized (mPackages) {
3142            final PackageParser.Package p = mPackages.get(packageName);
3143            if (p != null && p.isMatch(flags)) {
3144                return UserHandle.getUid(userId, p.applicationInfo.uid);
3145            }
3146            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3147                final PackageSetting ps = mSettings.mPackages.get(packageName);
3148                if (ps != null && ps.isMatch(flags)) {
3149                    return UserHandle.getUid(userId, ps.appId);
3150                }
3151            }
3152        }
3153
3154        return -1;
3155    }
3156
3157    @Override
3158    public int[] getPackageGids(String packageName, int flags, int userId) {
3159        if (!sUserManager.exists(userId)) return null;
3160        flags = updateFlagsForPackage(flags, userId, packageName);
3161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3162                false /* requireFullPermission */, false /* checkShell */,
3163                "getPackageGids");
3164
3165        // reader
3166        synchronized (mPackages) {
3167            final PackageParser.Package p = mPackages.get(packageName);
3168            if (p != null && p.isMatch(flags)) {
3169                PackageSetting ps = (PackageSetting) p.mExtras;
3170                return ps.getPermissionsState().computeGids(userId);
3171            }
3172            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3173                final PackageSetting ps = mSettings.mPackages.get(packageName);
3174                if (ps != null && ps.isMatch(flags)) {
3175                    return ps.getPermissionsState().computeGids(userId);
3176                }
3177            }
3178        }
3179
3180        return null;
3181    }
3182
3183    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3184        if (bp.perm != null) {
3185            return PackageParser.generatePermissionInfo(bp.perm, flags);
3186        }
3187        PermissionInfo pi = new PermissionInfo();
3188        pi.name = bp.name;
3189        pi.packageName = bp.sourcePackage;
3190        pi.nonLocalizedLabel = bp.name;
3191        pi.protectionLevel = bp.protectionLevel;
3192        return pi;
3193    }
3194
3195    @Override
3196    public PermissionInfo getPermissionInfo(String name, int flags) {
3197        // reader
3198        synchronized (mPackages) {
3199            final BasePermission p = mSettings.mPermissions.get(name);
3200            if (p != null) {
3201                return generatePermissionInfo(p, flags);
3202            }
3203            return null;
3204        }
3205    }
3206
3207    @Override
3208    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3209            int flags) {
3210        // reader
3211        synchronized (mPackages) {
3212            if (group != null && !mPermissionGroups.containsKey(group)) {
3213                // This is thrown as NameNotFoundException
3214                return null;
3215            }
3216
3217            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3218            for (BasePermission p : mSettings.mPermissions.values()) {
3219                if (group == null) {
3220                    if (p.perm == null || p.perm.info.group == null) {
3221                        out.add(generatePermissionInfo(p, flags));
3222                    }
3223                } else {
3224                    if (p.perm != null && group.equals(p.perm.info.group)) {
3225                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3226                    }
3227                }
3228            }
3229            return new ParceledListSlice<>(out);
3230        }
3231    }
3232
3233    @Override
3234    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3235        // reader
3236        synchronized (mPackages) {
3237            return PackageParser.generatePermissionGroupInfo(
3238                    mPermissionGroups.get(name), flags);
3239        }
3240    }
3241
3242    @Override
3243    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3244        // reader
3245        synchronized (mPackages) {
3246            final int N = mPermissionGroups.size();
3247            ArrayList<PermissionGroupInfo> out
3248                    = new ArrayList<PermissionGroupInfo>(N);
3249            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3250                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3251            }
3252            return new ParceledListSlice<>(out);
3253        }
3254    }
3255
3256    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3257            int userId) {
3258        if (!sUserManager.exists(userId)) return null;
3259        PackageSetting ps = mSettings.mPackages.get(packageName);
3260        if (ps != null) {
3261            if (ps.pkg == null) {
3262                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3263                if (pInfo != null) {
3264                    return pInfo.applicationInfo;
3265                }
3266                return null;
3267            }
3268            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3269                    ps.readUserState(userId), userId);
3270        }
3271        return null;
3272    }
3273
3274    @Override
3275    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3276        if (!sUserManager.exists(userId)) return null;
3277        flags = updateFlagsForApplication(flags, userId, packageName);
3278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3279                false /* requireFullPermission */, false /* checkShell */, "get application info");
3280        // writer
3281        synchronized (mPackages) {
3282            PackageParser.Package p = mPackages.get(packageName);
3283            if (DEBUG_PACKAGE_INFO) Log.v(
3284                    TAG, "getApplicationInfo " + packageName
3285                    + ": " + p);
3286            if (p != null) {
3287                PackageSetting ps = mSettings.mPackages.get(packageName);
3288                if (ps == null) return null;
3289                // Note: isEnabledLP() does not apply here - always return info
3290                return PackageParser.generateApplicationInfo(
3291                        p, flags, ps.readUserState(userId), userId);
3292            }
3293            if ("android".equals(packageName)||"system".equals(packageName)) {
3294                return mAndroidApplication;
3295            }
3296            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3297                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3298            }
3299        }
3300        return null;
3301    }
3302
3303    @Override
3304    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3305            final IPackageDataObserver observer) {
3306        mContext.enforceCallingOrSelfPermission(
3307                android.Manifest.permission.CLEAR_APP_CACHE, null);
3308        // Queue up an async operation since clearing cache may take a little while.
3309        mHandler.post(new Runnable() {
3310            public void run() {
3311                mHandler.removeCallbacks(this);
3312                boolean success = true;
3313                synchronized (mInstallLock) {
3314                    try {
3315                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3316                    } catch (InstallerException e) {
3317                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3318                        success = false;
3319                    }
3320                }
3321                if (observer != null) {
3322                    try {
3323                        observer.onRemoveCompleted(null, success);
3324                    } catch (RemoteException e) {
3325                        Slog.w(TAG, "RemoveException when invoking call back");
3326                    }
3327                }
3328            }
3329        });
3330    }
3331
3332    @Override
3333    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3334            final IntentSender pi) {
3335        mContext.enforceCallingOrSelfPermission(
3336                android.Manifest.permission.CLEAR_APP_CACHE, null);
3337        // Queue up an async operation since clearing cache may take a little while.
3338        mHandler.post(new Runnable() {
3339            public void run() {
3340                mHandler.removeCallbacks(this);
3341                boolean success = true;
3342                synchronized (mInstallLock) {
3343                    try {
3344                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3345                    } catch (InstallerException e) {
3346                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3347                        success = false;
3348                    }
3349                }
3350                if(pi != null) {
3351                    try {
3352                        // Callback via pending intent
3353                        int code = success ? 1 : 0;
3354                        pi.sendIntent(null, code, null,
3355                                null, null);
3356                    } catch (SendIntentException e1) {
3357                        Slog.i(TAG, "Failed to send pending intent");
3358                    }
3359                }
3360            }
3361        });
3362    }
3363
3364    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3365        synchronized (mInstallLock) {
3366            try {
3367                mInstaller.freeCache(volumeUuid, freeStorageSize);
3368            } catch (InstallerException e) {
3369                throw new IOException("Failed to free enough space", e);
3370            }
3371        }
3372    }
3373
3374    /**
3375     * Return if the user key is currently unlocked.
3376     */
3377    private boolean isUserKeyUnlocked(int userId) {
3378        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3379            final IMountService mount = IMountService.Stub
3380                    .asInterface(ServiceManager.getService("mount"));
3381            if (mount == null) {
3382                Slog.w(TAG, "Early during boot, assuming locked");
3383                return false;
3384            }
3385            final long token = Binder.clearCallingIdentity();
3386            try {
3387                return mount.isUserKeyUnlocked(userId);
3388            } catch (RemoteException e) {
3389                throw e.rethrowAsRuntimeException();
3390            } finally {
3391                Binder.restoreCallingIdentity(token);
3392            }
3393        } else {
3394            return true;
3395        }
3396    }
3397
3398    /**
3399     * Update given flags based on encryption status of current user.
3400     */
3401    private int updateFlags(int flags, int userId) {
3402        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3403                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3404            // Caller expressed an explicit opinion about what encryption
3405            // aware/unaware components they want to see, so fall through and
3406            // give them what they want
3407        } else {
3408            // Caller expressed no opinion, so match based on user state
3409            if (isUserKeyUnlocked(userId)) {
3410                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3411            } else {
3412                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3413            }
3414        }
3415        return flags;
3416    }
3417
3418    /**
3419     * Update given flags when being used to request {@link PackageInfo}.
3420     */
3421    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3422        boolean triaged = true;
3423        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3424                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3425            // Caller is asking for component details, so they'd better be
3426            // asking for specific encryption matching behavior, or be triaged
3427            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3428                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3429                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3430                triaged = false;
3431            }
3432        }
3433        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3434                | PackageManager.MATCH_SYSTEM_ONLY
3435                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3436            triaged = false;
3437        }
3438        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3439            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3440                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3441        }
3442        return updateFlags(flags, userId);
3443    }
3444
3445    /**
3446     * Update given flags when being used to request {@link ApplicationInfo}.
3447     */
3448    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3449        return updateFlagsForPackage(flags, userId, cookie);
3450    }
3451
3452    /**
3453     * Update given flags when being used to request {@link ComponentInfo}.
3454     */
3455    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3456        if (cookie instanceof Intent) {
3457            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3458                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3459            }
3460        }
3461
3462        boolean triaged = true;
3463        // Caller is asking for component details, so they'd better be
3464        // asking for specific encryption matching behavior, or be triaged
3465        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3466                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3467                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3468            triaged = false;
3469        }
3470        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3471            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3472                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3473        }
3474
3475        return updateFlags(flags, userId);
3476    }
3477
3478    /**
3479     * Update given flags when being used to request {@link ResolveInfo}.
3480     */
3481    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3482        // Safe mode means we shouldn't match any third-party components
3483        if (mSafeMode) {
3484            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3485        }
3486
3487        return updateFlagsForComponent(flags, userId, cookie);
3488    }
3489
3490    @Override
3491    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3492        if (!sUserManager.exists(userId)) return null;
3493        flags = updateFlagsForComponent(flags, userId, component);
3494        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3495                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3496        synchronized (mPackages) {
3497            PackageParser.Activity a = mActivities.mActivities.get(component);
3498
3499            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3500            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3501                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3502                if (ps == null) return null;
3503                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3504                        userId);
3505            }
3506            if (mResolveComponentName.equals(component)) {
3507                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3508                        new PackageUserState(), userId);
3509            }
3510        }
3511        return null;
3512    }
3513
3514    @Override
3515    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3516            String resolvedType) {
3517        synchronized (mPackages) {
3518            if (component.equals(mResolveComponentName)) {
3519                // The resolver supports EVERYTHING!
3520                return true;
3521            }
3522            PackageParser.Activity a = mActivities.mActivities.get(component);
3523            if (a == null) {
3524                return false;
3525            }
3526            for (int i=0; i<a.intents.size(); i++) {
3527                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3528                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3529                    return true;
3530                }
3531            }
3532            return false;
3533        }
3534    }
3535
3536    @Override
3537    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3538        if (!sUserManager.exists(userId)) return null;
3539        flags = updateFlagsForComponent(flags, userId, component);
3540        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3541                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3542        synchronized (mPackages) {
3543            PackageParser.Activity a = mReceivers.mActivities.get(component);
3544            if (DEBUG_PACKAGE_INFO) Log.v(
3545                TAG, "getReceiverInfo " + component + ": " + a);
3546            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3547                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3548                if (ps == null) return null;
3549                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3550                        userId);
3551            }
3552        }
3553        return null;
3554    }
3555
3556    @Override
3557    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3558        if (!sUserManager.exists(userId)) return null;
3559        flags = updateFlagsForComponent(flags, userId, component);
3560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3561                false /* requireFullPermission */, false /* checkShell */, "get service info");
3562        synchronized (mPackages) {
3563            PackageParser.Service s = mServices.mServices.get(component);
3564            if (DEBUG_PACKAGE_INFO) Log.v(
3565                TAG, "getServiceInfo " + component + ": " + s);
3566            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3567                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3568                if (ps == null) return null;
3569                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3570                        userId);
3571            }
3572        }
3573        return null;
3574    }
3575
3576    @Override
3577    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3578        if (!sUserManager.exists(userId)) return null;
3579        flags = updateFlagsForComponent(flags, userId, component);
3580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3581                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3582        synchronized (mPackages) {
3583            PackageParser.Provider p = mProviders.mProviders.get(component);
3584            if (DEBUG_PACKAGE_INFO) Log.v(
3585                TAG, "getProviderInfo " + component + ": " + p);
3586            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3587                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3588                if (ps == null) return null;
3589                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3590                        userId);
3591            }
3592        }
3593        return null;
3594    }
3595
3596    @Override
3597    public String[] getSystemSharedLibraryNames() {
3598        Set<String> libSet;
3599        synchronized (mPackages) {
3600            libSet = mSharedLibraries.keySet();
3601            int size = libSet.size();
3602            if (size > 0) {
3603                String[] libs = new String[size];
3604                libSet.toArray(libs);
3605                return libs;
3606            }
3607        }
3608        return null;
3609    }
3610
3611    @Override
3612    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3613        synchronized (mPackages) {
3614            return mServicesSystemSharedLibraryPackageName;
3615        }
3616    }
3617
3618    @Override
3619    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3620        synchronized (mPackages) {
3621            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3622
3623            final FeatureInfo fi = new FeatureInfo();
3624            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3625                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3626            res.add(fi);
3627
3628            return new ParceledListSlice<>(res);
3629        }
3630    }
3631
3632    @Override
3633    public boolean hasSystemFeature(String name, int version) {
3634        synchronized (mPackages) {
3635            final FeatureInfo feat = mAvailableFeatures.get(name);
3636            if (feat == null) {
3637                return false;
3638            } else {
3639                return feat.version >= version;
3640            }
3641        }
3642    }
3643
3644    @Override
3645    public int checkPermission(String permName, String pkgName, int userId) {
3646        if (!sUserManager.exists(userId)) {
3647            return PackageManager.PERMISSION_DENIED;
3648        }
3649
3650        synchronized (mPackages) {
3651            final PackageParser.Package p = mPackages.get(pkgName);
3652            if (p != null && p.mExtras != null) {
3653                final PackageSetting ps = (PackageSetting) p.mExtras;
3654                final PermissionsState permissionsState = ps.getPermissionsState();
3655                if (permissionsState.hasPermission(permName, userId)) {
3656                    return PackageManager.PERMISSION_GRANTED;
3657                }
3658                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3659                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3660                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3661                    return PackageManager.PERMISSION_GRANTED;
3662                }
3663            }
3664        }
3665
3666        return PackageManager.PERMISSION_DENIED;
3667    }
3668
3669    @Override
3670    public int checkUidPermission(String permName, int uid) {
3671        final int userId = UserHandle.getUserId(uid);
3672
3673        if (!sUserManager.exists(userId)) {
3674            return PackageManager.PERMISSION_DENIED;
3675        }
3676
3677        synchronized (mPackages) {
3678            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3679            if (obj != null) {
3680                final SettingBase ps = (SettingBase) obj;
3681                final PermissionsState permissionsState = ps.getPermissionsState();
3682                if (permissionsState.hasPermission(permName, userId)) {
3683                    return PackageManager.PERMISSION_GRANTED;
3684                }
3685                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3686                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3687                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3688                    return PackageManager.PERMISSION_GRANTED;
3689                }
3690            } else {
3691                ArraySet<String> perms = mSystemPermissions.get(uid);
3692                if (perms != null) {
3693                    if (perms.contains(permName)) {
3694                        return PackageManager.PERMISSION_GRANTED;
3695                    }
3696                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3697                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3698                        return PackageManager.PERMISSION_GRANTED;
3699                    }
3700                }
3701            }
3702        }
3703
3704        return PackageManager.PERMISSION_DENIED;
3705    }
3706
3707    @Override
3708    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3709        if (UserHandle.getCallingUserId() != userId) {
3710            mContext.enforceCallingPermission(
3711                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3712                    "isPermissionRevokedByPolicy for user " + userId);
3713        }
3714
3715        if (checkPermission(permission, packageName, userId)
3716                == PackageManager.PERMISSION_GRANTED) {
3717            return false;
3718        }
3719
3720        final long identity = Binder.clearCallingIdentity();
3721        try {
3722            final int flags = getPermissionFlags(permission, packageName, userId);
3723            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3724        } finally {
3725            Binder.restoreCallingIdentity(identity);
3726        }
3727    }
3728
3729    @Override
3730    public String getPermissionControllerPackageName() {
3731        synchronized (mPackages) {
3732            return mRequiredInstallerPackage;
3733        }
3734    }
3735
3736    /**
3737     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3738     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3739     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3740     * @param message the message to log on security exception
3741     */
3742    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3743            boolean checkShell, String message) {
3744        if (userId < 0) {
3745            throw new IllegalArgumentException("Invalid userId " + userId);
3746        }
3747        if (checkShell) {
3748            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3749        }
3750        if (userId == UserHandle.getUserId(callingUid)) return;
3751        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3752            if (requireFullPermission) {
3753                mContext.enforceCallingOrSelfPermission(
3754                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3755            } else {
3756                try {
3757                    mContext.enforceCallingOrSelfPermission(
3758                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3759                } catch (SecurityException se) {
3760                    mContext.enforceCallingOrSelfPermission(
3761                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3762                }
3763            }
3764        }
3765    }
3766
3767    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3768        if (callingUid == Process.SHELL_UID) {
3769            if (userHandle >= 0
3770                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3771                throw new SecurityException("Shell does not have permission to access user "
3772                        + userHandle);
3773            } else if (userHandle < 0) {
3774                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3775                        + Debug.getCallers(3));
3776            }
3777        }
3778    }
3779
3780    private BasePermission findPermissionTreeLP(String permName) {
3781        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3782            if (permName.startsWith(bp.name) &&
3783                    permName.length() > bp.name.length() &&
3784                    permName.charAt(bp.name.length()) == '.') {
3785                return bp;
3786            }
3787        }
3788        return null;
3789    }
3790
3791    private BasePermission checkPermissionTreeLP(String permName) {
3792        if (permName != null) {
3793            BasePermission bp = findPermissionTreeLP(permName);
3794            if (bp != null) {
3795                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3796                    return bp;
3797                }
3798                throw new SecurityException("Calling uid "
3799                        + Binder.getCallingUid()
3800                        + " is not allowed to add to permission tree "
3801                        + bp.name + " owned by uid " + bp.uid);
3802            }
3803        }
3804        throw new SecurityException("No permission tree found for " + permName);
3805    }
3806
3807    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3808        if (s1 == null) {
3809            return s2 == null;
3810        }
3811        if (s2 == null) {
3812            return false;
3813        }
3814        if (s1.getClass() != s2.getClass()) {
3815            return false;
3816        }
3817        return s1.equals(s2);
3818    }
3819
3820    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3821        if (pi1.icon != pi2.icon) return false;
3822        if (pi1.logo != pi2.logo) return false;
3823        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3824        if (!compareStrings(pi1.name, pi2.name)) return false;
3825        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3826        // We'll take care of setting this one.
3827        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3828        // These are not currently stored in settings.
3829        //if (!compareStrings(pi1.group, pi2.group)) return false;
3830        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3831        //if (pi1.labelRes != pi2.labelRes) return false;
3832        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3833        return true;
3834    }
3835
3836    int permissionInfoFootprint(PermissionInfo info) {
3837        int size = info.name.length();
3838        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3839        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3840        return size;
3841    }
3842
3843    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3844        int size = 0;
3845        for (BasePermission perm : mSettings.mPermissions.values()) {
3846            if (perm.uid == tree.uid) {
3847                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3848            }
3849        }
3850        return size;
3851    }
3852
3853    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3854        // We calculate the max size of permissions defined by this uid and throw
3855        // if that plus the size of 'info' would exceed our stated maximum.
3856        if (tree.uid != Process.SYSTEM_UID) {
3857            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3858            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3859                throw new SecurityException("Permission tree size cap exceeded");
3860            }
3861        }
3862    }
3863
3864    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3865        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3866            throw new SecurityException("Label must be specified in permission");
3867        }
3868        BasePermission tree = checkPermissionTreeLP(info.name);
3869        BasePermission bp = mSettings.mPermissions.get(info.name);
3870        boolean added = bp == null;
3871        boolean changed = true;
3872        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3873        if (added) {
3874            enforcePermissionCapLocked(info, tree);
3875            bp = new BasePermission(info.name, tree.sourcePackage,
3876                    BasePermission.TYPE_DYNAMIC);
3877        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3878            throw new SecurityException(
3879                    "Not allowed to modify non-dynamic permission "
3880                    + info.name);
3881        } else {
3882            if (bp.protectionLevel == fixedLevel
3883                    && bp.perm.owner.equals(tree.perm.owner)
3884                    && bp.uid == tree.uid
3885                    && comparePermissionInfos(bp.perm.info, info)) {
3886                changed = false;
3887            }
3888        }
3889        bp.protectionLevel = fixedLevel;
3890        info = new PermissionInfo(info);
3891        info.protectionLevel = fixedLevel;
3892        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3893        bp.perm.info.packageName = tree.perm.info.packageName;
3894        bp.uid = tree.uid;
3895        if (added) {
3896            mSettings.mPermissions.put(info.name, bp);
3897        }
3898        if (changed) {
3899            if (!async) {
3900                mSettings.writeLPr();
3901            } else {
3902                scheduleWriteSettingsLocked();
3903            }
3904        }
3905        return added;
3906    }
3907
3908    @Override
3909    public boolean addPermission(PermissionInfo info) {
3910        synchronized (mPackages) {
3911            return addPermissionLocked(info, false);
3912        }
3913    }
3914
3915    @Override
3916    public boolean addPermissionAsync(PermissionInfo info) {
3917        synchronized (mPackages) {
3918            return addPermissionLocked(info, true);
3919        }
3920    }
3921
3922    @Override
3923    public void removePermission(String name) {
3924        synchronized (mPackages) {
3925            checkPermissionTreeLP(name);
3926            BasePermission bp = mSettings.mPermissions.get(name);
3927            if (bp != null) {
3928                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3929                    throw new SecurityException(
3930                            "Not allowed to modify non-dynamic permission "
3931                            + name);
3932                }
3933                mSettings.mPermissions.remove(name);
3934                mSettings.writeLPr();
3935            }
3936        }
3937    }
3938
3939    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3940            BasePermission bp) {
3941        int index = pkg.requestedPermissions.indexOf(bp.name);
3942        if (index == -1) {
3943            throw new SecurityException("Package " + pkg.packageName
3944                    + " has not requested permission " + bp.name);
3945        }
3946        if (!bp.isRuntime() && !bp.isDevelopment()) {
3947            throw new SecurityException("Permission " + bp.name
3948                    + " is not a changeable permission type");
3949        }
3950    }
3951
3952    @Override
3953    public void grantRuntimePermission(String packageName, String name, final int userId) {
3954        if (!sUserManager.exists(userId)) {
3955            Log.e(TAG, "No such user:" + userId);
3956            return;
3957        }
3958
3959        mContext.enforceCallingOrSelfPermission(
3960                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3961                "grantRuntimePermission");
3962
3963        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3964                true /* requireFullPermission */, true /* checkShell */,
3965                "grantRuntimePermission");
3966
3967        final int uid;
3968        final SettingBase sb;
3969
3970        synchronized (mPackages) {
3971            final PackageParser.Package pkg = mPackages.get(packageName);
3972            if (pkg == null) {
3973                throw new IllegalArgumentException("Unknown package: " + packageName);
3974            }
3975
3976            final BasePermission bp = mSettings.mPermissions.get(name);
3977            if (bp == null) {
3978                throw new IllegalArgumentException("Unknown permission: " + name);
3979            }
3980
3981            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3982
3983            // If a permission review is required for legacy apps we represent
3984            // their permissions as always granted runtime ones since we need
3985            // to keep the review required permission flag per user while an
3986            // install permission's state is shared across all users.
3987            if (Build.PERMISSIONS_REVIEW_REQUIRED
3988                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3989                    && bp.isRuntime()) {
3990                return;
3991            }
3992
3993            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3994            sb = (SettingBase) pkg.mExtras;
3995            if (sb == null) {
3996                throw new IllegalArgumentException("Unknown package: " + packageName);
3997            }
3998
3999            final PermissionsState permissionsState = sb.getPermissionsState();
4000
4001            final int flags = permissionsState.getPermissionFlags(name, userId);
4002            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4003                throw new SecurityException("Cannot grant system fixed permission "
4004                        + name + " for package " + packageName);
4005            }
4006
4007            if (bp.isDevelopment()) {
4008                // Development permissions must be handled specially, since they are not
4009                // normal runtime permissions.  For now they apply to all users.
4010                if (permissionsState.grantInstallPermission(bp) !=
4011                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4012                    scheduleWriteSettingsLocked();
4013                }
4014                return;
4015            }
4016
4017            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4018                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4019                return;
4020            }
4021
4022            final int result = permissionsState.grantRuntimePermission(bp, userId);
4023            switch (result) {
4024                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4025                    return;
4026                }
4027
4028                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4029                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4030                    mHandler.post(new Runnable() {
4031                        @Override
4032                        public void run() {
4033                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4034                        }
4035                    });
4036                }
4037                break;
4038            }
4039
4040            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4041
4042            // Not critical if that is lost - app has to request again.
4043            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4044        }
4045
4046        // Only need to do this if user is initialized. Otherwise it's a new user
4047        // and there are no processes running as the user yet and there's no need
4048        // to make an expensive call to remount processes for the changed permissions.
4049        if (READ_EXTERNAL_STORAGE.equals(name)
4050                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4051            final long token = Binder.clearCallingIdentity();
4052            try {
4053                if (sUserManager.isInitialized(userId)) {
4054                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4055                            MountServiceInternal.class);
4056                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4057                }
4058            } finally {
4059                Binder.restoreCallingIdentity(token);
4060            }
4061        }
4062    }
4063
4064    @Override
4065    public void revokeRuntimePermission(String packageName, String name, int userId) {
4066        if (!sUserManager.exists(userId)) {
4067            Log.e(TAG, "No such user:" + userId);
4068            return;
4069        }
4070
4071        mContext.enforceCallingOrSelfPermission(
4072                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4073                "revokeRuntimePermission");
4074
4075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4076                true /* requireFullPermission */, true /* checkShell */,
4077                "revokeRuntimePermission");
4078
4079        final int appId;
4080
4081        synchronized (mPackages) {
4082            final PackageParser.Package pkg = mPackages.get(packageName);
4083            if (pkg == null) {
4084                throw new IllegalArgumentException("Unknown package: " + packageName);
4085            }
4086
4087            final BasePermission bp = mSettings.mPermissions.get(name);
4088            if (bp == null) {
4089                throw new IllegalArgumentException("Unknown permission: " + name);
4090            }
4091
4092            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4093
4094            // If a permission review is required for legacy apps we represent
4095            // their permissions as always granted runtime ones since we need
4096            // to keep the review required permission flag per user while an
4097            // install permission's state is shared across all users.
4098            if (Build.PERMISSIONS_REVIEW_REQUIRED
4099                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4100                    && bp.isRuntime()) {
4101                return;
4102            }
4103
4104            SettingBase sb = (SettingBase) pkg.mExtras;
4105            if (sb == null) {
4106                throw new IllegalArgumentException("Unknown package: " + packageName);
4107            }
4108
4109            final PermissionsState permissionsState = sb.getPermissionsState();
4110
4111            final int flags = permissionsState.getPermissionFlags(name, userId);
4112            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4113                throw new SecurityException("Cannot revoke system fixed permission "
4114                        + name + " for package " + packageName);
4115            }
4116
4117            if (bp.isDevelopment()) {
4118                // Development permissions must be handled specially, since they are not
4119                // normal runtime permissions.  For now they apply to all users.
4120                if (permissionsState.revokeInstallPermission(bp) !=
4121                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4122                    scheduleWriteSettingsLocked();
4123                }
4124                return;
4125            }
4126
4127            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4128                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4129                return;
4130            }
4131
4132            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4133
4134            // Critical, after this call app should never have the permission.
4135            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4136
4137            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4138        }
4139
4140        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4141    }
4142
4143    @Override
4144    public void resetRuntimePermissions() {
4145        mContext.enforceCallingOrSelfPermission(
4146                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4147                "revokeRuntimePermission");
4148
4149        int callingUid = Binder.getCallingUid();
4150        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4151            mContext.enforceCallingOrSelfPermission(
4152                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4153                    "resetRuntimePermissions");
4154        }
4155
4156        synchronized (mPackages) {
4157            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4158            for (int userId : UserManagerService.getInstance().getUserIds()) {
4159                final int packageCount = mPackages.size();
4160                for (int i = 0; i < packageCount; i++) {
4161                    PackageParser.Package pkg = mPackages.valueAt(i);
4162                    if (!(pkg.mExtras instanceof PackageSetting)) {
4163                        continue;
4164                    }
4165                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4166                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4167                }
4168            }
4169        }
4170    }
4171
4172    @Override
4173    public int getPermissionFlags(String name, String packageName, int userId) {
4174        if (!sUserManager.exists(userId)) {
4175            return 0;
4176        }
4177
4178        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4179
4180        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4181                true /* requireFullPermission */, false /* checkShell */,
4182                "getPermissionFlags");
4183
4184        synchronized (mPackages) {
4185            final PackageParser.Package pkg = mPackages.get(packageName);
4186            if (pkg == null) {
4187                throw new IllegalArgumentException("Unknown package: " + packageName);
4188            }
4189
4190            final BasePermission bp = mSettings.mPermissions.get(name);
4191            if (bp == null) {
4192                throw new IllegalArgumentException("Unknown permission: " + name);
4193            }
4194
4195            SettingBase sb = (SettingBase) pkg.mExtras;
4196            if (sb == null) {
4197                throw new IllegalArgumentException("Unknown package: " + packageName);
4198            }
4199
4200            PermissionsState permissionsState = sb.getPermissionsState();
4201            return permissionsState.getPermissionFlags(name, userId);
4202        }
4203    }
4204
4205    @Override
4206    public void updatePermissionFlags(String name, String packageName, int flagMask,
4207            int flagValues, int userId) {
4208        if (!sUserManager.exists(userId)) {
4209            return;
4210        }
4211
4212        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4213
4214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4215                true /* requireFullPermission */, true /* checkShell */,
4216                "updatePermissionFlags");
4217
4218        // Only the system can change these flags and nothing else.
4219        if (getCallingUid() != Process.SYSTEM_UID) {
4220            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4221            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4222            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4223            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4224            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4225        }
4226
4227        synchronized (mPackages) {
4228            final PackageParser.Package pkg = mPackages.get(packageName);
4229            if (pkg == null) {
4230                throw new IllegalArgumentException("Unknown package: " + packageName);
4231            }
4232
4233            final BasePermission bp = mSettings.mPermissions.get(name);
4234            if (bp == null) {
4235                throw new IllegalArgumentException("Unknown permission: " + name);
4236            }
4237
4238            SettingBase sb = (SettingBase) pkg.mExtras;
4239            if (sb == null) {
4240                throw new IllegalArgumentException("Unknown package: " + packageName);
4241            }
4242
4243            PermissionsState permissionsState = sb.getPermissionsState();
4244
4245            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4246
4247            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4248                // Install and runtime permissions are stored in different places,
4249                // so figure out what permission changed and persist the change.
4250                if (permissionsState.getInstallPermissionState(name) != null) {
4251                    scheduleWriteSettingsLocked();
4252                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4253                        || hadState) {
4254                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4255                }
4256            }
4257        }
4258    }
4259
4260    /**
4261     * Update the permission flags for all packages and runtime permissions of a user in order
4262     * to allow device or profile owner to remove POLICY_FIXED.
4263     */
4264    @Override
4265    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4266        if (!sUserManager.exists(userId)) {
4267            return;
4268        }
4269
4270        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4271
4272        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4273                true /* requireFullPermission */, true /* checkShell */,
4274                "updatePermissionFlagsForAllApps");
4275
4276        // Only the system can change system fixed flags.
4277        if (getCallingUid() != Process.SYSTEM_UID) {
4278            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4279            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4280        }
4281
4282        synchronized (mPackages) {
4283            boolean changed = false;
4284            final int packageCount = mPackages.size();
4285            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4286                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4287                SettingBase sb = (SettingBase) pkg.mExtras;
4288                if (sb == null) {
4289                    continue;
4290                }
4291                PermissionsState permissionsState = sb.getPermissionsState();
4292                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4293                        userId, flagMask, flagValues);
4294            }
4295            if (changed) {
4296                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4297            }
4298        }
4299    }
4300
4301    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4302        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4303                != PackageManager.PERMISSION_GRANTED
4304            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4305                != PackageManager.PERMISSION_GRANTED) {
4306            throw new SecurityException(message + " requires "
4307                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4308                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4309        }
4310    }
4311
4312    @Override
4313    public boolean shouldShowRequestPermissionRationale(String permissionName,
4314            String packageName, int userId) {
4315        if (UserHandle.getCallingUserId() != userId) {
4316            mContext.enforceCallingPermission(
4317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4318                    "canShowRequestPermissionRationale for user " + userId);
4319        }
4320
4321        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4322        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4323            return false;
4324        }
4325
4326        if (checkPermission(permissionName, packageName, userId)
4327                == PackageManager.PERMISSION_GRANTED) {
4328            return false;
4329        }
4330
4331        final int flags;
4332
4333        final long identity = Binder.clearCallingIdentity();
4334        try {
4335            flags = getPermissionFlags(permissionName,
4336                    packageName, userId);
4337        } finally {
4338            Binder.restoreCallingIdentity(identity);
4339        }
4340
4341        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4342                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4343                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4344
4345        if ((flags & fixedFlags) != 0) {
4346            return false;
4347        }
4348
4349        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4350    }
4351
4352    @Override
4353    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4354        mContext.enforceCallingOrSelfPermission(
4355                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4356                "addOnPermissionsChangeListener");
4357
4358        synchronized (mPackages) {
4359            mOnPermissionChangeListeners.addListenerLocked(listener);
4360        }
4361    }
4362
4363    @Override
4364    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4365        synchronized (mPackages) {
4366            mOnPermissionChangeListeners.removeListenerLocked(listener);
4367        }
4368    }
4369
4370    @Override
4371    public boolean isProtectedBroadcast(String actionName) {
4372        synchronized (mPackages) {
4373            if (mProtectedBroadcasts.contains(actionName)) {
4374                return true;
4375            } else if (actionName != null) {
4376                // TODO: remove these terrible hacks
4377                if (actionName.startsWith("android.net.netmon.lingerExpired")
4378                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4379                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4380                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4381                    return true;
4382                }
4383            }
4384        }
4385        return false;
4386    }
4387
4388    @Override
4389    public int checkSignatures(String pkg1, String pkg2) {
4390        synchronized (mPackages) {
4391            final PackageParser.Package p1 = mPackages.get(pkg1);
4392            final PackageParser.Package p2 = mPackages.get(pkg2);
4393            if (p1 == null || p1.mExtras == null
4394                    || p2 == null || p2.mExtras == null) {
4395                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4396            }
4397            return compareSignatures(p1.mSignatures, p2.mSignatures);
4398        }
4399    }
4400
4401    @Override
4402    public int checkUidSignatures(int uid1, int uid2) {
4403        // Map to base uids.
4404        uid1 = UserHandle.getAppId(uid1);
4405        uid2 = UserHandle.getAppId(uid2);
4406        // reader
4407        synchronized (mPackages) {
4408            Signature[] s1;
4409            Signature[] s2;
4410            Object obj = mSettings.getUserIdLPr(uid1);
4411            if (obj != null) {
4412                if (obj instanceof SharedUserSetting) {
4413                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4414                } else if (obj instanceof PackageSetting) {
4415                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4416                } else {
4417                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4418                }
4419            } else {
4420                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4421            }
4422            obj = mSettings.getUserIdLPr(uid2);
4423            if (obj != null) {
4424                if (obj instanceof SharedUserSetting) {
4425                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4426                } else if (obj instanceof PackageSetting) {
4427                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4428                } else {
4429                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4430                }
4431            } else {
4432                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4433            }
4434            return compareSignatures(s1, s2);
4435        }
4436    }
4437
4438    /**
4439     * This method should typically only be used when granting or revoking
4440     * permissions, since the app may immediately restart after this call.
4441     * <p>
4442     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4443     * guard your work against the app being relaunched.
4444     */
4445    private void killUid(int appId, int userId, String reason) {
4446        final long identity = Binder.clearCallingIdentity();
4447        try {
4448            IActivityManager am = ActivityManagerNative.getDefault();
4449            if (am != null) {
4450                try {
4451                    am.killUid(appId, userId, reason);
4452                } catch (RemoteException e) {
4453                    /* ignore - same process */
4454                }
4455            }
4456        } finally {
4457            Binder.restoreCallingIdentity(identity);
4458        }
4459    }
4460
4461    /**
4462     * Compares two sets of signatures. Returns:
4463     * <br />
4464     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4465     * <br />
4466     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4467     * <br />
4468     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4469     * <br />
4470     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4471     * <br />
4472     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4473     */
4474    static int compareSignatures(Signature[] s1, Signature[] s2) {
4475        if (s1 == null) {
4476            return s2 == null
4477                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4478                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4479        }
4480
4481        if (s2 == null) {
4482            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4483        }
4484
4485        if (s1.length != s2.length) {
4486            return PackageManager.SIGNATURE_NO_MATCH;
4487        }
4488
4489        // Since both signature sets are of size 1, we can compare without HashSets.
4490        if (s1.length == 1) {
4491            return s1[0].equals(s2[0]) ?
4492                    PackageManager.SIGNATURE_MATCH :
4493                    PackageManager.SIGNATURE_NO_MATCH;
4494        }
4495
4496        ArraySet<Signature> set1 = new ArraySet<Signature>();
4497        for (Signature sig : s1) {
4498            set1.add(sig);
4499        }
4500        ArraySet<Signature> set2 = new ArraySet<Signature>();
4501        for (Signature sig : s2) {
4502            set2.add(sig);
4503        }
4504        // Make sure s2 contains all signatures in s1.
4505        if (set1.equals(set2)) {
4506            return PackageManager.SIGNATURE_MATCH;
4507        }
4508        return PackageManager.SIGNATURE_NO_MATCH;
4509    }
4510
4511    /**
4512     * If the database version for this type of package (internal storage or
4513     * external storage) is less than the version where package signatures
4514     * were updated, return true.
4515     */
4516    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4517        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4518        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4519    }
4520
4521    /**
4522     * Used for backward compatibility to make sure any packages with
4523     * certificate chains get upgraded to the new style. {@code existingSigs}
4524     * will be in the old format (since they were stored on disk from before the
4525     * system upgrade) and {@code scannedSigs} will be in the newer format.
4526     */
4527    private int compareSignaturesCompat(PackageSignatures existingSigs,
4528            PackageParser.Package scannedPkg) {
4529        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4530            return PackageManager.SIGNATURE_NO_MATCH;
4531        }
4532
4533        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4534        for (Signature sig : existingSigs.mSignatures) {
4535            existingSet.add(sig);
4536        }
4537        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4538        for (Signature sig : scannedPkg.mSignatures) {
4539            try {
4540                Signature[] chainSignatures = sig.getChainSignatures();
4541                for (Signature chainSig : chainSignatures) {
4542                    scannedCompatSet.add(chainSig);
4543                }
4544            } catch (CertificateEncodingException e) {
4545                scannedCompatSet.add(sig);
4546            }
4547        }
4548        /*
4549         * Make sure the expanded scanned set contains all signatures in the
4550         * existing one.
4551         */
4552        if (scannedCompatSet.equals(existingSet)) {
4553            // Migrate the old signatures to the new scheme.
4554            existingSigs.assignSignatures(scannedPkg.mSignatures);
4555            // The new KeySets will be re-added later in the scanning process.
4556            synchronized (mPackages) {
4557                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4558            }
4559            return PackageManager.SIGNATURE_MATCH;
4560        }
4561        return PackageManager.SIGNATURE_NO_MATCH;
4562    }
4563
4564    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4565        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4566        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4567    }
4568
4569    private int compareSignaturesRecover(PackageSignatures existingSigs,
4570            PackageParser.Package scannedPkg) {
4571        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4572            return PackageManager.SIGNATURE_NO_MATCH;
4573        }
4574
4575        String msg = null;
4576        try {
4577            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4578                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4579                        + scannedPkg.packageName);
4580                return PackageManager.SIGNATURE_MATCH;
4581            }
4582        } catch (CertificateException e) {
4583            msg = e.getMessage();
4584        }
4585
4586        logCriticalInfo(Log.INFO,
4587                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4588        return PackageManager.SIGNATURE_NO_MATCH;
4589    }
4590
4591    @Override
4592    public List<String> getAllPackages() {
4593        synchronized (mPackages) {
4594            return new ArrayList<String>(mPackages.keySet());
4595        }
4596    }
4597
4598    @Override
4599    public String[] getPackagesForUid(int uid) {
4600        uid = UserHandle.getAppId(uid);
4601        // reader
4602        synchronized (mPackages) {
4603            Object obj = mSettings.getUserIdLPr(uid);
4604            if (obj instanceof SharedUserSetting) {
4605                final SharedUserSetting sus = (SharedUserSetting) obj;
4606                final int N = sus.packages.size();
4607                final String[] res = new String[N];
4608                final Iterator<PackageSetting> it = sus.packages.iterator();
4609                int i = 0;
4610                while (it.hasNext()) {
4611                    res[i++] = it.next().name;
4612                }
4613                return res;
4614            } else if (obj instanceof PackageSetting) {
4615                final PackageSetting ps = (PackageSetting) obj;
4616                return new String[] { ps.name };
4617            }
4618        }
4619        return null;
4620    }
4621
4622    @Override
4623    public String getNameForUid(int uid) {
4624        // reader
4625        synchronized (mPackages) {
4626            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4627            if (obj instanceof SharedUserSetting) {
4628                final SharedUserSetting sus = (SharedUserSetting) obj;
4629                return sus.name + ":" + sus.userId;
4630            } else if (obj instanceof PackageSetting) {
4631                final PackageSetting ps = (PackageSetting) obj;
4632                return ps.name;
4633            }
4634        }
4635        return null;
4636    }
4637
4638    @Override
4639    public int getUidForSharedUser(String sharedUserName) {
4640        if(sharedUserName == null) {
4641            return -1;
4642        }
4643        // reader
4644        synchronized (mPackages) {
4645            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4646            if (suid == null) {
4647                return -1;
4648            }
4649            return suid.userId;
4650        }
4651    }
4652
4653    @Override
4654    public int getFlagsForUid(int uid) {
4655        synchronized (mPackages) {
4656            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4657            if (obj instanceof SharedUserSetting) {
4658                final SharedUserSetting sus = (SharedUserSetting) obj;
4659                return sus.pkgFlags;
4660            } else if (obj instanceof PackageSetting) {
4661                final PackageSetting ps = (PackageSetting) obj;
4662                return ps.pkgFlags;
4663            }
4664        }
4665        return 0;
4666    }
4667
4668    @Override
4669    public int getPrivateFlagsForUid(int uid) {
4670        synchronized (mPackages) {
4671            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4672            if (obj instanceof SharedUserSetting) {
4673                final SharedUserSetting sus = (SharedUserSetting) obj;
4674                return sus.pkgPrivateFlags;
4675            } else if (obj instanceof PackageSetting) {
4676                final PackageSetting ps = (PackageSetting) obj;
4677                return ps.pkgPrivateFlags;
4678            }
4679        }
4680        return 0;
4681    }
4682
4683    @Override
4684    public boolean isUidPrivileged(int uid) {
4685        uid = UserHandle.getAppId(uid);
4686        // reader
4687        synchronized (mPackages) {
4688            Object obj = mSettings.getUserIdLPr(uid);
4689            if (obj instanceof SharedUserSetting) {
4690                final SharedUserSetting sus = (SharedUserSetting) obj;
4691                final Iterator<PackageSetting> it = sus.packages.iterator();
4692                while (it.hasNext()) {
4693                    if (it.next().isPrivileged()) {
4694                        return true;
4695                    }
4696                }
4697            } else if (obj instanceof PackageSetting) {
4698                final PackageSetting ps = (PackageSetting) obj;
4699                return ps.isPrivileged();
4700            }
4701        }
4702        return false;
4703    }
4704
4705    @Override
4706    public String[] getAppOpPermissionPackages(String permissionName) {
4707        synchronized (mPackages) {
4708            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4709            if (pkgs == null) {
4710                return null;
4711            }
4712            return pkgs.toArray(new String[pkgs.size()]);
4713        }
4714    }
4715
4716    @Override
4717    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4718            int flags, int userId) {
4719        if (!sUserManager.exists(userId)) return null;
4720        flags = updateFlagsForResolve(flags, userId, intent);
4721        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4722                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4723        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4724                userId);
4725        final ResolveInfo bestChoice =
4726                chooseBestActivity(intent, resolvedType, flags, query, userId);
4727
4728        if (isEphemeralAllowed(intent, query, userId)) {
4729            final EphemeralResolveInfo ai =
4730                    getEphemeralResolveInfo(intent, resolvedType, userId);
4731            if (ai != null) {
4732                if (DEBUG_EPHEMERAL) {
4733                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4734                }
4735                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4736                bestChoice.ephemeralResolveInfo = ai;
4737            }
4738        }
4739        return bestChoice;
4740    }
4741
4742    @Override
4743    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4744            IntentFilter filter, int match, ComponentName activity) {
4745        final int userId = UserHandle.getCallingUserId();
4746        if (DEBUG_PREFERRED) {
4747            Log.v(TAG, "setLastChosenActivity intent=" + intent
4748                + " resolvedType=" + resolvedType
4749                + " flags=" + flags
4750                + " filter=" + filter
4751                + " match=" + match
4752                + " activity=" + activity);
4753            filter.dump(new PrintStreamPrinter(System.out), "    ");
4754        }
4755        intent.setComponent(null);
4756        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4757                userId);
4758        // Find any earlier preferred or last chosen entries and nuke them
4759        findPreferredActivity(intent, resolvedType,
4760                flags, query, 0, false, true, false, userId);
4761        // Add the new activity as the last chosen for this filter
4762        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4763                "Setting last chosen");
4764    }
4765
4766    @Override
4767    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4768        final int userId = UserHandle.getCallingUserId();
4769        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4770        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4771                userId);
4772        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4773                false, false, false, userId);
4774    }
4775
4776
4777    private boolean isEphemeralAllowed(
4778            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4779        // Short circuit and return early if possible.
4780        if (DISABLE_EPHEMERAL_APPS) {
4781            return false;
4782        }
4783        final int callingUser = UserHandle.getCallingUserId();
4784        if (callingUser != UserHandle.USER_SYSTEM) {
4785            return false;
4786        }
4787        if (mEphemeralResolverConnection == null) {
4788            return false;
4789        }
4790        if (intent.getComponent() != null) {
4791            return false;
4792        }
4793        if (intent.getPackage() != null) {
4794            return false;
4795        }
4796        final boolean isWebUri = hasWebURI(intent);
4797        if (!isWebUri) {
4798            return false;
4799        }
4800        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4801        synchronized (mPackages) {
4802            final int count = resolvedActivites.size();
4803            for (int n = 0; n < count; n++) {
4804                ResolveInfo info = resolvedActivites.get(n);
4805                String packageName = info.activityInfo.packageName;
4806                PackageSetting ps = mSettings.mPackages.get(packageName);
4807                if (ps != null) {
4808                    // Try to get the status from User settings first
4809                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4810                    int status = (int) (packedStatus >> 32);
4811                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4812                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4813                        if (DEBUG_EPHEMERAL) {
4814                            Slog.v(TAG, "DENY ephemeral apps;"
4815                                + " pkg: " + packageName + ", status: " + status);
4816                        }
4817                        return false;
4818                    }
4819                }
4820            }
4821        }
4822        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4823        return true;
4824    }
4825
4826    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4827            int userId) {
4828        MessageDigest digest = null;
4829        try {
4830            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4831        } catch (NoSuchAlgorithmException e) {
4832            // If we can't create a digest, ignore ephemeral apps.
4833            return null;
4834        }
4835
4836        final byte[] hostBytes = intent.getData().getHost().getBytes();
4837        final byte[] digestBytes = digest.digest(hostBytes);
4838        int shaPrefix =
4839                digestBytes[0] << 24
4840                | digestBytes[1] << 16
4841                | digestBytes[2] << 8
4842                | digestBytes[3] << 0;
4843        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4844                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4845        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4846            // No hash prefix match; there are no ephemeral apps for this domain.
4847            return null;
4848        }
4849        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4850            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4851            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4852                continue;
4853            }
4854            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4855            // No filters; this should never happen.
4856            if (filters.isEmpty()) {
4857                continue;
4858            }
4859            // We have a domain match; resolve the filters to see if anything matches.
4860            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4861            for (int j = filters.size() - 1; j >= 0; --j) {
4862                final EphemeralResolveIntentInfo intentInfo =
4863                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4864                ephemeralResolver.addFilter(intentInfo);
4865            }
4866            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4867                    intent, resolvedType, false /*defaultOnly*/, userId);
4868            if (!matchedResolveInfoList.isEmpty()) {
4869                return matchedResolveInfoList.get(0);
4870            }
4871        }
4872        // Hash or filter mis-match; no ephemeral apps for this domain.
4873        return null;
4874    }
4875
4876    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4877            int flags, List<ResolveInfo> query, int userId) {
4878        if (query != null) {
4879            final int N = query.size();
4880            if (N == 1) {
4881                return query.get(0);
4882            } else if (N > 1) {
4883                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4884                // If there is more than one activity with the same priority,
4885                // then let the user decide between them.
4886                ResolveInfo r0 = query.get(0);
4887                ResolveInfo r1 = query.get(1);
4888                if (DEBUG_INTENT_MATCHING || debug) {
4889                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4890                            + r1.activityInfo.name + "=" + r1.priority);
4891                }
4892                // If the first activity has a higher priority, or a different
4893                // default, then it is always desirable to pick it.
4894                if (r0.priority != r1.priority
4895                        || r0.preferredOrder != r1.preferredOrder
4896                        || r0.isDefault != r1.isDefault) {
4897                    return query.get(0);
4898                }
4899                // If we have saved a preference for a preferred activity for
4900                // this Intent, use that.
4901                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4902                        flags, query, r0.priority, true, false, debug, userId);
4903                if (ri != null) {
4904                    return ri;
4905                }
4906                ri = new ResolveInfo(mResolveInfo);
4907                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4908                ri.activityInfo.applicationInfo = new ApplicationInfo(
4909                        ri.activityInfo.applicationInfo);
4910                if (userId != 0) {
4911                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4912                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4913                }
4914                // Make sure that the resolver is displayable in car mode
4915                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4916                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4917                return ri;
4918            }
4919        }
4920        return null;
4921    }
4922
4923    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4924            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4925        final int N = query.size();
4926        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4927                .get(userId);
4928        // Get the list of persistent preferred activities that handle the intent
4929        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4930        List<PersistentPreferredActivity> pprefs = ppir != null
4931                ? ppir.queryIntent(intent, resolvedType,
4932                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4933                : null;
4934        if (pprefs != null && pprefs.size() > 0) {
4935            final int M = pprefs.size();
4936            for (int i=0; i<M; i++) {
4937                final PersistentPreferredActivity ppa = pprefs.get(i);
4938                if (DEBUG_PREFERRED || debug) {
4939                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4940                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4941                            + "\n  component=" + ppa.mComponent);
4942                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4943                }
4944                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4945                        flags | MATCH_DISABLED_COMPONENTS, userId);
4946                if (DEBUG_PREFERRED || debug) {
4947                    Slog.v(TAG, "Found persistent preferred activity:");
4948                    if (ai != null) {
4949                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4950                    } else {
4951                        Slog.v(TAG, "  null");
4952                    }
4953                }
4954                if (ai == null) {
4955                    // This previously registered persistent preferred activity
4956                    // component is no longer known. Ignore it and do NOT remove it.
4957                    continue;
4958                }
4959                for (int j=0; j<N; j++) {
4960                    final ResolveInfo ri = query.get(j);
4961                    if (!ri.activityInfo.applicationInfo.packageName
4962                            .equals(ai.applicationInfo.packageName)) {
4963                        continue;
4964                    }
4965                    if (!ri.activityInfo.name.equals(ai.name)) {
4966                        continue;
4967                    }
4968                    //  Found a persistent preference that can handle the intent.
4969                    if (DEBUG_PREFERRED || debug) {
4970                        Slog.v(TAG, "Returning persistent preferred activity: " +
4971                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4972                    }
4973                    return ri;
4974                }
4975            }
4976        }
4977        return null;
4978    }
4979
4980    // TODO: handle preferred activities missing while user has amnesia
4981    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4982            List<ResolveInfo> query, int priority, boolean always,
4983            boolean removeMatches, boolean debug, int userId) {
4984        if (!sUserManager.exists(userId)) return null;
4985        flags = updateFlagsForResolve(flags, userId, intent);
4986        // writer
4987        synchronized (mPackages) {
4988            if (intent.getSelector() != null) {
4989                intent = intent.getSelector();
4990            }
4991            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4992
4993            // Try to find a matching persistent preferred activity.
4994            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4995                    debug, userId);
4996
4997            // If a persistent preferred activity matched, use it.
4998            if (pri != null) {
4999                return pri;
5000            }
5001
5002            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5003            // Get the list of preferred activities that handle the intent
5004            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5005            List<PreferredActivity> prefs = pir != null
5006                    ? pir.queryIntent(intent, resolvedType,
5007                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5008                    : null;
5009            if (prefs != null && prefs.size() > 0) {
5010                boolean changed = false;
5011                try {
5012                    // First figure out how good the original match set is.
5013                    // We will only allow preferred activities that came
5014                    // from the same match quality.
5015                    int match = 0;
5016
5017                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5018
5019                    final int N = query.size();
5020                    for (int j=0; j<N; j++) {
5021                        final ResolveInfo ri = query.get(j);
5022                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5023                                + ": 0x" + Integer.toHexString(match));
5024                        if (ri.match > match) {
5025                            match = ri.match;
5026                        }
5027                    }
5028
5029                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5030                            + Integer.toHexString(match));
5031
5032                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5033                    final int M = prefs.size();
5034                    for (int i=0; i<M; i++) {
5035                        final PreferredActivity pa = prefs.get(i);
5036                        if (DEBUG_PREFERRED || debug) {
5037                            Slog.v(TAG, "Checking PreferredActivity ds="
5038                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5039                                    + "\n  component=" + pa.mPref.mComponent);
5040                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5041                        }
5042                        if (pa.mPref.mMatch != match) {
5043                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5044                                    + Integer.toHexString(pa.mPref.mMatch));
5045                            continue;
5046                        }
5047                        // If it's not an "always" type preferred activity and that's what we're
5048                        // looking for, skip it.
5049                        if (always && !pa.mPref.mAlways) {
5050                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5051                            continue;
5052                        }
5053                        final ActivityInfo ai = getActivityInfo(
5054                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5055                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5056                                userId);
5057                        if (DEBUG_PREFERRED || debug) {
5058                            Slog.v(TAG, "Found preferred activity:");
5059                            if (ai != null) {
5060                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5061                            } else {
5062                                Slog.v(TAG, "  null");
5063                            }
5064                        }
5065                        if (ai == null) {
5066                            // This previously registered preferred activity
5067                            // component is no longer known.  Most likely an update
5068                            // to the app was installed and in the new version this
5069                            // component no longer exists.  Clean it up by removing
5070                            // it from the preferred activities list, and skip it.
5071                            Slog.w(TAG, "Removing dangling preferred activity: "
5072                                    + pa.mPref.mComponent);
5073                            pir.removeFilter(pa);
5074                            changed = true;
5075                            continue;
5076                        }
5077                        for (int j=0; j<N; j++) {
5078                            final ResolveInfo ri = query.get(j);
5079                            if (!ri.activityInfo.applicationInfo.packageName
5080                                    .equals(ai.applicationInfo.packageName)) {
5081                                continue;
5082                            }
5083                            if (!ri.activityInfo.name.equals(ai.name)) {
5084                                continue;
5085                            }
5086
5087                            if (removeMatches) {
5088                                pir.removeFilter(pa);
5089                                changed = true;
5090                                if (DEBUG_PREFERRED) {
5091                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5092                                }
5093                                break;
5094                            }
5095
5096                            // Okay we found a previously set preferred or last chosen app.
5097                            // If the result set is different from when this
5098                            // was created, we need to clear it and re-ask the
5099                            // user their preference, if we're looking for an "always" type entry.
5100                            if (always && !pa.mPref.sameSet(query)) {
5101                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5102                                        + intent + " type " + resolvedType);
5103                                if (DEBUG_PREFERRED) {
5104                                    Slog.v(TAG, "Removing preferred activity since set changed "
5105                                            + pa.mPref.mComponent);
5106                                }
5107                                pir.removeFilter(pa);
5108                                // Re-add the filter as a "last chosen" entry (!always)
5109                                PreferredActivity lastChosen = new PreferredActivity(
5110                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5111                                pir.addFilter(lastChosen);
5112                                changed = true;
5113                                return null;
5114                            }
5115
5116                            // Yay! Either the set matched or we're looking for the last chosen
5117                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5118                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5119                            return ri;
5120                        }
5121                    }
5122                } finally {
5123                    if (changed) {
5124                        if (DEBUG_PREFERRED) {
5125                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5126                        }
5127                        scheduleWritePackageRestrictionsLocked(userId);
5128                    }
5129                }
5130            }
5131        }
5132        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5133        return null;
5134    }
5135
5136    /*
5137     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5138     */
5139    @Override
5140    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5141            int targetUserId) {
5142        mContext.enforceCallingOrSelfPermission(
5143                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5144        List<CrossProfileIntentFilter> matches =
5145                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5146        if (matches != null) {
5147            int size = matches.size();
5148            for (int i = 0; i < size; i++) {
5149                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5150            }
5151        }
5152        if (hasWebURI(intent)) {
5153            // cross-profile app linking works only towards the parent.
5154            final UserInfo parent = getProfileParent(sourceUserId);
5155            synchronized(mPackages) {
5156                int flags = updateFlagsForResolve(0, parent.id, intent);
5157                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5158                        intent, resolvedType, flags, sourceUserId, parent.id);
5159                return xpDomainInfo != null;
5160            }
5161        }
5162        return false;
5163    }
5164
5165    private UserInfo getProfileParent(int userId) {
5166        final long identity = Binder.clearCallingIdentity();
5167        try {
5168            return sUserManager.getProfileParent(userId);
5169        } finally {
5170            Binder.restoreCallingIdentity(identity);
5171        }
5172    }
5173
5174    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5175            String resolvedType, int userId) {
5176        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5177        if (resolver != null) {
5178            return resolver.queryIntent(intent, resolvedType, false, userId);
5179        }
5180        return null;
5181    }
5182
5183    @Override
5184    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5185            String resolvedType, int flags, int userId) {
5186        return new ParceledListSlice<>(
5187                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5188    }
5189
5190    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5191            String resolvedType, int flags, int userId) {
5192        if (!sUserManager.exists(userId)) return Collections.emptyList();
5193        flags = updateFlagsForResolve(flags, userId, intent);
5194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5195                false /* requireFullPermission */, false /* checkShell */,
5196                "query intent activities");
5197        ComponentName comp = intent.getComponent();
5198        if (comp == null) {
5199            if (intent.getSelector() != null) {
5200                intent = intent.getSelector();
5201                comp = intent.getComponent();
5202            }
5203        }
5204
5205        if (comp != null) {
5206            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5207            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5208            if (ai != null) {
5209                final ResolveInfo ri = new ResolveInfo();
5210                ri.activityInfo = ai;
5211                list.add(ri);
5212            }
5213            return list;
5214        }
5215
5216        // reader
5217        synchronized (mPackages) {
5218            final String pkgName = intent.getPackage();
5219            if (pkgName == null) {
5220                List<CrossProfileIntentFilter> matchingFilters =
5221                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5222                // Check for results that need to skip the current profile.
5223                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5224                        resolvedType, flags, userId);
5225                if (xpResolveInfo != null) {
5226                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5227                    result.add(xpResolveInfo);
5228                    return filterIfNotSystemUser(result, userId);
5229                }
5230
5231                // Check for results in the current profile.
5232                List<ResolveInfo> result = mActivities.queryIntent(
5233                        intent, resolvedType, flags, userId);
5234                result = filterIfNotSystemUser(result, userId);
5235
5236                // Check for cross profile results.
5237                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5238                xpResolveInfo = queryCrossProfileIntents(
5239                        matchingFilters, intent, resolvedType, flags, userId,
5240                        hasNonNegativePriorityResult);
5241                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5242                    boolean isVisibleToUser = filterIfNotSystemUser(
5243                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5244                    if (isVisibleToUser) {
5245                        result.add(xpResolveInfo);
5246                        Collections.sort(result, mResolvePrioritySorter);
5247                    }
5248                }
5249                if (hasWebURI(intent)) {
5250                    CrossProfileDomainInfo xpDomainInfo = null;
5251                    final UserInfo parent = getProfileParent(userId);
5252                    if (parent != null) {
5253                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5254                                flags, userId, parent.id);
5255                    }
5256                    if (xpDomainInfo != null) {
5257                        if (xpResolveInfo != null) {
5258                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5259                            // in the result.
5260                            result.remove(xpResolveInfo);
5261                        }
5262                        if (result.size() == 0) {
5263                            result.add(xpDomainInfo.resolveInfo);
5264                            return result;
5265                        }
5266                    } else if (result.size() <= 1) {
5267                        return result;
5268                    }
5269                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5270                            xpDomainInfo, userId);
5271                    Collections.sort(result, mResolvePrioritySorter);
5272                }
5273                return result;
5274            }
5275            final PackageParser.Package pkg = mPackages.get(pkgName);
5276            if (pkg != null) {
5277                return filterIfNotSystemUser(
5278                        mActivities.queryIntentForPackage(
5279                                intent, resolvedType, flags, pkg.activities, userId),
5280                        userId);
5281            }
5282            return new ArrayList<ResolveInfo>();
5283        }
5284    }
5285
5286    private static class CrossProfileDomainInfo {
5287        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5288        ResolveInfo resolveInfo;
5289        /* Best domain verification status of the activities found in the other profile */
5290        int bestDomainVerificationStatus;
5291    }
5292
5293    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5294            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5295        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5296                sourceUserId)) {
5297            return null;
5298        }
5299        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5300                resolvedType, flags, parentUserId);
5301
5302        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5303            return null;
5304        }
5305        CrossProfileDomainInfo result = null;
5306        int size = resultTargetUser.size();
5307        for (int i = 0; i < size; i++) {
5308            ResolveInfo riTargetUser = resultTargetUser.get(i);
5309            // Intent filter verification is only for filters that specify a host. So don't return
5310            // those that handle all web uris.
5311            if (riTargetUser.handleAllWebDataURI) {
5312                continue;
5313            }
5314            String packageName = riTargetUser.activityInfo.packageName;
5315            PackageSetting ps = mSettings.mPackages.get(packageName);
5316            if (ps == null) {
5317                continue;
5318            }
5319            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5320            int status = (int)(verificationState >> 32);
5321            if (result == null) {
5322                result = new CrossProfileDomainInfo();
5323                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5324                        sourceUserId, parentUserId);
5325                result.bestDomainVerificationStatus = status;
5326            } else {
5327                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5328                        result.bestDomainVerificationStatus);
5329            }
5330        }
5331        // Don't consider matches with status NEVER across profiles.
5332        if (result != null && result.bestDomainVerificationStatus
5333                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5334            return null;
5335        }
5336        return result;
5337    }
5338
5339    /**
5340     * Verification statuses are ordered from the worse to the best, except for
5341     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5342     */
5343    private int bestDomainVerificationStatus(int status1, int status2) {
5344        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5345            return status2;
5346        }
5347        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5348            return status1;
5349        }
5350        return (int) MathUtils.max(status1, status2);
5351    }
5352
5353    private boolean isUserEnabled(int userId) {
5354        long callingId = Binder.clearCallingIdentity();
5355        try {
5356            UserInfo userInfo = sUserManager.getUserInfo(userId);
5357            return userInfo != null && userInfo.isEnabled();
5358        } finally {
5359            Binder.restoreCallingIdentity(callingId);
5360        }
5361    }
5362
5363    /**
5364     * Filter out activities with systemUserOnly flag set, when current user is not System.
5365     *
5366     * @return filtered list
5367     */
5368    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5369        if (userId == UserHandle.USER_SYSTEM) {
5370            return resolveInfos;
5371        }
5372        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5373            ResolveInfo info = resolveInfos.get(i);
5374            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5375                resolveInfos.remove(i);
5376            }
5377        }
5378        return resolveInfos;
5379    }
5380
5381    /**
5382     * @param resolveInfos list of resolve infos in descending priority order
5383     * @return if the list contains a resolve info with non-negative priority
5384     */
5385    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5386        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5387    }
5388
5389    private static boolean hasWebURI(Intent intent) {
5390        if (intent.getData() == null) {
5391            return false;
5392        }
5393        final String scheme = intent.getScheme();
5394        if (TextUtils.isEmpty(scheme)) {
5395            return false;
5396        }
5397        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5398    }
5399
5400    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5401            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5402            int userId) {
5403        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5404
5405        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5406            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5407                    candidates.size());
5408        }
5409
5410        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5411        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5412        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5413        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5414        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5415        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5416
5417        synchronized (mPackages) {
5418            final int count = candidates.size();
5419            // First, try to use linked apps. Partition the candidates into four lists:
5420            // one for the final results, one for the "do not use ever", one for "undefined status"
5421            // and finally one for "browser app type".
5422            for (int n=0; n<count; n++) {
5423                ResolveInfo info = candidates.get(n);
5424                String packageName = info.activityInfo.packageName;
5425                PackageSetting ps = mSettings.mPackages.get(packageName);
5426                if (ps != null) {
5427                    // Add to the special match all list (Browser use case)
5428                    if (info.handleAllWebDataURI) {
5429                        matchAllList.add(info);
5430                        continue;
5431                    }
5432                    // Try to get the status from User settings first
5433                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5434                    int status = (int)(packedStatus >> 32);
5435                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5436                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5437                        if (DEBUG_DOMAIN_VERIFICATION) {
5438                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5439                                    + " : linkgen=" + linkGeneration);
5440                        }
5441                        // Use link-enabled generation as preferredOrder, i.e.
5442                        // prefer newly-enabled over earlier-enabled.
5443                        info.preferredOrder = linkGeneration;
5444                        alwaysList.add(info);
5445                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5446                        if (DEBUG_DOMAIN_VERIFICATION) {
5447                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5448                        }
5449                        neverList.add(info);
5450                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5451                        if (DEBUG_DOMAIN_VERIFICATION) {
5452                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5453                        }
5454                        alwaysAskList.add(info);
5455                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5456                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5457                        if (DEBUG_DOMAIN_VERIFICATION) {
5458                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5459                        }
5460                        undefinedList.add(info);
5461                    }
5462                }
5463            }
5464
5465            // We'll want to include browser possibilities in a few cases
5466            boolean includeBrowser = false;
5467
5468            // First try to add the "always" resolution(s) for the current user, if any
5469            if (alwaysList.size() > 0) {
5470                result.addAll(alwaysList);
5471            } else {
5472                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5473                result.addAll(undefinedList);
5474                // Maybe add one for the other profile.
5475                if (xpDomainInfo != null && (
5476                        xpDomainInfo.bestDomainVerificationStatus
5477                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5478                    result.add(xpDomainInfo.resolveInfo);
5479                }
5480                includeBrowser = true;
5481            }
5482
5483            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5484            // If there were 'always' entries their preferred order has been set, so we also
5485            // back that off to make the alternatives equivalent
5486            if (alwaysAskList.size() > 0) {
5487                for (ResolveInfo i : result) {
5488                    i.preferredOrder = 0;
5489                }
5490                result.addAll(alwaysAskList);
5491                includeBrowser = true;
5492            }
5493
5494            if (includeBrowser) {
5495                // Also add browsers (all of them or only the default one)
5496                if (DEBUG_DOMAIN_VERIFICATION) {
5497                    Slog.v(TAG, "   ...including browsers in candidate set");
5498                }
5499                if ((matchFlags & MATCH_ALL) != 0) {
5500                    result.addAll(matchAllList);
5501                } else {
5502                    // Browser/generic handling case.  If there's a default browser, go straight
5503                    // to that (but only if there is no other higher-priority match).
5504                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5505                    int maxMatchPrio = 0;
5506                    ResolveInfo defaultBrowserMatch = null;
5507                    final int numCandidates = matchAllList.size();
5508                    for (int n = 0; n < numCandidates; n++) {
5509                        ResolveInfo info = matchAllList.get(n);
5510                        // track the highest overall match priority...
5511                        if (info.priority > maxMatchPrio) {
5512                            maxMatchPrio = info.priority;
5513                        }
5514                        // ...and the highest-priority default browser match
5515                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5516                            if (defaultBrowserMatch == null
5517                                    || (defaultBrowserMatch.priority < info.priority)) {
5518                                if (debug) {
5519                                    Slog.v(TAG, "Considering default browser match " + info);
5520                                }
5521                                defaultBrowserMatch = info;
5522                            }
5523                        }
5524                    }
5525                    if (defaultBrowserMatch != null
5526                            && defaultBrowserMatch.priority >= maxMatchPrio
5527                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5528                    {
5529                        if (debug) {
5530                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5531                        }
5532                        result.add(defaultBrowserMatch);
5533                    } else {
5534                        result.addAll(matchAllList);
5535                    }
5536                }
5537
5538                // If there is nothing selected, add all candidates and remove the ones that the user
5539                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5540                if (result.size() == 0) {
5541                    result.addAll(candidates);
5542                    result.removeAll(neverList);
5543                }
5544            }
5545        }
5546        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5547            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5548                    result.size());
5549            for (ResolveInfo info : result) {
5550                Slog.v(TAG, "  + " + info.activityInfo);
5551            }
5552        }
5553        return result;
5554    }
5555
5556    // Returns a packed value as a long:
5557    //
5558    // high 'int'-sized word: link status: undefined/ask/never/always.
5559    // low 'int'-sized word: relative priority among 'always' results.
5560    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5561        long result = ps.getDomainVerificationStatusForUser(userId);
5562        // if none available, get the master status
5563        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5564            if (ps.getIntentFilterVerificationInfo() != null) {
5565                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5566            }
5567        }
5568        return result;
5569    }
5570
5571    private ResolveInfo querySkipCurrentProfileIntents(
5572            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5573            int flags, int sourceUserId) {
5574        if (matchingFilters != null) {
5575            int size = matchingFilters.size();
5576            for (int i = 0; i < size; i ++) {
5577                CrossProfileIntentFilter filter = matchingFilters.get(i);
5578                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5579                    // Checking if there are activities in the target user that can handle the
5580                    // intent.
5581                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5582                            resolvedType, flags, sourceUserId);
5583                    if (resolveInfo != null) {
5584                        return resolveInfo;
5585                    }
5586                }
5587            }
5588        }
5589        return null;
5590    }
5591
5592    // Return matching ResolveInfo in target user if any.
5593    private ResolveInfo queryCrossProfileIntents(
5594            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5595            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5596        if (matchingFilters != null) {
5597            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5598            // match the same intent. For performance reasons, it is better not to
5599            // run queryIntent twice for the same userId
5600            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5601            int size = matchingFilters.size();
5602            for (int i = 0; i < size; i++) {
5603                CrossProfileIntentFilter filter = matchingFilters.get(i);
5604                int targetUserId = filter.getTargetUserId();
5605                boolean skipCurrentProfile =
5606                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5607                boolean skipCurrentProfileIfNoMatchFound =
5608                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5609                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5610                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5611                    // Checking if there are activities in the target user that can handle the
5612                    // intent.
5613                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5614                            resolvedType, flags, sourceUserId);
5615                    if (resolveInfo != null) return resolveInfo;
5616                    alreadyTriedUserIds.put(targetUserId, true);
5617                }
5618            }
5619        }
5620        return null;
5621    }
5622
5623    /**
5624     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5625     * will forward the intent to the filter's target user.
5626     * Otherwise, returns null.
5627     */
5628    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5629            String resolvedType, int flags, int sourceUserId) {
5630        int targetUserId = filter.getTargetUserId();
5631        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5632                resolvedType, flags, targetUserId);
5633        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5634            // If all the matches in the target profile are suspended, return null.
5635            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5636                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5637                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5638                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5639                            targetUserId);
5640                }
5641            }
5642        }
5643        return null;
5644    }
5645
5646    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5647            int sourceUserId, int targetUserId) {
5648        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5649        long ident = Binder.clearCallingIdentity();
5650        boolean targetIsProfile;
5651        try {
5652            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5653        } finally {
5654            Binder.restoreCallingIdentity(ident);
5655        }
5656        String className;
5657        if (targetIsProfile) {
5658            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5659        } else {
5660            className = FORWARD_INTENT_TO_PARENT;
5661        }
5662        ComponentName forwardingActivityComponentName = new ComponentName(
5663                mAndroidApplication.packageName, className);
5664        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5665                sourceUserId);
5666        if (!targetIsProfile) {
5667            forwardingActivityInfo.showUserIcon = targetUserId;
5668            forwardingResolveInfo.noResourceId = true;
5669        }
5670        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5671        forwardingResolveInfo.priority = 0;
5672        forwardingResolveInfo.preferredOrder = 0;
5673        forwardingResolveInfo.match = 0;
5674        forwardingResolveInfo.isDefault = true;
5675        forwardingResolveInfo.filter = filter;
5676        forwardingResolveInfo.targetUserId = targetUserId;
5677        return forwardingResolveInfo;
5678    }
5679
5680    @Override
5681    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5682            Intent[] specifics, String[] specificTypes, Intent intent,
5683            String resolvedType, int flags, int userId) {
5684        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5685                specificTypes, intent, resolvedType, flags, userId));
5686    }
5687
5688    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5689            Intent[] specifics, String[] specificTypes, Intent intent,
5690            String resolvedType, int flags, int userId) {
5691        if (!sUserManager.exists(userId)) return Collections.emptyList();
5692        flags = updateFlagsForResolve(flags, userId, intent);
5693        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5694                false /* requireFullPermission */, false /* checkShell */,
5695                "query intent activity options");
5696        final String resultsAction = intent.getAction();
5697
5698        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5699                | PackageManager.GET_RESOLVED_FILTER, userId);
5700
5701        if (DEBUG_INTENT_MATCHING) {
5702            Log.v(TAG, "Query " + intent + ": " + results);
5703        }
5704
5705        int specificsPos = 0;
5706        int N;
5707
5708        // todo: note that the algorithm used here is O(N^2).  This
5709        // isn't a problem in our current environment, but if we start running
5710        // into situations where we have more than 5 or 10 matches then this
5711        // should probably be changed to something smarter...
5712
5713        // First we go through and resolve each of the specific items
5714        // that were supplied, taking care of removing any corresponding
5715        // duplicate items in the generic resolve list.
5716        if (specifics != null) {
5717            for (int i=0; i<specifics.length; i++) {
5718                final Intent sintent = specifics[i];
5719                if (sintent == null) {
5720                    continue;
5721                }
5722
5723                if (DEBUG_INTENT_MATCHING) {
5724                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5725                }
5726
5727                String action = sintent.getAction();
5728                if (resultsAction != null && resultsAction.equals(action)) {
5729                    // If this action was explicitly requested, then don't
5730                    // remove things that have it.
5731                    action = null;
5732                }
5733
5734                ResolveInfo ri = null;
5735                ActivityInfo ai = null;
5736
5737                ComponentName comp = sintent.getComponent();
5738                if (comp == null) {
5739                    ri = resolveIntent(
5740                        sintent,
5741                        specificTypes != null ? specificTypes[i] : null,
5742                            flags, userId);
5743                    if (ri == null) {
5744                        continue;
5745                    }
5746                    if (ri == mResolveInfo) {
5747                        // ACK!  Must do something better with this.
5748                    }
5749                    ai = ri.activityInfo;
5750                    comp = new ComponentName(ai.applicationInfo.packageName,
5751                            ai.name);
5752                } else {
5753                    ai = getActivityInfo(comp, flags, userId);
5754                    if (ai == null) {
5755                        continue;
5756                    }
5757                }
5758
5759                // Look for any generic query activities that are duplicates
5760                // of this specific one, and remove them from the results.
5761                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5762                N = results.size();
5763                int j;
5764                for (j=specificsPos; j<N; j++) {
5765                    ResolveInfo sri = results.get(j);
5766                    if ((sri.activityInfo.name.equals(comp.getClassName())
5767                            && sri.activityInfo.applicationInfo.packageName.equals(
5768                                    comp.getPackageName()))
5769                        || (action != null && sri.filter.matchAction(action))) {
5770                        results.remove(j);
5771                        if (DEBUG_INTENT_MATCHING) Log.v(
5772                            TAG, "Removing duplicate item from " + j
5773                            + " due to specific " + specificsPos);
5774                        if (ri == null) {
5775                            ri = sri;
5776                        }
5777                        j--;
5778                        N--;
5779                    }
5780                }
5781
5782                // Add this specific item to its proper place.
5783                if (ri == null) {
5784                    ri = new ResolveInfo();
5785                    ri.activityInfo = ai;
5786                }
5787                results.add(specificsPos, ri);
5788                ri.specificIndex = i;
5789                specificsPos++;
5790            }
5791        }
5792
5793        // Now we go through the remaining generic results and remove any
5794        // duplicate actions that are found here.
5795        N = results.size();
5796        for (int i=specificsPos; i<N-1; i++) {
5797            final ResolveInfo rii = results.get(i);
5798            if (rii.filter == null) {
5799                continue;
5800            }
5801
5802            // Iterate over all of the actions of this result's intent
5803            // filter...  typically this should be just one.
5804            final Iterator<String> it = rii.filter.actionsIterator();
5805            if (it == null) {
5806                continue;
5807            }
5808            while (it.hasNext()) {
5809                final String action = it.next();
5810                if (resultsAction != null && resultsAction.equals(action)) {
5811                    // If this action was explicitly requested, then don't
5812                    // remove things that have it.
5813                    continue;
5814                }
5815                for (int j=i+1; j<N; j++) {
5816                    final ResolveInfo rij = results.get(j);
5817                    if (rij.filter != null && rij.filter.hasAction(action)) {
5818                        results.remove(j);
5819                        if (DEBUG_INTENT_MATCHING) Log.v(
5820                            TAG, "Removing duplicate item from " + j
5821                            + " due to action " + action + " at " + i);
5822                        j--;
5823                        N--;
5824                    }
5825                }
5826            }
5827
5828            // If the caller didn't request filter information, drop it now
5829            // so we don't have to marshall/unmarshall it.
5830            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5831                rii.filter = null;
5832            }
5833        }
5834
5835        // Filter out the caller activity if so requested.
5836        if (caller != null) {
5837            N = results.size();
5838            for (int i=0; i<N; i++) {
5839                ActivityInfo ainfo = results.get(i).activityInfo;
5840                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5841                        && caller.getClassName().equals(ainfo.name)) {
5842                    results.remove(i);
5843                    break;
5844                }
5845            }
5846        }
5847
5848        // If the caller didn't request filter information,
5849        // drop them now so we don't have to
5850        // marshall/unmarshall it.
5851        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5852            N = results.size();
5853            for (int i=0; i<N; i++) {
5854                results.get(i).filter = null;
5855            }
5856        }
5857
5858        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5859        return results;
5860    }
5861
5862    @Override
5863    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5864            String resolvedType, int flags, int userId) {
5865        return new ParceledListSlice<>(
5866                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5867    }
5868
5869    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5870            String resolvedType, int flags, int userId) {
5871        if (!sUserManager.exists(userId)) return Collections.emptyList();
5872        flags = updateFlagsForResolve(flags, userId, intent);
5873        ComponentName comp = intent.getComponent();
5874        if (comp == null) {
5875            if (intent.getSelector() != null) {
5876                intent = intent.getSelector();
5877                comp = intent.getComponent();
5878            }
5879        }
5880        if (comp != null) {
5881            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5882            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5883            if (ai != null) {
5884                ResolveInfo ri = new ResolveInfo();
5885                ri.activityInfo = ai;
5886                list.add(ri);
5887            }
5888            return list;
5889        }
5890
5891        // reader
5892        synchronized (mPackages) {
5893            String pkgName = intent.getPackage();
5894            if (pkgName == null) {
5895                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5896            }
5897            final PackageParser.Package pkg = mPackages.get(pkgName);
5898            if (pkg != null) {
5899                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5900                        userId);
5901            }
5902            return Collections.emptyList();
5903        }
5904    }
5905
5906    @Override
5907    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5908        if (!sUserManager.exists(userId)) return null;
5909        flags = updateFlagsForResolve(flags, userId, intent);
5910        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5911        if (query != null) {
5912            if (query.size() >= 1) {
5913                // If there is more than one service with the same priority,
5914                // just arbitrarily pick the first one.
5915                return query.get(0);
5916            }
5917        }
5918        return null;
5919    }
5920
5921    @Override
5922    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5923            String resolvedType, int flags, int userId) {
5924        return new ParceledListSlice<>(
5925                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5926    }
5927
5928    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5929            String resolvedType, int flags, int userId) {
5930        if (!sUserManager.exists(userId)) return Collections.emptyList();
5931        flags = updateFlagsForResolve(flags, userId, intent);
5932        ComponentName comp = intent.getComponent();
5933        if (comp == null) {
5934            if (intent.getSelector() != null) {
5935                intent = intent.getSelector();
5936                comp = intent.getComponent();
5937            }
5938        }
5939        if (comp != null) {
5940            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5941            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5942            if (si != null) {
5943                final ResolveInfo ri = new ResolveInfo();
5944                ri.serviceInfo = si;
5945                list.add(ri);
5946            }
5947            return list;
5948        }
5949
5950        // reader
5951        synchronized (mPackages) {
5952            String pkgName = intent.getPackage();
5953            if (pkgName == null) {
5954                return mServices.queryIntent(intent, resolvedType, flags, userId);
5955            }
5956            final PackageParser.Package pkg = mPackages.get(pkgName);
5957            if (pkg != null) {
5958                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5959                        userId);
5960            }
5961            return Collections.emptyList();
5962        }
5963    }
5964
5965    @Override
5966    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5967            String resolvedType, int flags, int userId) {
5968        return new ParceledListSlice<>(
5969                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5970    }
5971
5972    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5973            Intent intent, String resolvedType, int flags, int userId) {
5974        if (!sUserManager.exists(userId)) return Collections.emptyList();
5975        flags = updateFlagsForResolve(flags, userId, intent);
5976        ComponentName comp = intent.getComponent();
5977        if (comp == null) {
5978            if (intent.getSelector() != null) {
5979                intent = intent.getSelector();
5980                comp = intent.getComponent();
5981            }
5982        }
5983        if (comp != null) {
5984            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5985            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5986            if (pi != null) {
5987                final ResolveInfo ri = new ResolveInfo();
5988                ri.providerInfo = pi;
5989                list.add(ri);
5990            }
5991            return list;
5992        }
5993
5994        // reader
5995        synchronized (mPackages) {
5996            String pkgName = intent.getPackage();
5997            if (pkgName == null) {
5998                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5999            }
6000            final PackageParser.Package pkg = mPackages.get(pkgName);
6001            if (pkg != null) {
6002                return mProviders.queryIntentForPackage(
6003                        intent, resolvedType, flags, pkg.providers, userId);
6004            }
6005            return Collections.emptyList();
6006        }
6007    }
6008
6009    @Override
6010    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6011        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6012        flags = updateFlagsForPackage(flags, userId, null);
6013        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6014        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6015                true /* requireFullPermission */, false /* checkShell */,
6016                "get installed packages");
6017
6018        // writer
6019        synchronized (mPackages) {
6020            ArrayList<PackageInfo> list;
6021            if (listUninstalled) {
6022                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6023                for (PackageSetting ps : mSettings.mPackages.values()) {
6024                    final PackageInfo pi;
6025                    if (ps.pkg != null) {
6026                        pi = generatePackageInfo(ps, flags, userId);
6027                    } else {
6028                        pi = generatePackageInfo(ps, flags, userId);
6029                    }
6030                    if (pi != null) {
6031                        list.add(pi);
6032                    }
6033                }
6034            } else {
6035                list = new ArrayList<PackageInfo>(mPackages.size());
6036                for (PackageParser.Package p : mPackages.values()) {
6037                    final PackageInfo pi =
6038                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6039                    if (pi != null) {
6040                        list.add(pi);
6041                    }
6042                }
6043            }
6044
6045            return new ParceledListSlice<PackageInfo>(list);
6046        }
6047    }
6048
6049    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6050            String[] permissions, boolean[] tmp, int flags, int userId) {
6051        int numMatch = 0;
6052        final PermissionsState permissionsState = ps.getPermissionsState();
6053        for (int i=0; i<permissions.length; i++) {
6054            final String permission = permissions[i];
6055            if (permissionsState.hasPermission(permission, userId)) {
6056                tmp[i] = true;
6057                numMatch++;
6058            } else {
6059                tmp[i] = false;
6060            }
6061        }
6062        if (numMatch == 0) {
6063            return;
6064        }
6065        final PackageInfo pi;
6066        if (ps.pkg != null) {
6067            pi = generatePackageInfo(ps, flags, userId);
6068        } else {
6069            pi = generatePackageInfo(ps, flags, userId);
6070        }
6071        // The above might return null in cases of uninstalled apps or install-state
6072        // skew across users/profiles.
6073        if (pi != null) {
6074            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6075                if (numMatch == permissions.length) {
6076                    pi.requestedPermissions = permissions;
6077                } else {
6078                    pi.requestedPermissions = new String[numMatch];
6079                    numMatch = 0;
6080                    for (int i=0; i<permissions.length; i++) {
6081                        if (tmp[i]) {
6082                            pi.requestedPermissions[numMatch] = permissions[i];
6083                            numMatch++;
6084                        }
6085                    }
6086                }
6087            }
6088            list.add(pi);
6089        }
6090    }
6091
6092    @Override
6093    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6094            String[] permissions, int flags, int userId) {
6095        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6096        flags = updateFlagsForPackage(flags, userId, permissions);
6097        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6098
6099        // writer
6100        synchronized (mPackages) {
6101            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6102            boolean[] tmpBools = new boolean[permissions.length];
6103            if (listUninstalled) {
6104                for (PackageSetting ps : mSettings.mPackages.values()) {
6105                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6106                }
6107            } else {
6108                for (PackageParser.Package pkg : mPackages.values()) {
6109                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6110                    if (ps != null) {
6111                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6112                                userId);
6113                    }
6114                }
6115            }
6116
6117            return new ParceledListSlice<PackageInfo>(list);
6118        }
6119    }
6120
6121    @Override
6122    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6123        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6124        flags = updateFlagsForApplication(flags, userId, null);
6125        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6126
6127        // writer
6128        synchronized (mPackages) {
6129            ArrayList<ApplicationInfo> list;
6130            if (listUninstalled) {
6131                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6132                for (PackageSetting ps : mSettings.mPackages.values()) {
6133                    ApplicationInfo ai;
6134                    if (ps.pkg != null) {
6135                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6136                                ps.readUserState(userId), userId);
6137                    } else {
6138                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6139                    }
6140                    if (ai != null) {
6141                        list.add(ai);
6142                    }
6143                }
6144            } else {
6145                list = new ArrayList<ApplicationInfo>(mPackages.size());
6146                for (PackageParser.Package p : mPackages.values()) {
6147                    if (p.mExtras != null) {
6148                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6149                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6150                        if (ai != null) {
6151                            list.add(ai);
6152                        }
6153                    }
6154                }
6155            }
6156
6157            return new ParceledListSlice<ApplicationInfo>(list);
6158        }
6159    }
6160
6161    @Override
6162    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6163        if (DISABLE_EPHEMERAL_APPS) {
6164            return null;
6165        }
6166
6167        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6168                "getEphemeralApplications");
6169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6170                true /* requireFullPermission */, false /* checkShell */,
6171                "getEphemeralApplications");
6172        synchronized (mPackages) {
6173            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6174                    .getEphemeralApplicationsLPw(userId);
6175            if (ephemeralApps != null) {
6176                return new ParceledListSlice<>(ephemeralApps);
6177            }
6178        }
6179        return null;
6180    }
6181
6182    @Override
6183    public boolean isEphemeralApplication(String packageName, int userId) {
6184        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6185                true /* requireFullPermission */, false /* checkShell */,
6186                "isEphemeral");
6187        if (DISABLE_EPHEMERAL_APPS) {
6188            return false;
6189        }
6190
6191        if (!isCallerSameApp(packageName)) {
6192            return false;
6193        }
6194        synchronized (mPackages) {
6195            PackageParser.Package pkg = mPackages.get(packageName);
6196            if (pkg != null) {
6197                return pkg.applicationInfo.isEphemeralApp();
6198            }
6199        }
6200        return false;
6201    }
6202
6203    @Override
6204    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6205        if (DISABLE_EPHEMERAL_APPS) {
6206            return null;
6207        }
6208
6209        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6210                true /* requireFullPermission */, false /* checkShell */,
6211                "getCookie");
6212        if (!isCallerSameApp(packageName)) {
6213            return null;
6214        }
6215        synchronized (mPackages) {
6216            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6217                    packageName, userId);
6218        }
6219    }
6220
6221    @Override
6222    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6223        if (DISABLE_EPHEMERAL_APPS) {
6224            return true;
6225        }
6226
6227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6228                true /* requireFullPermission */, true /* checkShell */,
6229                "setCookie");
6230        if (!isCallerSameApp(packageName)) {
6231            return false;
6232        }
6233        synchronized (mPackages) {
6234            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6235                    packageName, cookie, userId);
6236        }
6237    }
6238
6239    @Override
6240    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6241        if (DISABLE_EPHEMERAL_APPS) {
6242            return null;
6243        }
6244
6245        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6246                "getEphemeralApplicationIcon");
6247        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6248                true /* requireFullPermission */, false /* checkShell */,
6249                "getEphemeralApplicationIcon");
6250        synchronized (mPackages) {
6251            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6252                    packageName, userId);
6253        }
6254    }
6255
6256    private boolean isCallerSameApp(String packageName) {
6257        PackageParser.Package pkg = mPackages.get(packageName);
6258        return pkg != null
6259                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6260    }
6261
6262    @Override
6263    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6264        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6265    }
6266
6267    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6268        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6269
6270        // reader
6271        synchronized (mPackages) {
6272            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6273            final int userId = UserHandle.getCallingUserId();
6274            while (i.hasNext()) {
6275                final PackageParser.Package p = i.next();
6276                if (p.applicationInfo == null) continue;
6277
6278                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6279                        && !p.applicationInfo.isDirectBootAware();
6280                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6281                        && p.applicationInfo.isDirectBootAware();
6282
6283                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6284                        && (!mSafeMode || isSystemApp(p))
6285                        && (matchesUnaware || matchesAware)) {
6286                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6287                    if (ps != null) {
6288                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6289                                ps.readUserState(userId), userId);
6290                        if (ai != null) {
6291                            finalList.add(ai);
6292                        }
6293                    }
6294                }
6295            }
6296        }
6297
6298        return finalList;
6299    }
6300
6301    @Override
6302    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6303        if (!sUserManager.exists(userId)) return null;
6304        flags = updateFlagsForComponent(flags, userId, name);
6305        // reader
6306        synchronized (mPackages) {
6307            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6308            PackageSetting ps = provider != null
6309                    ? mSettings.mPackages.get(provider.owner.packageName)
6310                    : null;
6311            return ps != null
6312                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6313                    ? PackageParser.generateProviderInfo(provider, flags,
6314                            ps.readUserState(userId), userId)
6315                    : null;
6316        }
6317    }
6318
6319    /**
6320     * @deprecated
6321     */
6322    @Deprecated
6323    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6324        // reader
6325        synchronized (mPackages) {
6326            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6327                    .entrySet().iterator();
6328            final int userId = UserHandle.getCallingUserId();
6329            while (i.hasNext()) {
6330                Map.Entry<String, PackageParser.Provider> entry = i.next();
6331                PackageParser.Provider p = entry.getValue();
6332                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6333
6334                if (ps != null && p.syncable
6335                        && (!mSafeMode || (p.info.applicationInfo.flags
6336                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6337                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6338                            ps.readUserState(userId), userId);
6339                    if (info != null) {
6340                        outNames.add(entry.getKey());
6341                        outInfo.add(info);
6342                    }
6343                }
6344            }
6345        }
6346    }
6347
6348    @Override
6349    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6350            int uid, int flags) {
6351        final int userId = processName != null ? UserHandle.getUserId(uid)
6352                : UserHandle.getCallingUserId();
6353        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6354        flags = updateFlagsForComponent(flags, userId, processName);
6355
6356        ArrayList<ProviderInfo> finalList = null;
6357        // reader
6358        synchronized (mPackages) {
6359            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6360            while (i.hasNext()) {
6361                final PackageParser.Provider p = i.next();
6362                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6363                if (ps != null && p.info.authority != null
6364                        && (processName == null
6365                                || (p.info.processName.equals(processName)
6366                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6367                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6368                    if (finalList == null) {
6369                        finalList = new ArrayList<ProviderInfo>(3);
6370                    }
6371                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6372                            ps.readUserState(userId), userId);
6373                    if (info != null) {
6374                        finalList.add(info);
6375                    }
6376                }
6377            }
6378        }
6379
6380        if (finalList != null) {
6381            Collections.sort(finalList, mProviderInitOrderSorter);
6382            return new ParceledListSlice<ProviderInfo>(finalList);
6383        }
6384
6385        return ParceledListSlice.emptyList();
6386    }
6387
6388    @Override
6389    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6390        // reader
6391        synchronized (mPackages) {
6392            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6393            return PackageParser.generateInstrumentationInfo(i, flags);
6394        }
6395    }
6396
6397    @Override
6398    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6399            String targetPackage, int flags) {
6400        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6401    }
6402
6403    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6404            int flags) {
6405        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6406
6407        // reader
6408        synchronized (mPackages) {
6409            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6410            while (i.hasNext()) {
6411                final PackageParser.Instrumentation p = i.next();
6412                if (targetPackage == null
6413                        || targetPackage.equals(p.info.targetPackage)) {
6414                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6415                            flags);
6416                    if (ii != null) {
6417                        finalList.add(ii);
6418                    }
6419                }
6420            }
6421        }
6422
6423        return finalList;
6424    }
6425
6426    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6427        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6428        if (overlays == null) {
6429            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6430            return;
6431        }
6432        for (PackageParser.Package opkg : overlays.values()) {
6433            // Not much to do if idmap fails: we already logged the error
6434            // and we certainly don't want to abort installation of pkg simply
6435            // because an overlay didn't fit properly. For these reasons,
6436            // ignore the return value of createIdmapForPackagePairLI.
6437            createIdmapForPackagePairLI(pkg, opkg);
6438        }
6439    }
6440
6441    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6442            PackageParser.Package opkg) {
6443        if (!opkg.mTrustedOverlay) {
6444            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6445                    opkg.baseCodePath + ": overlay not trusted");
6446            return false;
6447        }
6448        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6449        if (overlaySet == null) {
6450            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6451                    opkg.baseCodePath + " but target package has no known overlays");
6452            return false;
6453        }
6454        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6455        // TODO: generate idmap for split APKs
6456        try {
6457            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6458        } catch (InstallerException e) {
6459            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6460                    + opkg.baseCodePath);
6461            return false;
6462        }
6463        PackageParser.Package[] overlayArray =
6464            overlaySet.values().toArray(new PackageParser.Package[0]);
6465        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6466            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6467                return p1.mOverlayPriority - p2.mOverlayPriority;
6468            }
6469        };
6470        Arrays.sort(overlayArray, cmp);
6471
6472        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6473        int i = 0;
6474        for (PackageParser.Package p : overlayArray) {
6475            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6476        }
6477        return true;
6478    }
6479
6480    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6481        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6482        try {
6483            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6484        } finally {
6485            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6486        }
6487    }
6488
6489    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6490        final File[] files = dir.listFiles();
6491        if (ArrayUtils.isEmpty(files)) {
6492            Log.d(TAG, "No files in app dir " + dir);
6493            return;
6494        }
6495
6496        if (DEBUG_PACKAGE_SCANNING) {
6497            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6498                    + " flags=0x" + Integer.toHexString(parseFlags));
6499        }
6500
6501        for (File file : files) {
6502            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6503                    && !PackageInstallerService.isStageName(file.getName());
6504            if (!isPackage) {
6505                // Ignore entries which are not packages
6506                continue;
6507            }
6508            try {
6509                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6510                        scanFlags, currentTime, null);
6511            } catch (PackageManagerException e) {
6512                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6513
6514                // Delete invalid userdata apps
6515                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6516                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6517                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6518                    removeCodePathLI(file);
6519                }
6520            }
6521        }
6522    }
6523
6524    private static File getSettingsProblemFile() {
6525        File dataDir = Environment.getDataDirectory();
6526        File systemDir = new File(dataDir, "system");
6527        File fname = new File(systemDir, "uiderrors.txt");
6528        return fname;
6529    }
6530
6531    static void reportSettingsProblem(int priority, String msg) {
6532        logCriticalInfo(priority, msg);
6533    }
6534
6535    static void logCriticalInfo(int priority, String msg) {
6536        Slog.println(priority, TAG, msg);
6537        EventLogTags.writePmCriticalInfo(msg);
6538        try {
6539            File fname = getSettingsProblemFile();
6540            FileOutputStream out = new FileOutputStream(fname, true);
6541            PrintWriter pw = new FastPrintWriter(out);
6542            SimpleDateFormat formatter = new SimpleDateFormat();
6543            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6544            pw.println(dateString + ": " + msg);
6545            pw.close();
6546            FileUtils.setPermissions(
6547                    fname.toString(),
6548                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6549                    -1, -1);
6550        } catch (java.io.IOException e) {
6551        }
6552    }
6553
6554    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6555            int parseFlags) throws PackageManagerException {
6556        if (ps != null
6557                && ps.codePath.equals(srcFile)
6558                && ps.timeStamp == srcFile.lastModified()
6559                && !isCompatSignatureUpdateNeeded(pkg)
6560                && !isRecoverSignatureUpdateNeeded(pkg)) {
6561            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6562            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6563            ArraySet<PublicKey> signingKs;
6564            synchronized (mPackages) {
6565                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6566            }
6567            if (ps.signatures.mSignatures != null
6568                    && ps.signatures.mSignatures.length != 0
6569                    && signingKs != null) {
6570                // Optimization: reuse the existing cached certificates
6571                // if the package appears to be unchanged.
6572                pkg.mSignatures = ps.signatures.mSignatures;
6573                pkg.mSigningKeys = signingKs;
6574                return;
6575            }
6576
6577            Slog.w(TAG, "PackageSetting for " + ps.name
6578                    + " is missing signatures.  Collecting certs again to recover them.");
6579        } else {
6580            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6581        }
6582
6583        try {
6584            PackageParser.collectCertificates(pkg, parseFlags);
6585        } catch (PackageParserException e) {
6586            throw PackageManagerException.from(e);
6587        }
6588    }
6589
6590    /**
6591     *  Traces a package scan.
6592     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6593     */
6594    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6595            long currentTime, UserHandle user) throws PackageManagerException {
6596        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6597        try {
6598            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6599        } finally {
6600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6601        }
6602    }
6603
6604    /**
6605     *  Scans a package and returns the newly parsed package.
6606     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6607     */
6608    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6609            long currentTime, UserHandle user) throws PackageManagerException {
6610        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6611        parseFlags |= mDefParseFlags;
6612        PackageParser pp = new PackageParser();
6613        pp.setSeparateProcesses(mSeparateProcesses);
6614        pp.setOnlyCoreApps(mOnlyCore);
6615        pp.setDisplayMetrics(mMetrics);
6616
6617        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6618            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6619        }
6620
6621        final PackageParser.Package pkg;
6622        try {
6623            pkg = pp.parsePackage(scanFile, parseFlags);
6624        } catch (PackageParserException e) {
6625            throw PackageManagerException.from(e);
6626        }
6627
6628        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6629    }
6630
6631    /**
6632     *  Scans a package and returns the newly parsed package.
6633     *  @throws PackageManagerException on a parse error.
6634     */
6635    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6636            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6637            throws PackageManagerException {
6638        // If the package has children and this is the first dive in the function
6639        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6640        // packages (parent and children) would be successfully scanned before the
6641        // actual scan since scanning mutates internal state and we want to atomically
6642        // install the package and its children.
6643        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6644            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6645                scanFlags |= SCAN_CHECK_ONLY;
6646            }
6647        } else {
6648            scanFlags &= ~SCAN_CHECK_ONLY;
6649        }
6650
6651        // Scan the parent
6652        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6653                scanFlags, currentTime, user);
6654
6655        // Scan the children
6656        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6657        for (int i = 0; i < childCount; i++) {
6658            PackageParser.Package childPackage = pkg.childPackages.get(i);
6659            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6660                    currentTime, user);
6661        }
6662
6663
6664        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6665            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6666        }
6667
6668        return scannedPkg;
6669    }
6670
6671    /**
6672     *  Scans a package and returns the newly parsed package.
6673     *  @throws PackageManagerException on a parse error.
6674     */
6675    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6676            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6677            throws PackageManagerException {
6678        PackageSetting ps = null;
6679        PackageSetting updatedPkg;
6680        // reader
6681        synchronized (mPackages) {
6682            // Look to see if we already know about this package.
6683            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6684            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6685                // This package has been renamed to its original name.  Let's
6686                // use that.
6687                ps = mSettings.peekPackageLPr(oldName);
6688            }
6689            // If there was no original package, see one for the real package name.
6690            if (ps == null) {
6691                ps = mSettings.peekPackageLPr(pkg.packageName);
6692            }
6693            // Check to see if this package could be hiding/updating a system
6694            // package.  Must look for it either under the original or real
6695            // package name depending on our state.
6696            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6697            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6698
6699            // If this is a package we don't know about on the system partition, we
6700            // may need to remove disabled child packages on the system partition
6701            // or may need to not add child packages if the parent apk is updated
6702            // on the data partition and no longer defines this child package.
6703            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6704                // If this is a parent package for an updated system app and this system
6705                // app got an OTA update which no longer defines some of the child packages
6706                // we have to prune them from the disabled system packages.
6707                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6708                if (disabledPs != null) {
6709                    final int scannedChildCount = (pkg.childPackages != null)
6710                            ? pkg.childPackages.size() : 0;
6711                    final int disabledChildCount = disabledPs.childPackageNames != null
6712                            ? disabledPs.childPackageNames.size() : 0;
6713                    for (int i = 0; i < disabledChildCount; i++) {
6714                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6715                        boolean disabledPackageAvailable = false;
6716                        for (int j = 0; j < scannedChildCount; j++) {
6717                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6718                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6719                                disabledPackageAvailable = true;
6720                                break;
6721                            }
6722                         }
6723                         if (!disabledPackageAvailable) {
6724                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6725                         }
6726                    }
6727                }
6728            }
6729        }
6730
6731        boolean updatedPkgBetter = false;
6732        // First check if this is a system package that may involve an update
6733        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6734            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6735            // it needs to drop FLAG_PRIVILEGED.
6736            if (locationIsPrivileged(scanFile)) {
6737                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6738            } else {
6739                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6740            }
6741
6742            if (ps != null && !ps.codePath.equals(scanFile)) {
6743                // The path has changed from what was last scanned...  check the
6744                // version of the new path against what we have stored to determine
6745                // what to do.
6746                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6747                if (pkg.mVersionCode <= ps.versionCode) {
6748                    // The system package has been updated and the code path does not match
6749                    // Ignore entry. Skip it.
6750                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6751                            + " ignored: updated version " + ps.versionCode
6752                            + " better than this " + pkg.mVersionCode);
6753                    if (!updatedPkg.codePath.equals(scanFile)) {
6754                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6755                                + ps.name + " changing from " + updatedPkg.codePathString
6756                                + " to " + scanFile);
6757                        updatedPkg.codePath = scanFile;
6758                        updatedPkg.codePathString = scanFile.toString();
6759                        updatedPkg.resourcePath = scanFile;
6760                        updatedPkg.resourcePathString = scanFile.toString();
6761                    }
6762                    updatedPkg.pkg = pkg;
6763                    updatedPkg.versionCode = pkg.mVersionCode;
6764
6765                    // Update the disabled system child packages to point to the package too.
6766                    final int childCount = updatedPkg.childPackageNames != null
6767                            ? updatedPkg.childPackageNames.size() : 0;
6768                    for (int i = 0; i < childCount; i++) {
6769                        String childPackageName = updatedPkg.childPackageNames.get(i);
6770                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6771                                childPackageName);
6772                        if (updatedChildPkg != null) {
6773                            updatedChildPkg.pkg = pkg;
6774                            updatedChildPkg.versionCode = pkg.mVersionCode;
6775                        }
6776                    }
6777
6778                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6779                            + scanFile + " ignored: updated version " + ps.versionCode
6780                            + " better than this " + pkg.mVersionCode);
6781                } else {
6782                    // The current app on the system partition is better than
6783                    // what we have updated to on the data partition; switch
6784                    // back to the system partition version.
6785                    // At this point, its safely assumed that package installation for
6786                    // apps in system partition will go through. If not there won't be a working
6787                    // version of the app
6788                    // writer
6789                    synchronized (mPackages) {
6790                        // Just remove the loaded entries from package lists.
6791                        mPackages.remove(ps.name);
6792                    }
6793
6794                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6795                            + " reverting from " + ps.codePathString
6796                            + ": new version " + pkg.mVersionCode
6797                            + " better than installed " + ps.versionCode);
6798
6799                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6800                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6801                    synchronized (mInstallLock) {
6802                        args.cleanUpResourcesLI();
6803                    }
6804                    synchronized (mPackages) {
6805                        mSettings.enableSystemPackageLPw(ps.name);
6806                    }
6807                    updatedPkgBetter = true;
6808                }
6809            }
6810        }
6811
6812        if (updatedPkg != null) {
6813            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6814            // initially
6815            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6816
6817            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6818            // flag set initially
6819            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6820                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6821            }
6822        }
6823
6824        // Verify certificates against what was last scanned
6825        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6826
6827        /*
6828         * A new system app appeared, but we already had a non-system one of the
6829         * same name installed earlier.
6830         */
6831        boolean shouldHideSystemApp = false;
6832        if (updatedPkg == null && ps != null
6833                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6834            /*
6835             * Check to make sure the signatures match first. If they don't,
6836             * wipe the installed application and its data.
6837             */
6838            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6839                    != PackageManager.SIGNATURE_MATCH) {
6840                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6841                        + " signatures don't match existing userdata copy; removing");
6842                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6843                        "scanPackageInternalLI")) {
6844                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6845                }
6846                ps = null;
6847            } else {
6848                /*
6849                 * If the newly-added system app is an older version than the
6850                 * already installed version, hide it. It will be scanned later
6851                 * and re-added like an update.
6852                 */
6853                if (pkg.mVersionCode <= ps.versionCode) {
6854                    shouldHideSystemApp = true;
6855                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6856                            + " but new version " + pkg.mVersionCode + " better than installed "
6857                            + ps.versionCode + "; hiding system");
6858                } else {
6859                    /*
6860                     * The newly found system app is a newer version that the
6861                     * one previously installed. Simply remove the
6862                     * already-installed application and replace it with our own
6863                     * while keeping the application data.
6864                     */
6865                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6866                            + " reverting from " + ps.codePathString + ": new version "
6867                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6868                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6869                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6870                    synchronized (mInstallLock) {
6871                        args.cleanUpResourcesLI();
6872                    }
6873                }
6874            }
6875        }
6876
6877        // The apk is forward locked (not public) if its code and resources
6878        // are kept in different files. (except for app in either system or
6879        // vendor path).
6880        // TODO grab this value from PackageSettings
6881        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6882            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6883                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6884            }
6885        }
6886
6887        // TODO: extend to support forward-locked splits
6888        String resourcePath = null;
6889        String baseResourcePath = null;
6890        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6891            if (ps != null && ps.resourcePathString != null) {
6892                resourcePath = ps.resourcePathString;
6893                baseResourcePath = ps.resourcePathString;
6894            } else {
6895                // Should not happen at all. Just log an error.
6896                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6897            }
6898        } else {
6899            resourcePath = pkg.codePath;
6900            baseResourcePath = pkg.baseCodePath;
6901        }
6902
6903        // Set application objects path explicitly.
6904        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6905        pkg.setApplicationInfoCodePath(pkg.codePath);
6906        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6907        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6908        pkg.setApplicationInfoResourcePath(resourcePath);
6909        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6910        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6911
6912        // Note that we invoke the following method only if we are about to unpack an application
6913        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6914                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6915
6916        /*
6917         * If the system app should be overridden by a previously installed
6918         * data, hide the system app now and let the /data/app scan pick it up
6919         * again.
6920         */
6921        if (shouldHideSystemApp) {
6922            synchronized (mPackages) {
6923                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6924            }
6925        }
6926
6927        return scannedPkg;
6928    }
6929
6930    private static String fixProcessName(String defProcessName,
6931            String processName, int uid) {
6932        if (processName == null) {
6933            return defProcessName;
6934        }
6935        return processName;
6936    }
6937
6938    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6939            throws PackageManagerException {
6940        if (pkgSetting.signatures.mSignatures != null) {
6941            // Already existing package. Make sure signatures match
6942            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6943                    == PackageManager.SIGNATURE_MATCH;
6944            if (!match) {
6945                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6946                        == PackageManager.SIGNATURE_MATCH;
6947            }
6948            if (!match) {
6949                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6950                        == PackageManager.SIGNATURE_MATCH;
6951            }
6952            if (!match) {
6953                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6954                        + pkg.packageName + " signatures do not match the "
6955                        + "previously installed version; ignoring!");
6956            }
6957        }
6958
6959        // Check for shared user signatures
6960        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6961            // Already existing package. Make sure signatures match
6962            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6963                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6964            if (!match) {
6965                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6966                        == PackageManager.SIGNATURE_MATCH;
6967            }
6968            if (!match) {
6969                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6970                        == PackageManager.SIGNATURE_MATCH;
6971            }
6972            if (!match) {
6973                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6974                        "Package " + pkg.packageName
6975                        + " has no signatures that match those in shared user "
6976                        + pkgSetting.sharedUser.name + "; ignoring!");
6977            }
6978        }
6979    }
6980
6981    /**
6982     * Enforces that only the system UID or root's UID can call a method exposed
6983     * via Binder.
6984     *
6985     * @param message used as message if SecurityException is thrown
6986     * @throws SecurityException if the caller is not system or root
6987     */
6988    private static final void enforceSystemOrRoot(String message) {
6989        final int uid = Binder.getCallingUid();
6990        if (uid != Process.SYSTEM_UID && uid != 0) {
6991            throw new SecurityException(message);
6992        }
6993    }
6994
6995    @Override
6996    public void performFstrimIfNeeded() {
6997        enforceSystemOrRoot("Only the system can request fstrim");
6998
6999        // Before everything else, see whether we need to fstrim.
7000        try {
7001            IMountService ms = PackageHelper.getMountService();
7002            if (ms != null) {
7003                final boolean isUpgrade = isUpgrade();
7004                boolean doTrim = isUpgrade;
7005                if (doTrim) {
7006                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7007                } else {
7008                    final long interval = android.provider.Settings.Global.getLong(
7009                            mContext.getContentResolver(),
7010                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7011                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7012                    if (interval > 0) {
7013                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7014                        if (timeSinceLast > interval) {
7015                            doTrim = true;
7016                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7017                                    + "; running immediately");
7018                        }
7019                    }
7020                }
7021                if (doTrim) {
7022                    if (!isFirstBoot()) {
7023                        try {
7024                            ActivityManagerNative.getDefault().showBootMessage(
7025                                    mContext.getResources().getString(
7026                                            R.string.android_upgrading_fstrim), true);
7027                        } catch (RemoteException e) {
7028                        }
7029                    }
7030                    ms.runMaintenance();
7031                }
7032            } else {
7033                Slog.e(TAG, "Mount service unavailable!");
7034            }
7035        } catch (RemoteException e) {
7036            // Can't happen; MountService is local
7037        }
7038    }
7039
7040    @Override
7041    public void updatePackagesIfNeeded() {
7042        enforceSystemOrRoot("Only the system can request package update");
7043
7044        // We need to re-extract after an OTA.
7045        boolean causeUpgrade = isUpgrade();
7046
7047        // First boot or factory reset.
7048        // Note: we also handle devices that are upgrading to N right now as if it is their
7049        //       first boot, as they do not have profile data.
7050        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7051
7052        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7053        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7054
7055        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7056            return;
7057        }
7058
7059        List<PackageParser.Package> pkgs;
7060        synchronized (mPackages) {
7061            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7062        }
7063
7064        UsageStatsManager usageMgr =
7065                (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
7066
7067        int curr = 0;
7068        int total = pkgs.size();
7069        for (PackageParser.Package pkg : pkgs) {
7070            curr++;
7071
7072            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7073                if (DEBUG_DEXOPT) {
7074                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7075                }
7076                continue;
7077            }
7078
7079            if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) {
7080                if (DEBUG_DEXOPT) {
7081                    Log.i(TAG, "Skipping update of of idle app " + pkg.packageName);
7082                }
7083                continue;
7084            }
7085
7086            if (DEBUG_DEXOPT) {
7087                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7088            }
7089
7090            if (!isFirstBoot()) {
7091                try {
7092                    ActivityManagerNative.getDefault().showBootMessage(
7093                            mContext.getResources().getString(R.string.android_upgrading_apk,
7094                                    curr, total), true);
7095                } catch (RemoteException e) {
7096                }
7097            }
7098
7099            performDexOpt(pkg.packageName,
7100                    null /* instructionSet */,
7101                    false /* checkProfiles */,
7102                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7103                    false /* force */);
7104        }
7105    }
7106
7107    @Override
7108    public void notifyPackageUse(String packageName) {
7109        synchronized (mPackages) {
7110            PackageParser.Package p = mPackages.get(packageName);
7111            if (p == null) {
7112                return;
7113            }
7114            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7115        }
7116    }
7117
7118    // TODO: this is not used nor needed. Delete it.
7119    @Override
7120    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7121        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7122                getFullCompilerFilter(), false /* force */);
7123    }
7124
7125    @Override
7126    public boolean performDexOpt(String packageName, String instructionSet,
7127            boolean checkProfiles, int compileReason, boolean force) {
7128        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7129                getCompilerFilterForReason(compileReason), force);
7130    }
7131
7132    @Override
7133    public boolean performDexOptMode(String packageName, String instructionSet,
7134            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7135        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7136                targetCompilerFilter, force);
7137    }
7138
7139    private boolean performDexOptTraced(String packageName, String instructionSet,
7140                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7141        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7142        try {
7143            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7144                    targetCompilerFilter, force);
7145        } finally {
7146            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7147        }
7148    }
7149
7150    private boolean performDexOptInternal(String packageName, String instructionSet,
7151                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7152        PackageParser.Package p;
7153        final String targetInstructionSet;
7154        synchronized (mPackages) {
7155            p = mPackages.get(packageName);
7156            if (p == null) {
7157                return false;
7158            }
7159            mPackageUsage.write(false);
7160
7161            targetInstructionSet = instructionSet != null ? instructionSet :
7162                    getPrimaryInstructionSet(p.applicationInfo);
7163        }
7164        long callingId = Binder.clearCallingIdentity();
7165        try {
7166            synchronized (mInstallLock) {
7167                final String[] instructionSets = new String[] { targetInstructionSet };
7168                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7169                        checkProfiles, targetCompilerFilter, force);
7170                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7171            }
7172        } finally {
7173            Binder.restoreCallingIdentity(callingId);
7174        }
7175    }
7176
7177    public ArraySet<String> getOptimizablePackages() {
7178        ArraySet<String> pkgs = new ArraySet<String>();
7179        synchronized (mPackages) {
7180            for (PackageParser.Package p : mPackages.values()) {
7181                if (PackageDexOptimizer.canOptimizePackage(p)) {
7182                    pkgs.add(p.packageName);
7183                }
7184            }
7185        }
7186        return pkgs;
7187    }
7188
7189    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7190            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7191            boolean force) {
7192        // Select the dex optimizer based on the force parameter.
7193        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7194        //       allocate an object here.
7195        PackageDexOptimizer pdo = force
7196                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7197                : mPackageDexOptimizer;
7198
7199        // Optimize all dependencies first. Note: we ignore the return value and march on
7200        // on errors.
7201        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7202        if (!deps.isEmpty()) {
7203            for (PackageParser.Package depPackage : deps) {
7204                // TODO: Analyze and investigate if we (should) profile libraries.
7205                // Currently this will do a full compilation of the library by default.
7206                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7207                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7208            }
7209        }
7210
7211        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7212    }
7213
7214    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7215        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7216            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7217            Set<String> collectedNames = new HashSet<>();
7218            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7219
7220            retValue.remove(p);
7221
7222            return retValue;
7223        } else {
7224            return Collections.emptyList();
7225        }
7226    }
7227
7228    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7229            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7230        if (!collectedNames.contains(p.packageName)) {
7231            collectedNames.add(p.packageName);
7232            collected.add(p);
7233
7234            if (p.usesLibraries != null) {
7235                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7236            }
7237            if (p.usesOptionalLibraries != null) {
7238                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7239                        collectedNames);
7240            }
7241        }
7242    }
7243
7244    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7245            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7246        for (String libName : libs) {
7247            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7248            if (libPkg != null) {
7249                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7250            }
7251        }
7252    }
7253
7254    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7255        synchronized (mPackages) {
7256            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7257            if (lib != null && lib.apk != null) {
7258                return mPackages.get(lib.apk);
7259            }
7260        }
7261        return null;
7262    }
7263
7264    public void shutdown() {
7265        mPackageUsage.write(true);
7266    }
7267
7268    @Override
7269    public void forceDexOpt(String packageName) {
7270        enforceSystemOrRoot("forceDexOpt");
7271
7272        PackageParser.Package pkg;
7273        synchronized (mPackages) {
7274            pkg = mPackages.get(packageName);
7275            if (pkg == null) {
7276                throw new IllegalArgumentException("Unknown package: " + packageName);
7277            }
7278        }
7279
7280        synchronized (mInstallLock) {
7281            final String[] instructionSets = new String[] {
7282                    getPrimaryInstructionSet(pkg.applicationInfo) };
7283
7284            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7285
7286            // Whoever is calling forceDexOpt wants a fully compiled package.
7287            // Don't use profiles since that may cause compilation to be skipped.
7288            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7289                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7290                    true /* force */);
7291
7292            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7293            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7294                throw new IllegalStateException("Failed to dexopt: " + res);
7295            }
7296        }
7297    }
7298
7299    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7300        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7301            Slog.w(TAG, "Unable to update from " + oldPkg.name
7302                    + " to " + newPkg.packageName
7303                    + ": old package not in system partition");
7304            return false;
7305        } else if (mPackages.get(oldPkg.name) != null) {
7306            Slog.w(TAG, "Unable to update from " + oldPkg.name
7307                    + " to " + newPkg.packageName
7308                    + ": old package still exists");
7309            return false;
7310        }
7311        return true;
7312    }
7313
7314    void removeCodePathLI(File codePath) {
7315        if (codePath.isDirectory()) {
7316            try {
7317                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7318            } catch (InstallerException e) {
7319                Slog.w(TAG, "Failed to remove code path", e);
7320            }
7321        } else {
7322            codePath.delete();
7323        }
7324    }
7325
7326    private int[] resolveUserIds(int userId) {
7327        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7328    }
7329
7330    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7331        if (pkg == null) {
7332            Slog.wtf(TAG, "Package was null!", new Throwable());
7333            return;
7334        }
7335        clearAppDataLeafLIF(pkg, userId, flags);
7336        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7337        for (int i = 0; i < childCount; i++) {
7338            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7339        }
7340    }
7341
7342    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7343        final PackageSetting ps;
7344        synchronized (mPackages) {
7345            ps = mSettings.mPackages.get(pkg.packageName);
7346        }
7347        for (int realUserId : resolveUserIds(userId)) {
7348            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7349            try {
7350                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7351                        ceDataInode);
7352            } catch (InstallerException e) {
7353                Slog.w(TAG, String.valueOf(e));
7354            }
7355        }
7356    }
7357
7358    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7359        if (pkg == null) {
7360            Slog.wtf(TAG, "Package was null!", new Throwable());
7361            return;
7362        }
7363        destroyAppDataLeafLIF(pkg, userId, flags);
7364        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7365        for (int i = 0; i < childCount; i++) {
7366            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7367        }
7368    }
7369
7370    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7371        final PackageSetting ps;
7372        synchronized (mPackages) {
7373            ps = mSettings.mPackages.get(pkg.packageName);
7374        }
7375        for (int realUserId : resolveUserIds(userId)) {
7376            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7377            try {
7378                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7379                        ceDataInode);
7380            } catch (InstallerException e) {
7381                Slog.w(TAG, String.valueOf(e));
7382            }
7383        }
7384    }
7385
7386    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7387        if (pkg == null) {
7388            Slog.wtf(TAG, "Package was null!", new Throwable());
7389            return;
7390        }
7391        destroyAppProfilesLeafLIF(pkg);
7392        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7393        for (int i = 0; i < childCount; i++) {
7394            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7395        }
7396    }
7397
7398    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7399        try {
7400            mInstaller.destroyAppProfiles(pkg.packageName);
7401        } catch (InstallerException e) {
7402            Slog.w(TAG, String.valueOf(e));
7403        }
7404    }
7405
7406    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7407        if (pkg == null) {
7408            Slog.wtf(TAG, "Package was null!", new Throwable());
7409            return;
7410        }
7411        clearAppProfilesLeafLIF(pkg);
7412        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7413        for (int i = 0; i < childCount; i++) {
7414            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7415        }
7416    }
7417
7418    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7419        try {
7420            mInstaller.clearAppProfiles(pkg.packageName);
7421        } catch (InstallerException e) {
7422            Slog.w(TAG, String.valueOf(e));
7423        }
7424    }
7425
7426    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7427            long lastUpdateTime) {
7428        // Set parent install/update time
7429        PackageSetting ps = (PackageSetting) pkg.mExtras;
7430        if (ps != null) {
7431            ps.firstInstallTime = firstInstallTime;
7432            ps.lastUpdateTime = lastUpdateTime;
7433        }
7434        // Set children install/update time
7435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7436        for (int i = 0; i < childCount; i++) {
7437            PackageParser.Package childPkg = pkg.childPackages.get(i);
7438            ps = (PackageSetting) childPkg.mExtras;
7439            if (ps != null) {
7440                ps.firstInstallTime = firstInstallTime;
7441                ps.lastUpdateTime = lastUpdateTime;
7442            }
7443        }
7444    }
7445
7446    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7447            PackageParser.Package changingLib) {
7448        if (file.path != null) {
7449            usesLibraryFiles.add(file.path);
7450            return;
7451        }
7452        PackageParser.Package p = mPackages.get(file.apk);
7453        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7454            // If we are doing this while in the middle of updating a library apk,
7455            // then we need to make sure to use that new apk for determining the
7456            // dependencies here.  (We haven't yet finished committing the new apk
7457            // to the package manager state.)
7458            if (p == null || p.packageName.equals(changingLib.packageName)) {
7459                p = changingLib;
7460            }
7461        }
7462        if (p != null) {
7463            usesLibraryFiles.addAll(p.getAllCodePaths());
7464        }
7465    }
7466
7467    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7468            PackageParser.Package changingLib) throws PackageManagerException {
7469        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7470            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7471            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7472            for (int i=0; i<N; i++) {
7473                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7474                if (file == null) {
7475                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7476                            "Package " + pkg.packageName + " requires unavailable shared library "
7477                            + pkg.usesLibraries.get(i) + "; failing!");
7478                }
7479                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7480            }
7481            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7482            for (int i=0; i<N; i++) {
7483                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7484                if (file == null) {
7485                    Slog.w(TAG, "Package " + pkg.packageName
7486                            + " desires unavailable shared library "
7487                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7488                } else {
7489                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7490                }
7491            }
7492            N = usesLibraryFiles.size();
7493            if (N > 0) {
7494                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7495            } else {
7496                pkg.usesLibraryFiles = null;
7497            }
7498        }
7499    }
7500
7501    private static boolean hasString(List<String> list, List<String> which) {
7502        if (list == null) {
7503            return false;
7504        }
7505        for (int i=list.size()-1; i>=0; i--) {
7506            for (int j=which.size()-1; j>=0; j--) {
7507                if (which.get(j).equals(list.get(i))) {
7508                    return true;
7509                }
7510            }
7511        }
7512        return false;
7513    }
7514
7515    private void updateAllSharedLibrariesLPw() {
7516        for (PackageParser.Package pkg : mPackages.values()) {
7517            try {
7518                updateSharedLibrariesLPw(pkg, null);
7519            } catch (PackageManagerException e) {
7520                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7521            }
7522        }
7523    }
7524
7525    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7526            PackageParser.Package changingPkg) {
7527        ArrayList<PackageParser.Package> res = null;
7528        for (PackageParser.Package pkg : mPackages.values()) {
7529            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7530                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7531                if (res == null) {
7532                    res = new ArrayList<PackageParser.Package>();
7533                }
7534                res.add(pkg);
7535                try {
7536                    updateSharedLibrariesLPw(pkg, changingPkg);
7537                } catch (PackageManagerException e) {
7538                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7539                }
7540            }
7541        }
7542        return res;
7543    }
7544
7545    /**
7546     * Derive the value of the {@code cpuAbiOverride} based on the provided
7547     * value and an optional stored value from the package settings.
7548     */
7549    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7550        String cpuAbiOverride = null;
7551
7552        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7553            cpuAbiOverride = null;
7554        } else if (abiOverride != null) {
7555            cpuAbiOverride = abiOverride;
7556        } else if (settings != null) {
7557            cpuAbiOverride = settings.cpuAbiOverrideString;
7558        }
7559
7560        return cpuAbiOverride;
7561    }
7562
7563    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7564            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7565        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7566        // If the package has children and this is the first dive in the function
7567        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7568        // whether all packages (parent and children) would be successfully scanned
7569        // before the actual scan since scanning mutates internal state and we want
7570        // to atomically install the package and its children.
7571        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7572            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7573                scanFlags |= SCAN_CHECK_ONLY;
7574            }
7575        } else {
7576            scanFlags &= ~SCAN_CHECK_ONLY;
7577        }
7578
7579        final PackageParser.Package scannedPkg;
7580        try {
7581            // Scan the parent
7582            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7583            // Scan the children
7584            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7585            for (int i = 0; i < childCount; i++) {
7586                PackageParser.Package childPkg = pkg.childPackages.get(i);
7587                scanPackageLI(childPkg, parseFlags,
7588                        scanFlags, currentTime, user);
7589            }
7590        } finally {
7591            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7592        }
7593
7594        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7595            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7596        }
7597
7598        return scannedPkg;
7599    }
7600
7601    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7602            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7603        boolean success = false;
7604        try {
7605            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7606                    currentTime, user);
7607            success = true;
7608            return res;
7609        } finally {
7610            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7611                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7612                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7613                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7614                destroyAppProfilesLIF(pkg);
7615            }
7616        }
7617    }
7618
7619    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7620            int scanFlags, long currentTime, UserHandle user)
7621            throws PackageManagerException {
7622        final File scanFile = new File(pkg.codePath);
7623        if (pkg.applicationInfo.getCodePath() == null ||
7624                pkg.applicationInfo.getResourcePath() == null) {
7625            // Bail out. The resource and code paths haven't been set.
7626            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7627                    "Code and resource paths haven't been set correctly");
7628        }
7629
7630        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7631            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7632        } else {
7633            // Only allow system apps to be flagged as core apps.
7634            pkg.coreApp = false;
7635        }
7636
7637        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7638            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7639        }
7640
7641        if (mCustomResolverComponentName != null &&
7642                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7643            setUpCustomResolverActivity(pkg);
7644        }
7645
7646        if (pkg.packageName.equals("android")) {
7647            synchronized (mPackages) {
7648                if (mAndroidApplication != null) {
7649                    Slog.w(TAG, "*************************************************");
7650                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7651                    Slog.w(TAG, " file=" + scanFile);
7652                    Slog.w(TAG, "*************************************************");
7653                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7654                            "Core android package being redefined.  Skipping.");
7655                }
7656
7657                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7658                    // Set up information for our fall-back user intent resolution activity.
7659                    mPlatformPackage = pkg;
7660                    pkg.mVersionCode = mSdkVersion;
7661                    mAndroidApplication = pkg.applicationInfo;
7662
7663                    if (!mResolverReplaced) {
7664                        mResolveActivity.applicationInfo = mAndroidApplication;
7665                        mResolveActivity.name = ResolverActivity.class.getName();
7666                        mResolveActivity.packageName = mAndroidApplication.packageName;
7667                        mResolveActivity.processName = "system:ui";
7668                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7669                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7670                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7671                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7672                        mResolveActivity.exported = true;
7673                        mResolveActivity.enabled = true;
7674                        mResolveInfo.activityInfo = mResolveActivity;
7675                        mResolveInfo.priority = 0;
7676                        mResolveInfo.preferredOrder = 0;
7677                        mResolveInfo.match = 0;
7678                        mResolveComponentName = new ComponentName(
7679                                mAndroidApplication.packageName, mResolveActivity.name);
7680                    }
7681                }
7682            }
7683        }
7684
7685        if (DEBUG_PACKAGE_SCANNING) {
7686            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7687                Log.d(TAG, "Scanning package " + pkg.packageName);
7688        }
7689
7690        synchronized (mPackages) {
7691            if (mPackages.containsKey(pkg.packageName)
7692                    || mSharedLibraries.containsKey(pkg.packageName)) {
7693                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7694                        "Application package " + pkg.packageName
7695                                + " already installed.  Skipping duplicate.");
7696            }
7697
7698            // If we're only installing presumed-existing packages, require that the
7699            // scanned APK is both already known and at the path previously established
7700            // for it.  Previously unknown packages we pick up normally, but if we have an
7701            // a priori expectation about this package's install presence, enforce it.
7702            // With a singular exception for new system packages. When an OTA contains
7703            // a new system package, we allow the codepath to change from a system location
7704            // to the user-installed location. If we don't allow this change, any newer,
7705            // user-installed version of the application will be ignored.
7706            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7707                if (mExpectingBetter.containsKey(pkg.packageName)) {
7708                    logCriticalInfo(Log.WARN,
7709                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7710                } else {
7711                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7712                    if (known != null) {
7713                        if (DEBUG_PACKAGE_SCANNING) {
7714                            Log.d(TAG, "Examining " + pkg.codePath
7715                                    + " and requiring known paths " + known.codePathString
7716                                    + " & " + known.resourcePathString);
7717                        }
7718                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7719                                || !pkg.applicationInfo.getResourcePath().equals(
7720                                known.resourcePathString)) {
7721                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7722                                    "Application package " + pkg.packageName
7723                                            + " found at " + pkg.applicationInfo.getCodePath()
7724                                            + " but expected at " + known.codePathString
7725                                            + "; ignoring.");
7726                        }
7727                    }
7728                }
7729            }
7730        }
7731
7732        // Initialize package source and resource directories
7733        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7734        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7735
7736        SharedUserSetting suid = null;
7737        PackageSetting pkgSetting = null;
7738
7739        if (!isSystemApp(pkg)) {
7740            // Only system apps can use these features.
7741            pkg.mOriginalPackages = null;
7742            pkg.mRealPackage = null;
7743            pkg.mAdoptPermissions = null;
7744        }
7745
7746        // Getting the package setting may have a side-effect, so if we
7747        // are only checking if scan would succeed, stash a copy of the
7748        // old setting to restore at the end.
7749        PackageSetting nonMutatedPs = null;
7750
7751        // writer
7752        synchronized (mPackages) {
7753            if (pkg.mSharedUserId != null) {
7754                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7755                if (suid == null) {
7756                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7757                            "Creating application package " + pkg.packageName
7758                            + " for shared user failed");
7759                }
7760                if (DEBUG_PACKAGE_SCANNING) {
7761                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7762                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7763                                + "): packages=" + suid.packages);
7764                }
7765            }
7766
7767            // Check if we are renaming from an original package name.
7768            PackageSetting origPackage = null;
7769            String realName = null;
7770            if (pkg.mOriginalPackages != null) {
7771                // This package may need to be renamed to a previously
7772                // installed name.  Let's check on that...
7773                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7774                if (pkg.mOriginalPackages.contains(renamed)) {
7775                    // This package had originally been installed as the
7776                    // original name, and we have already taken care of
7777                    // transitioning to the new one.  Just update the new
7778                    // one to continue using the old name.
7779                    realName = pkg.mRealPackage;
7780                    if (!pkg.packageName.equals(renamed)) {
7781                        // Callers into this function may have already taken
7782                        // care of renaming the package; only do it here if
7783                        // it is not already done.
7784                        pkg.setPackageName(renamed);
7785                    }
7786
7787                } else {
7788                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7789                        if ((origPackage = mSettings.peekPackageLPr(
7790                                pkg.mOriginalPackages.get(i))) != null) {
7791                            // We do have the package already installed under its
7792                            // original name...  should we use it?
7793                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7794                                // New package is not compatible with original.
7795                                origPackage = null;
7796                                continue;
7797                            } else if (origPackage.sharedUser != null) {
7798                                // Make sure uid is compatible between packages.
7799                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7800                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7801                                            + " to " + pkg.packageName + ": old uid "
7802                                            + origPackage.sharedUser.name
7803                                            + " differs from " + pkg.mSharedUserId);
7804                                    origPackage = null;
7805                                    continue;
7806                                }
7807                            } else {
7808                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7809                                        + pkg.packageName + " to old name " + origPackage.name);
7810                            }
7811                            break;
7812                        }
7813                    }
7814                }
7815            }
7816
7817            if (mTransferedPackages.contains(pkg.packageName)) {
7818                Slog.w(TAG, "Package " + pkg.packageName
7819                        + " was transferred to another, but its .apk remains");
7820            }
7821
7822            // See comments in nonMutatedPs declaration
7823            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7824                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7825                if (foundPs != null) {
7826                    nonMutatedPs = new PackageSetting(foundPs);
7827                }
7828            }
7829
7830            // Just create the setting, don't add it yet. For already existing packages
7831            // the PkgSetting exists already and doesn't have to be created.
7832            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7833                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7834                    pkg.applicationInfo.primaryCpuAbi,
7835                    pkg.applicationInfo.secondaryCpuAbi,
7836                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7837                    user, false);
7838            if (pkgSetting == null) {
7839                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7840                        "Creating application package " + pkg.packageName + " failed");
7841            }
7842
7843            if (pkgSetting.origPackage != null) {
7844                // If we are first transitioning from an original package,
7845                // fix up the new package's name now.  We need to do this after
7846                // looking up the package under its new name, so getPackageLP
7847                // can take care of fiddling things correctly.
7848                pkg.setPackageName(origPackage.name);
7849
7850                // File a report about this.
7851                String msg = "New package " + pkgSetting.realName
7852                        + " renamed to replace old package " + pkgSetting.name;
7853                reportSettingsProblem(Log.WARN, msg);
7854
7855                // Make a note of it.
7856                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7857                    mTransferedPackages.add(origPackage.name);
7858                }
7859
7860                // No longer need to retain this.
7861                pkgSetting.origPackage = null;
7862            }
7863
7864            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7865                // Make a note of it.
7866                mTransferedPackages.add(pkg.packageName);
7867            }
7868
7869            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7870                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7871            }
7872
7873            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7874                // Check all shared libraries and map to their actual file path.
7875                // We only do this here for apps not on a system dir, because those
7876                // are the only ones that can fail an install due to this.  We
7877                // will take care of the system apps by updating all of their
7878                // library paths after the scan is done.
7879                updateSharedLibrariesLPw(pkg, null);
7880            }
7881
7882            if (mFoundPolicyFile) {
7883                SELinuxMMAC.assignSeinfoValue(pkg);
7884            }
7885
7886            pkg.applicationInfo.uid = pkgSetting.appId;
7887            pkg.mExtras = pkgSetting;
7888            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7889                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7890                    // We just determined the app is signed correctly, so bring
7891                    // over the latest parsed certs.
7892                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7893                } else {
7894                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7895                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7896                                "Package " + pkg.packageName + " upgrade keys do not match the "
7897                                + "previously installed version");
7898                    } else {
7899                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7900                        String msg = "System package " + pkg.packageName
7901                            + " signature changed; retaining data.";
7902                        reportSettingsProblem(Log.WARN, msg);
7903                    }
7904                }
7905            } else {
7906                try {
7907                    verifySignaturesLP(pkgSetting, pkg);
7908                    // We just determined the app is signed correctly, so bring
7909                    // over the latest parsed certs.
7910                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7911                } catch (PackageManagerException e) {
7912                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7913                        throw e;
7914                    }
7915                    // The signature has changed, but this package is in the system
7916                    // image...  let's recover!
7917                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7918                    // However...  if this package is part of a shared user, but it
7919                    // doesn't match the signature of the shared user, let's fail.
7920                    // What this means is that you can't change the signatures
7921                    // associated with an overall shared user, which doesn't seem all
7922                    // that unreasonable.
7923                    if (pkgSetting.sharedUser != null) {
7924                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7925                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7926                            throw new PackageManagerException(
7927                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7928                                            "Signature mismatch for shared user: "
7929                                            + pkgSetting.sharedUser);
7930                        }
7931                    }
7932                    // File a report about this.
7933                    String msg = "System package " + pkg.packageName
7934                        + " signature changed; retaining data.";
7935                    reportSettingsProblem(Log.WARN, msg);
7936                }
7937            }
7938            // Verify that this new package doesn't have any content providers
7939            // that conflict with existing packages.  Only do this if the
7940            // package isn't already installed, since we don't want to break
7941            // things that are installed.
7942            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7943                final int N = pkg.providers.size();
7944                int i;
7945                for (i=0; i<N; i++) {
7946                    PackageParser.Provider p = pkg.providers.get(i);
7947                    if (p.info.authority != null) {
7948                        String names[] = p.info.authority.split(";");
7949                        for (int j = 0; j < names.length; j++) {
7950                            if (mProvidersByAuthority.containsKey(names[j])) {
7951                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7952                                final String otherPackageName =
7953                                        ((other != null && other.getComponentName() != null) ?
7954                                                other.getComponentName().getPackageName() : "?");
7955                                throw new PackageManagerException(
7956                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7957                                                "Can't install because provider name " + names[j]
7958                                                + " (in package " + pkg.applicationInfo.packageName
7959                                                + ") is already used by " + otherPackageName);
7960                            }
7961                        }
7962                    }
7963                }
7964            }
7965
7966            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7967                // This package wants to adopt ownership of permissions from
7968                // another package.
7969                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7970                    final String origName = pkg.mAdoptPermissions.get(i);
7971                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7972                    if (orig != null) {
7973                        if (verifyPackageUpdateLPr(orig, pkg)) {
7974                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7975                                    + pkg.packageName);
7976                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7977                        }
7978                    }
7979                }
7980            }
7981        }
7982
7983        final String pkgName = pkg.packageName;
7984
7985        final long scanFileTime = scanFile.lastModified();
7986        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7987        pkg.applicationInfo.processName = fixProcessName(
7988                pkg.applicationInfo.packageName,
7989                pkg.applicationInfo.processName,
7990                pkg.applicationInfo.uid);
7991
7992        if (pkg != mPlatformPackage) {
7993            // Get all of our default paths setup
7994            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7995        }
7996
7997        final String path = scanFile.getPath();
7998        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7999
8000        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8001            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8002
8003            // Some system apps still use directory structure for native libraries
8004            // in which case we might end up not detecting abi solely based on apk
8005            // structure. Try to detect abi based on directory structure.
8006            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8007                    pkg.applicationInfo.primaryCpuAbi == null) {
8008                setBundledAppAbisAndRoots(pkg, pkgSetting);
8009                setNativeLibraryPaths(pkg);
8010            }
8011
8012        } else {
8013            if ((scanFlags & SCAN_MOVE) != 0) {
8014                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8015                // but we already have this packages package info in the PackageSetting. We just
8016                // use that and derive the native library path based on the new codepath.
8017                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8018                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8019            }
8020
8021            // Set native library paths again. For moves, the path will be updated based on the
8022            // ABIs we've determined above. For non-moves, the path will be updated based on the
8023            // ABIs we determined during compilation, but the path will depend on the final
8024            // package path (after the rename away from the stage path).
8025            setNativeLibraryPaths(pkg);
8026        }
8027
8028        // This is a special case for the "system" package, where the ABI is
8029        // dictated by the zygote configuration (and init.rc). We should keep track
8030        // of this ABI so that we can deal with "normal" applications that run under
8031        // the same UID correctly.
8032        if (mPlatformPackage == pkg) {
8033            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8034                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8035        }
8036
8037        // If there's a mismatch between the abi-override in the package setting
8038        // and the abiOverride specified for the install. Warn about this because we
8039        // would've already compiled the app without taking the package setting into
8040        // account.
8041        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8042            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8043                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8044                        " for package " + pkg.packageName);
8045            }
8046        }
8047
8048        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8049        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8050        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8051
8052        // Copy the derived override back to the parsed package, so that we can
8053        // update the package settings accordingly.
8054        pkg.cpuAbiOverride = cpuAbiOverride;
8055
8056        if (DEBUG_ABI_SELECTION) {
8057            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8058                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8059                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8060        }
8061
8062        // Push the derived path down into PackageSettings so we know what to
8063        // clean up at uninstall time.
8064        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8065
8066        if (DEBUG_ABI_SELECTION) {
8067            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8068                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8069                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8070        }
8071
8072        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8073            // We don't do this here during boot because we can do it all
8074            // at once after scanning all existing packages.
8075            //
8076            // We also do this *before* we perform dexopt on this package, so that
8077            // we can avoid redundant dexopts, and also to make sure we've got the
8078            // code and package path correct.
8079            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8080                    pkg, true /* boot complete */);
8081        }
8082
8083        if (mFactoryTest && pkg.requestedPermissions.contains(
8084                android.Manifest.permission.FACTORY_TEST)) {
8085            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8086        }
8087
8088        ArrayList<PackageParser.Package> clientLibPkgs = null;
8089
8090        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8091            if (nonMutatedPs != null) {
8092                synchronized (mPackages) {
8093                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8094                }
8095            }
8096            return pkg;
8097        }
8098
8099        // Only privileged apps and updated privileged apps can add child packages.
8100        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8101            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
8102                throw new PackageManagerException("Only privileged apps and updated "
8103                        + "privileged apps can add child packages. Ignoring package "
8104                        + pkg.packageName);
8105            }
8106            final int childCount = pkg.childPackages.size();
8107            for (int i = 0; i < childCount; i++) {
8108                PackageParser.Package childPkg = pkg.childPackages.get(i);
8109                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8110                        childPkg.packageName)) {
8111                    throw new PackageManagerException("Cannot override a child package of "
8112                            + "another disabled system app. Ignoring package " + pkg.packageName);
8113                }
8114            }
8115        }
8116
8117        // writer
8118        synchronized (mPackages) {
8119            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8120                // Only system apps can add new shared libraries.
8121                if (pkg.libraryNames != null) {
8122                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8123                        String name = pkg.libraryNames.get(i);
8124                        boolean allowed = false;
8125                        if (pkg.isUpdatedSystemApp()) {
8126                            // New library entries can only be added through the
8127                            // system image.  This is important to get rid of a lot
8128                            // of nasty edge cases: for example if we allowed a non-
8129                            // system update of the app to add a library, then uninstalling
8130                            // the update would make the library go away, and assumptions
8131                            // we made such as through app install filtering would now
8132                            // have allowed apps on the device which aren't compatible
8133                            // with it.  Better to just have the restriction here, be
8134                            // conservative, and create many fewer cases that can negatively
8135                            // impact the user experience.
8136                            final PackageSetting sysPs = mSettings
8137                                    .getDisabledSystemPkgLPr(pkg.packageName);
8138                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8139                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8140                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8141                                        allowed = true;
8142                                        break;
8143                                    }
8144                                }
8145                            }
8146                        } else {
8147                            allowed = true;
8148                        }
8149                        if (allowed) {
8150                            if (!mSharedLibraries.containsKey(name)) {
8151                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8152                            } else if (!name.equals(pkg.packageName)) {
8153                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8154                                        + name + " already exists; skipping");
8155                            }
8156                        } else {
8157                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8158                                    + name + " that is not declared on system image; skipping");
8159                        }
8160                    }
8161                    if ((scanFlags & SCAN_BOOTING) == 0) {
8162                        // If we are not booting, we need to update any applications
8163                        // that are clients of our shared library.  If we are booting,
8164                        // this will all be done once the scan is complete.
8165                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8166                    }
8167                }
8168            }
8169        }
8170
8171        if ((scanFlags & SCAN_BOOTING) != 0) {
8172            // No apps can run during boot scan, so they don't need to be frozen
8173        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8174            // Caller asked to not kill app, so it's probably not frozen
8175        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8176            // Caller asked us to ignore frozen check for some reason; they
8177            // probably didn't know the package name
8178        } else {
8179            // We're doing major surgery on this package, so it better be frozen
8180            // right now to keep it from launching
8181            checkPackageFrozen(pkgName);
8182        }
8183
8184        // Also need to kill any apps that are dependent on the library.
8185        if (clientLibPkgs != null) {
8186            for (int i=0; i<clientLibPkgs.size(); i++) {
8187                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8188                killApplication(clientPkg.applicationInfo.packageName,
8189                        clientPkg.applicationInfo.uid, "update lib");
8190            }
8191        }
8192
8193        // Make sure we're not adding any bogus keyset info
8194        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8195        ksms.assertScannedPackageValid(pkg);
8196
8197        // writer
8198        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8199
8200        boolean createIdmapFailed = false;
8201        synchronized (mPackages) {
8202            // We don't expect installation to fail beyond this point
8203
8204            // Add the new setting to mSettings
8205            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8206            // Add the new setting to mPackages
8207            mPackages.put(pkg.applicationInfo.packageName, pkg);
8208            // Make sure we don't accidentally delete its data.
8209            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8210            while (iter.hasNext()) {
8211                PackageCleanItem item = iter.next();
8212                if (pkgName.equals(item.packageName)) {
8213                    iter.remove();
8214                }
8215            }
8216
8217            // Take care of first install / last update times.
8218            if (currentTime != 0) {
8219                if (pkgSetting.firstInstallTime == 0) {
8220                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8221                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8222                    pkgSetting.lastUpdateTime = currentTime;
8223                }
8224            } else if (pkgSetting.firstInstallTime == 0) {
8225                // We need *something*.  Take time time stamp of the file.
8226                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8227            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8228                if (scanFileTime != pkgSetting.timeStamp) {
8229                    // A package on the system image has changed; consider this
8230                    // to be an update.
8231                    pkgSetting.lastUpdateTime = scanFileTime;
8232                }
8233            }
8234
8235            // Add the package's KeySets to the global KeySetManagerService
8236            ksms.addScannedPackageLPw(pkg);
8237
8238            int N = pkg.providers.size();
8239            StringBuilder r = null;
8240            int i;
8241            for (i=0; i<N; i++) {
8242                PackageParser.Provider p = pkg.providers.get(i);
8243                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8244                        p.info.processName, pkg.applicationInfo.uid);
8245                mProviders.addProvider(p);
8246                p.syncable = p.info.isSyncable;
8247                if (p.info.authority != null) {
8248                    String names[] = p.info.authority.split(";");
8249                    p.info.authority = null;
8250                    for (int j = 0; j < names.length; j++) {
8251                        if (j == 1 && p.syncable) {
8252                            // We only want the first authority for a provider to possibly be
8253                            // syncable, so if we already added this provider using a different
8254                            // authority clear the syncable flag. We copy the provider before
8255                            // changing it because the mProviders object contains a reference
8256                            // to a provider that we don't want to change.
8257                            // Only do this for the second authority since the resulting provider
8258                            // object can be the same for all future authorities for this provider.
8259                            p = new PackageParser.Provider(p);
8260                            p.syncable = false;
8261                        }
8262                        if (!mProvidersByAuthority.containsKey(names[j])) {
8263                            mProvidersByAuthority.put(names[j], p);
8264                            if (p.info.authority == null) {
8265                                p.info.authority = names[j];
8266                            } else {
8267                                p.info.authority = p.info.authority + ";" + names[j];
8268                            }
8269                            if (DEBUG_PACKAGE_SCANNING) {
8270                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8271                                    Log.d(TAG, "Registered content provider: " + names[j]
8272                                            + ", className = " + p.info.name + ", isSyncable = "
8273                                            + p.info.isSyncable);
8274                            }
8275                        } else {
8276                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8277                            Slog.w(TAG, "Skipping provider name " + names[j] +
8278                                    " (in package " + pkg.applicationInfo.packageName +
8279                                    "): name already used by "
8280                                    + ((other != null && other.getComponentName() != null)
8281                                            ? other.getComponentName().getPackageName() : "?"));
8282                        }
8283                    }
8284                }
8285                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8286                    if (r == null) {
8287                        r = new StringBuilder(256);
8288                    } else {
8289                        r.append(' ');
8290                    }
8291                    r.append(p.info.name);
8292                }
8293            }
8294            if (r != null) {
8295                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8296            }
8297
8298            N = pkg.services.size();
8299            r = null;
8300            for (i=0; i<N; i++) {
8301                PackageParser.Service s = pkg.services.get(i);
8302                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8303                        s.info.processName, pkg.applicationInfo.uid);
8304                mServices.addService(s);
8305                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8306                    if (r == null) {
8307                        r = new StringBuilder(256);
8308                    } else {
8309                        r.append(' ');
8310                    }
8311                    r.append(s.info.name);
8312                }
8313            }
8314            if (r != null) {
8315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8316            }
8317
8318            N = pkg.receivers.size();
8319            r = null;
8320            for (i=0; i<N; i++) {
8321                PackageParser.Activity a = pkg.receivers.get(i);
8322                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8323                        a.info.processName, pkg.applicationInfo.uid);
8324                mReceivers.addActivity(a, "receiver");
8325                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8326                    if (r == null) {
8327                        r = new StringBuilder(256);
8328                    } else {
8329                        r.append(' ');
8330                    }
8331                    r.append(a.info.name);
8332                }
8333            }
8334            if (r != null) {
8335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8336            }
8337
8338            N = pkg.activities.size();
8339            r = null;
8340            for (i=0; i<N; i++) {
8341                PackageParser.Activity a = pkg.activities.get(i);
8342                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8343                        a.info.processName, pkg.applicationInfo.uid);
8344                mActivities.addActivity(a, "activity");
8345                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8346                    if (r == null) {
8347                        r = new StringBuilder(256);
8348                    } else {
8349                        r.append(' ');
8350                    }
8351                    r.append(a.info.name);
8352                }
8353            }
8354            if (r != null) {
8355                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8356            }
8357
8358            N = pkg.permissionGroups.size();
8359            r = null;
8360            for (i=0; i<N; i++) {
8361                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8362                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8363                if (cur == null) {
8364                    mPermissionGroups.put(pg.info.name, pg);
8365                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8366                        if (r == null) {
8367                            r = new StringBuilder(256);
8368                        } else {
8369                            r.append(' ');
8370                        }
8371                        r.append(pg.info.name);
8372                    }
8373                } else {
8374                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8375                            + pg.info.packageName + " ignored: original from "
8376                            + cur.info.packageName);
8377                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8378                        if (r == null) {
8379                            r = new StringBuilder(256);
8380                        } else {
8381                            r.append(' ');
8382                        }
8383                        r.append("DUP:");
8384                        r.append(pg.info.name);
8385                    }
8386                }
8387            }
8388            if (r != null) {
8389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8390            }
8391
8392            N = pkg.permissions.size();
8393            r = null;
8394            for (i=0; i<N; i++) {
8395                PackageParser.Permission p = pkg.permissions.get(i);
8396
8397                // Assume by default that we did not install this permission into the system.
8398                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8399
8400                // Now that permission groups have a special meaning, we ignore permission
8401                // groups for legacy apps to prevent unexpected behavior. In particular,
8402                // permissions for one app being granted to someone just becase they happen
8403                // to be in a group defined by another app (before this had no implications).
8404                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8405                    p.group = mPermissionGroups.get(p.info.group);
8406                    // Warn for a permission in an unknown group.
8407                    if (p.info.group != null && p.group == null) {
8408                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8409                                + p.info.packageName + " in an unknown group " + p.info.group);
8410                    }
8411                }
8412
8413                ArrayMap<String, BasePermission> permissionMap =
8414                        p.tree ? mSettings.mPermissionTrees
8415                                : mSettings.mPermissions;
8416                BasePermission bp = permissionMap.get(p.info.name);
8417
8418                // Allow system apps to redefine non-system permissions
8419                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8420                    final boolean currentOwnerIsSystem = (bp.perm != null
8421                            && isSystemApp(bp.perm.owner));
8422                    if (isSystemApp(p.owner)) {
8423                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8424                            // It's a built-in permission and no owner, take ownership now
8425                            bp.packageSetting = pkgSetting;
8426                            bp.perm = p;
8427                            bp.uid = pkg.applicationInfo.uid;
8428                            bp.sourcePackage = p.info.packageName;
8429                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8430                        } else if (!currentOwnerIsSystem) {
8431                            String msg = "New decl " + p.owner + " of permission  "
8432                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8433                            reportSettingsProblem(Log.WARN, msg);
8434                            bp = null;
8435                        }
8436                    }
8437                }
8438
8439                if (bp == null) {
8440                    bp = new BasePermission(p.info.name, p.info.packageName,
8441                            BasePermission.TYPE_NORMAL);
8442                    permissionMap.put(p.info.name, bp);
8443                }
8444
8445                if (bp.perm == null) {
8446                    if (bp.sourcePackage == null
8447                            || bp.sourcePackage.equals(p.info.packageName)) {
8448                        BasePermission tree = findPermissionTreeLP(p.info.name);
8449                        if (tree == null
8450                                || tree.sourcePackage.equals(p.info.packageName)) {
8451                            bp.packageSetting = pkgSetting;
8452                            bp.perm = p;
8453                            bp.uid = pkg.applicationInfo.uid;
8454                            bp.sourcePackage = p.info.packageName;
8455                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8456                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8457                                if (r == null) {
8458                                    r = new StringBuilder(256);
8459                                } else {
8460                                    r.append(' ');
8461                                }
8462                                r.append(p.info.name);
8463                            }
8464                        } else {
8465                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8466                                    + p.info.packageName + " ignored: base tree "
8467                                    + tree.name + " is from package "
8468                                    + tree.sourcePackage);
8469                        }
8470                    } else {
8471                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8472                                + p.info.packageName + " ignored: original from "
8473                                + bp.sourcePackage);
8474                    }
8475                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8476                    if (r == null) {
8477                        r = new StringBuilder(256);
8478                    } else {
8479                        r.append(' ');
8480                    }
8481                    r.append("DUP:");
8482                    r.append(p.info.name);
8483                }
8484                if (bp.perm == p) {
8485                    bp.protectionLevel = p.info.protectionLevel;
8486                }
8487            }
8488
8489            if (r != null) {
8490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8491            }
8492
8493            N = pkg.instrumentation.size();
8494            r = null;
8495            for (i=0; i<N; i++) {
8496                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8497                a.info.packageName = pkg.applicationInfo.packageName;
8498                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8499                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8500                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8501                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8502                a.info.dataDir = pkg.applicationInfo.dataDir;
8503                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8504                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8505
8506                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8507                // need other information about the application, like the ABI and what not ?
8508                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8509                mInstrumentation.put(a.getComponentName(), a);
8510                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8511                    if (r == null) {
8512                        r = new StringBuilder(256);
8513                    } else {
8514                        r.append(' ');
8515                    }
8516                    r.append(a.info.name);
8517                }
8518            }
8519            if (r != null) {
8520                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8521            }
8522
8523            if (pkg.protectedBroadcasts != null) {
8524                N = pkg.protectedBroadcasts.size();
8525                for (i=0; i<N; i++) {
8526                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8527                }
8528            }
8529
8530            pkgSetting.setTimeStamp(scanFileTime);
8531
8532            // Create idmap files for pairs of (packages, overlay packages).
8533            // Note: "android", ie framework-res.apk, is handled by native layers.
8534            if (pkg.mOverlayTarget != null) {
8535                // This is an overlay package.
8536                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8537                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8538                        mOverlays.put(pkg.mOverlayTarget,
8539                                new ArrayMap<String, PackageParser.Package>());
8540                    }
8541                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8542                    map.put(pkg.packageName, pkg);
8543                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8544                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8545                        createIdmapFailed = true;
8546                    }
8547                }
8548            } else if (mOverlays.containsKey(pkg.packageName) &&
8549                    !pkg.packageName.equals("android")) {
8550                // This is a regular package, with one or more known overlay packages.
8551                createIdmapsForPackageLI(pkg);
8552            }
8553        }
8554
8555        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8556
8557        if (createIdmapFailed) {
8558            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8559                    "scanPackageLI failed to createIdmap");
8560        }
8561        return pkg;
8562    }
8563
8564    /**
8565     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8566     * is derived purely on the basis of the contents of {@code scanFile} and
8567     * {@code cpuAbiOverride}.
8568     *
8569     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8570     */
8571    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8572                                 String cpuAbiOverride, boolean extractLibs)
8573            throws PackageManagerException {
8574        // TODO: We can probably be smarter about this stuff. For installed apps,
8575        // we can calculate this information at install time once and for all. For
8576        // system apps, we can probably assume that this information doesn't change
8577        // after the first boot scan. As things stand, we do lots of unnecessary work.
8578
8579        // Give ourselves some initial paths; we'll come back for another
8580        // pass once we've determined ABI below.
8581        setNativeLibraryPaths(pkg);
8582
8583        // We would never need to extract libs for forward-locked and external packages,
8584        // since the container service will do it for us. We shouldn't attempt to
8585        // extract libs from system app when it was not updated.
8586        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8587                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8588            extractLibs = false;
8589        }
8590
8591        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8592        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8593
8594        NativeLibraryHelper.Handle handle = null;
8595        try {
8596            handle = NativeLibraryHelper.Handle.create(pkg);
8597            // TODO(multiArch): This can be null for apps that didn't go through the
8598            // usual installation process. We can calculate it again, like we
8599            // do during install time.
8600            //
8601            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8602            // unnecessary.
8603            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8604
8605            // Null out the abis so that they can be recalculated.
8606            pkg.applicationInfo.primaryCpuAbi = null;
8607            pkg.applicationInfo.secondaryCpuAbi = null;
8608            if (isMultiArch(pkg.applicationInfo)) {
8609                // Warn if we've set an abiOverride for multi-lib packages..
8610                // By definition, we need to copy both 32 and 64 bit libraries for
8611                // such packages.
8612                if (pkg.cpuAbiOverride != null
8613                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8614                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8615                }
8616
8617                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8618                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8619                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8620                    if (extractLibs) {
8621                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8622                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8623                                useIsaSpecificSubdirs);
8624                    } else {
8625                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8626                    }
8627                }
8628
8629                maybeThrowExceptionForMultiArchCopy(
8630                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8631
8632                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8633                    if (extractLibs) {
8634                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8635                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8636                                useIsaSpecificSubdirs);
8637                    } else {
8638                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8639                    }
8640                }
8641
8642                maybeThrowExceptionForMultiArchCopy(
8643                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8644
8645                if (abi64 >= 0) {
8646                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8647                }
8648
8649                if (abi32 >= 0) {
8650                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8651                    if (abi64 >= 0) {
8652                        if (pkg.use32bitAbi) {
8653                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8654                            pkg.applicationInfo.primaryCpuAbi = abi;
8655                        } else {
8656                            pkg.applicationInfo.secondaryCpuAbi = abi;
8657                        }
8658                    } else {
8659                        pkg.applicationInfo.primaryCpuAbi = abi;
8660                    }
8661                }
8662
8663            } else {
8664                String[] abiList = (cpuAbiOverride != null) ?
8665                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8666
8667                // Enable gross and lame hacks for apps that are built with old
8668                // SDK tools. We must scan their APKs for renderscript bitcode and
8669                // not launch them if it's present. Don't bother checking on devices
8670                // that don't have 64 bit support.
8671                boolean needsRenderScriptOverride = false;
8672                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8673                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8674                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8675                    needsRenderScriptOverride = true;
8676                }
8677
8678                final int copyRet;
8679                if (extractLibs) {
8680                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8681                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8682                } else {
8683                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8684                }
8685
8686                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8687                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8688                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8689                }
8690
8691                if (copyRet >= 0) {
8692                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8693                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8694                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8695                } else if (needsRenderScriptOverride) {
8696                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8697                }
8698            }
8699        } catch (IOException ioe) {
8700            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8701        } finally {
8702            IoUtils.closeQuietly(handle);
8703        }
8704
8705        // Now that we've calculated the ABIs and determined if it's an internal app,
8706        // we will go ahead and populate the nativeLibraryPath.
8707        setNativeLibraryPaths(pkg);
8708    }
8709
8710    /**
8711     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8712     * i.e, so that all packages can be run inside a single process if required.
8713     *
8714     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8715     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8716     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8717     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8718     * updating a package that belongs to a shared user.
8719     *
8720     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8721     * adds unnecessary complexity.
8722     */
8723    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8724            PackageParser.Package scannedPackage, boolean bootComplete) {
8725        String requiredInstructionSet = null;
8726        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8727            requiredInstructionSet = VMRuntime.getInstructionSet(
8728                     scannedPackage.applicationInfo.primaryCpuAbi);
8729        }
8730
8731        PackageSetting requirer = null;
8732        for (PackageSetting ps : packagesForUser) {
8733            // If packagesForUser contains scannedPackage, we skip it. This will happen
8734            // when scannedPackage is an update of an existing package. Without this check,
8735            // we will never be able to change the ABI of any package belonging to a shared
8736            // user, even if it's compatible with other packages.
8737            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8738                if (ps.primaryCpuAbiString == null) {
8739                    continue;
8740                }
8741
8742                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8743                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8744                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8745                    // this but there's not much we can do.
8746                    String errorMessage = "Instruction set mismatch, "
8747                            + ((requirer == null) ? "[caller]" : requirer)
8748                            + " requires " + requiredInstructionSet + " whereas " + ps
8749                            + " requires " + instructionSet;
8750                    Slog.w(TAG, errorMessage);
8751                }
8752
8753                if (requiredInstructionSet == null) {
8754                    requiredInstructionSet = instructionSet;
8755                    requirer = ps;
8756                }
8757            }
8758        }
8759
8760        if (requiredInstructionSet != null) {
8761            String adjustedAbi;
8762            if (requirer != null) {
8763                // requirer != null implies that either scannedPackage was null or that scannedPackage
8764                // did not require an ABI, in which case we have to adjust scannedPackage to match
8765                // the ABI of the set (which is the same as requirer's ABI)
8766                adjustedAbi = requirer.primaryCpuAbiString;
8767                if (scannedPackage != null) {
8768                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8769                }
8770            } else {
8771                // requirer == null implies that we're updating all ABIs in the set to
8772                // match scannedPackage.
8773                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8774            }
8775
8776            for (PackageSetting ps : packagesForUser) {
8777                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8778                    if (ps.primaryCpuAbiString != null) {
8779                        continue;
8780                    }
8781
8782                    ps.primaryCpuAbiString = adjustedAbi;
8783                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8784                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8785                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8786                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8787                                + " (requirer="
8788                                + (requirer == null ? "null" : requirer.pkg.packageName)
8789                                + ", scannedPackage="
8790                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8791                                + ")");
8792                        try {
8793                            mInstaller.rmdex(ps.codePathString,
8794                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8795                        } catch (InstallerException ignored) {
8796                        }
8797                    }
8798                }
8799            }
8800        }
8801    }
8802
8803    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8804        synchronized (mPackages) {
8805            mResolverReplaced = true;
8806            // Set up information for custom user intent resolution activity.
8807            mResolveActivity.applicationInfo = pkg.applicationInfo;
8808            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8809            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8810            mResolveActivity.processName = pkg.applicationInfo.packageName;
8811            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8812            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8813                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8814            mResolveActivity.theme = 0;
8815            mResolveActivity.exported = true;
8816            mResolveActivity.enabled = true;
8817            mResolveInfo.activityInfo = mResolveActivity;
8818            mResolveInfo.priority = 0;
8819            mResolveInfo.preferredOrder = 0;
8820            mResolveInfo.match = 0;
8821            mResolveComponentName = mCustomResolverComponentName;
8822            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8823                    mResolveComponentName);
8824        }
8825    }
8826
8827    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8828        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8829
8830        // Set up information for ephemeral installer activity
8831        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8832        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8833        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8834        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8835        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8836        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8837                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8838        mEphemeralInstallerActivity.theme = 0;
8839        mEphemeralInstallerActivity.exported = true;
8840        mEphemeralInstallerActivity.enabled = true;
8841        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8842        mEphemeralInstallerInfo.priority = 0;
8843        mEphemeralInstallerInfo.preferredOrder = 0;
8844        mEphemeralInstallerInfo.match = 0;
8845
8846        if (DEBUG_EPHEMERAL) {
8847            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8848        }
8849    }
8850
8851    private static String calculateBundledApkRoot(final String codePathString) {
8852        final File codePath = new File(codePathString);
8853        final File codeRoot;
8854        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8855            codeRoot = Environment.getRootDirectory();
8856        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8857            codeRoot = Environment.getOemDirectory();
8858        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8859            codeRoot = Environment.getVendorDirectory();
8860        } else {
8861            // Unrecognized code path; take its top real segment as the apk root:
8862            // e.g. /something/app/blah.apk => /something
8863            try {
8864                File f = codePath.getCanonicalFile();
8865                File parent = f.getParentFile();    // non-null because codePath is a file
8866                File tmp;
8867                while ((tmp = parent.getParentFile()) != null) {
8868                    f = parent;
8869                    parent = tmp;
8870                }
8871                codeRoot = f;
8872                Slog.w(TAG, "Unrecognized code path "
8873                        + codePath + " - using " + codeRoot);
8874            } catch (IOException e) {
8875                // Can't canonicalize the code path -- shenanigans?
8876                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8877                return Environment.getRootDirectory().getPath();
8878            }
8879        }
8880        return codeRoot.getPath();
8881    }
8882
8883    /**
8884     * Derive and set the location of native libraries for the given package,
8885     * which varies depending on where and how the package was installed.
8886     */
8887    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8888        final ApplicationInfo info = pkg.applicationInfo;
8889        final String codePath = pkg.codePath;
8890        final File codeFile = new File(codePath);
8891        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8892        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8893
8894        info.nativeLibraryRootDir = null;
8895        info.nativeLibraryRootRequiresIsa = false;
8896        info.nativeLibraryDir = null;
8897        info.secondaryNativeLibraryDir = null;
8898
8899        if (isApkFile(codeFile)) {
8900            // Monolithic install
8901            if (bundledApp) {
8902                // If "/system/lib64/apkname" exists, assume that is the per-package
8903                // native library directory to use; otherwise use "/system/lib/apkname".
8904                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8905                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8906                        getPrimaryInstructionSet(info));
8907
8908                // This is a bundled system app so choose the path based on the ABI.
8909                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8910                // is just the default path.
8911                final String apkName = deriveCodePathName(codePath);
8912                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8913                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8914                        apkName).getAbsolutePath();
8915
8916                if (info.secondaryCpuAbi != null) {
8917                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8918                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8919                            secondaryLibDir, apkName).getAbsolutePath();
8920                }
8921            } else if (asecApp) {
8922                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8923                        .getAbsolutePath();
8924            } else {
8925                final String apkName = deriveCodePathName(codePath);
8926                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8927                        .getAbsolutePath();
8928            }
8929
8930            info.nativeLibraryRootRequiresIsa = false;
8931            info.nativeLibraryDir = info.nativeLibraryRootDir;
8932        } else {
8933            // Cluster install
8934            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8935            info.nativeLibraryRootRequiresIsa = true;
8936
8937            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8938                    getPrimaryInstructionSet(info)).getAbsolutePath();
8939
8940            if (info.secondaryCpuAbi != null) {
8941                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8942                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8943            }
8944        }
8945    }
8946
8947    /**
8948     * Calculate the abis and roots for a bundled app. These can uniquely
8949     * be determined from the contents of the system partition, i.e whether
8950     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8951     * of this information, and instead assume that the system was built
8952     * sensibly.
8953     */
8954    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8955                                           PackageSetting pkgSetting) {
8956        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8957
8958        // If "/system/lib64/apkname" exists, assume that is the per-package
8959        // native library directory to use; otherwise use "/system/lib/apkname".
8960        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8961        setBundledAppAbi(pkg, apkRoot, apkName);
8962        // pkgSetting might be null during rescan following uninstall of updates
8963        // to a bundled app, so accommodate that possibility.  The settings in
8964        // that case will be established later from the parsed package.
8965        //
8966        // If the settings aren't null, sync them up with what we've just derived.
8967        // note that apkRoot isn't stored in the package settings.
8968        if (pkgSetting != null) {
8969            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8970            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8971        }
8972    }
8973
8974    /**
8975     * Deduces the ABI of a bundled app and sets the relevant fields on the
8976     * parsed pkg object.
8977     *
8978     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8979     *        under which system libraries are installed.
8980     * @param apkName the name of the installed package.
8981     */
8982    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8983        final File codeFile = new File(pkg.codePath);
8984
8985        final boolean has64BitLibs;
8986        final boolean has32BitLibs;
8987        if (isApkFile(codeFile)) {
8988            // Monolithic install
8989            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8990            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8991        } else {
8992            // Cluster install
8993            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8994            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8995                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8996                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8997                has64BitLibs = (new File(rootDir, isa)).exists();
8998            } else {
8999                has64BitLibs = false;
9000            }
9001            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9002                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9003                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9004                has32BitLibs = (new File(rootDir, isa)).exists();
9005            } else {
9006                has32BitLibs = false;
9007            }
9008        }
9009
9010        if (has64BitLibs && !has32BitLibs) {
9011            // The package has 64 bit libs, but not 32 bit libs. Its primary
9012            // ABI should be 64 bit. We can safely assume here that the bundled
9013            // native libraries correspond to the most preferred ABI in the list.
9014
9015            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9016            pkg.applicationInfo.secondaryCpuAbi = null;
9017        } else if (has32BitLibs && !has64BitLibs) {
9018            // The package has 32 bit libs but not 64 bit libs. Its primary
9019            // ABI should be 32 bit.
9020
9021            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9022            pkg.applicationInfo.secondaryCpuAbi = null;
9023        } else if (has32BitLibs && has64BitLibs) {
9024            // The application has both 64 and 32 bit bundled libraries. We check
9025            // here that the app declares multiArch support, and warn if it doesn't.
9026            //
9027            // We will be lenient here and record both ABIs. The primary will be the
9028            // ABI that's higher on the list, i.e, a device that's configured to prefer
9029            // 64 bit apps will see a 64 bit primary ABI,
9030
9031            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9032                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9033            }
9034
9035            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9036                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9037                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9038            } else {
9039                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9040                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9041            }
9042        } else {
9043            pkg.applicationInfo.primaryCpuAbi = null;
9044            pkg.applicationInfo.secondaryCpuAbi = null;
9045        }
9046    }
9047
9048    private void killApplication(String pkgName, int appId, String reason) {
9049        // Request the ActivityManager to kill the process(only for existing packages)
9050        // so that we do not end up in a confused state while the user is still using the older
9051        // version of the application while the new one gets installed.
9052        final long token = Binder.clearCallingIdentity();
9053        try {
9054            IActivityManager am = ActivityManagerNative.getDefault();
9055            if (am != null) {
9056                try {
9057                    am.killApplicationWithAppId(pkgName, appId, reason);
9058                } catch (RemoteException e) {
9059                }
9060            }
9061        } finally {
9062            Binder.restoreCallingIdentity(token);
9063        }
9064    }
9065
9066    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9067        // Remove the parent package setting
9068        PackageSetting ps = (PackageSetting) pkg.mExtras;
9069        if (ps != null) {
9070            removePackageLI(ps, chatty);
9071        }
9072        // Remove the child package setting
9073        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9074        for (int i = 0; i < childCount; i++) {
9075            PackageParser.Package childPkg = pkg.childPackages.get(i);
9076            ps = (PackageSetting) childPkg.mExtras;
9077            if (ps != null) {
9078                removePackageLI(ps, chatty);
9079            }
9080        }
9081    }
9082
9083    void removePackageLI(PackageSetting ps, boolean chatty) {
9084        if (DEBUG_INSTALL) {
9085            if (chatty)
9086                Log.d(TAG, "Removing package " + ps.name);
9087        }
9088
9089        // writer
9090        synchronized (mPackages) {
9091            mPackages.remove(ps.name);
9092            final PackageParser.Package pkg = ps.pkg;
9093            if (pkg != null) {
9094                cleanPackageDataStructuresLILPw(pkg, chatty);
9095            }
9096        }
9097    }
9098
9099    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9100        if (DEBUG_INSTALL) {
9101            if (chatty)
9102                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9103        }
9104
9105        // writer
9106        synchronized (mPackages) {
9107            // Remove the parent package
9108            mPackages.remove(pkg.applicationInfo.packageName);
9109            cleanPackageDataStructuresLILPw(pkg, chatty);
9110
9111            // Remove the child packages
9112            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9113            for (int i = 0; i < childCount; i++) {
9114                PackageParser.Package childPkg = pkg.childPackages.get(i);
9115                mPackages.remove(childPkg.applicationInfo.packageName);
9116                cleanPackageDataStructuresLILPw(childPkg, chatty);
9117            }
9118        }
9119    }
9120
9121    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9122        int N = pkg.providers.size();
9123        StringBuilder r = null;
9124        int i;
9125        for (i=0; i<N; i++) {
9126            PackageParser.Provider p = pkg.providers.get(i);
9127            mProviders.removeProvider(p);
9128            if (p.info.authority == null) {
9129
9130                /* There was another ContentProvider with this authority when
9131                 * this app was installed so this authority is null,
9132                 * Ignore it as we don't have to unregister the provider.
9133                 */
9134                continue;
9135            }
9136            String names[] = p.info.authority.split(";");
9137            for (int j = 0; j < names.length; j++) {
9138                if (mProvidersByAuthority.get(names[j]) == p) {
9139                    mProvidersByAuthority.remove(names[j]);
9140                    if (DEBUG_REMOVE) {
9141                        if (chatty)
9142                            Log.d(TAG, "Unregistered content provider: " + names[j]
9143                                    + ", className = " + p.info.name + ", isSyncable = "
9144                                    + p.info.isSyncable);
9145                    }
9146                }
9147            }
9148            if (DEBUG_REMOVE && chatty) {
9149                if (r == null) {
9150                    r = new StringBuilder(256);
9151                } else {
9152                    r.append(' ');
9153                }
9154                r.append(p.info.name);
9155            }
9156        }
9157        if (r != null) {
9158            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9159        }
9160
9161        N = pkg.services.size();
9162        r = null;
9163        for (i=0; i<N; i++) {
9164            PackageParser.Service s = pkg.services.get(i);
9165            mServices.removeService(s);
9166            if (chatty) {
9167                if (r == null) {
9168                    r = new StringBuilder(256);
9169                } else {
9170                    r.append(' ');
9171                }
9172                r.append(s.info.name);
9173            }
9174        }
9175        if (r != null) {
9176            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9177        }
9178
9179        N = pkg.receivers.size();
9180        r = null;
9181        for (i=0; i<N; i++) {
9182            PackageParser.Activity a = pkg.receivers.get(i);
9183            mReceivers.removeActivity(a, "receiver");
9184            if (DEBUG_REMOVE && chatty) {
9185                if (r == null) {
9186                    r = new StringBuilder(256);
9187                } else {
9188                    r.append(' ');
9189                }
9190                r.append(a.info.name);
9191            }
9192        }
9193        if (r != null) {
9194            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9195        }
9196
9197        N = pkg.activities.size();
9198        r = null;
9199        for (i=0; i<N; i++) {
9200            PackageParser.Activity a = pkg.activities.get(i);
9201            mActivities.removeActivity(a, "activity");
9202            if (DEBUG_REMOVE && chatty) {
9203                if (r == null) {
9204                    r = new StringBuilder(256);
9205                } else {
9206                    r.append(' ');
9207                }
9208                r.append(a.info.name);
9209            }
9210        }
9211        if (r != null) {
9212            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9213        }
9214
9215        N = pkg.permissions.size();
9216        r = null;
9217        for (i=0; i<N; i++) {
9218            PackageParser.Permission p = pkg.permissions.get(i);
9219            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9220            if (bp == null) {
9221                bp = mSettings.mPermissionTrees.get(p.info.name);
9222            }
9223            if (bp != null && bp.perm == p) {
9224                bp.perm = null;
9225                if (DEBUG_REMOVE && chatty) {
9226                    if (r == null) {
9227                        r = new StringBuilder(256);
9228                    } else {
9229                        r.append(' ');
9230                    }
9231                    r.append(p.info.name);
9232                }
9233            }
9234            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9235                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9236                if (appOpPkgs != null) {
9237                    appOpPkgs.remove(pkg.packageName);
9238                }
9239            }
9240        }
9241        if (r != null) {
9242            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9243        }
9244
9245        N = pkg.requestedPermissions.size();
9246        r = null;
9247        for (i=0; i<N; i++) {
9248            String perm = pkg.requestedPermissions.get(i);
9249            BasePermission bp = mSettings.mPermissions.get(perm);
9250            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9251                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9252                if (appOpPkgs != null) {
9253                    appOpPkgs.remove(pkg.packageName);
9254                    if (appOpPkgs.isEmpty()) {
9255                        mAppOpPermissionPackages.remove(perm);
9256                    }
9257                }
9258            }
9259        }
9260        if (r != null) {
9261            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9262        }
9263
9264        N = pkg.instrumentation.size();
9265        r = null;
9266        for (i=0; i<N; i++) {
9267            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9268            mInstrumentation.remove(a.getComponentName());
9269            if (DEBUG_REMOVE && chatty) {
9270                if (r == null) {
9271                    r = new StringBuilder(256);
9272                } else {
9273                    r.append(' ');
9274                }
9275                r.append(a.info.name);
9276            }
9277        }
9278        if (r != null) {
9279            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9280        }
9281
9282        r = null;
9283        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9284            // Only system apps can hold shared libraries.
9285            if (pkg.libraryNames != null) {
9286                for (i=0; i<pkg.libraryNames.size(); i++) {
9287                    String name = pkg.libraryNames.get(i);
9288                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9289                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9290                        mSharedLibraries.remove(name);
9291                        if (DEBUG_REMOVE && chatty) {
9292                            if (r == null) {
9293                                r = new StringBuilder(256);
9294                            } else {
9295                                r.append(' ');
9296                            }
9297                            r.append(name);
9298                        }
9299                    }
9300                }
9301            }
9302        }
9303        if (r != null) {
9304            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9305        }
9306    }
9307
9308    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9309        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9310            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9311                return true;
9312            }
9313        }
9314        return false;
9315    }
9316
9317    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9318    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9319    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9320
9321    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9322        // Update the parent permissions
9323        updatePermissionsLPw(pkg.packageName, pkg, flags);
9324        // Update the child permissions
9325        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9326        for (int i = 0; i < childCount; i++) {
9327            PackageParser.Package childPkg = pkg.childPackages.get(i);
9328            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9329        }
9330    }
9331
9332    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9333            int flags) {
9334        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9335        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9336    }
9337
9338    private void updatePermissionsLPw(String changingPkg,
9339            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9340        // Make sure there are no dangling permission trees.
9341        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9342        while (it.hasNext()) {
9343            final BasePermission bp = it.next();
9344            if (bp.packageSetting == null) {
9345                // We may not yet have parsed the package, so just see if
9346                // we still know about its settings.
9347                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9348            }
9349            if (bp.packageSetting == null) {
9350                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9351                        + " from package " + bp.sourcePackage);
9352                it.remove();
9353            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9354                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9355                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9356                            + " from package " + bp.sourcePackage);
9357                    flags |= UPDATE_PERMISSIONS_ALL;
9358                    it.remove();
9359                }
9360            }
9361        }
9362
9363        // Make sure all dynamic permissions have been assigned to a package,
9364        // and make sure there are no dangling permissions.
9365        it = mSettings.mPermissions.values().iterator();
9366        while (it.hasNext()) {
9367            final BasePermission bp = it.next();
9368            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9369                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9370                        + bp.name + " pkg=" + bp.sourcePackage
9371                        + " info=" + bp.pendingInfo);
9372                if (bp.packageSetting == null && bp.pendingInfo != null) {
9373                    final BasePermission tree = findPermissionTreeLP(bp.name);
9374                    if (tree != null && tree.perm != null) {
9375                        bp.packageSetting = tree.packageSetting;
9376                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9377                                new PermissionInfo(bp.pendingInfo));
9378                        bp.perm.info.packageName = tree.perm.info.packageName;
9379                        bp.perm.info.name = bp.name;
9380                        bp.uid = tree.uid;
9381                    }
9382                }
9383            }
9384            if (bp.packageSetting == null) {
9385                // We may not yet have parsed the package, so just see if
9386                // we still know about its settings.
9387                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9388            }
9389            if (bp.packageSetting == null) {
9390                Slog.w(TAG, "Removing dangling permission: " + bp.name
9391                        + " from package " + bp.sourcePackage);
9392                it.remove();
9393            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9394                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9395                    Slog.i(TAG, "Removing old permission: " + bp.name
9396                            + " from package " + bp.sourcePackage);
9397                    flags |= UPDATE_PERMISSIONS_ALL;
9398                    it.remove();
9399                }
9400            }
9401        }
9402
9403        // Now update the permissions for all packages, in particular
9404        // replace the granted permissions of the system packages.
9405        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9406            for (PackageParser.Package pkg : mPackages.values()) {
9407                if (pkg != pkgInfo) {
9408                    // Only replace for packages on requested volume
9409                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9410                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9411                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9412                    grantPermissionsLPw(pkg, replace, changingPkg);
9413                }
9414            }
9415        }
9416
9417        if (pkgInfo != null) {
9418            // Only replace for packages on requested volume
9419            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9420            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9421                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9422            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9423        }
9424    }
9425
9426    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9427            String packageOfInterest) {
9428        // IMPORTANT: There are two types of permissions: install and runtime.
9429        // Install time permissions are granted when the app is installed to
9430        // all device users and users added in the future. Runtime permissions
9431        // are granted at runtime explicitly to specific users. Normal and signature
9432        // protected permissions are install time permissions. Dangerous permissions
9433        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9434        // otherwise they are runtime permissions. This function does not manage
9435        // runtime permissions except for the case an app targeting Lollipop MR1
9436        // being upgraded to target a newer SDK, in which case dangerous permissions
9437        // are transformed from install time to runtime ones.
9438
9439        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9440        if (ps == null) {
9441            return;
9442        }
9443
9444        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9445
9446        PermissionsState permissionsState = ps.getPermissionsState();
9447        PermissionsState origPermissions = permissionsState;
9448
9449        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9450
9451        boolean runtimePermissionsRevoked = false;
9452        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9453
9454        boolean changedInstallPermission = false;
9455
9456        if (replace) {
9457            ps.installPermissionsFixed = false;
9458            if (!ps.isSharedUser()) {
9459                origPermissions = new PermissionsState(permissionsState);
9460                permissionsState.reset();
9461            } else {
9462                // We need to know only about runtime permission changes since the
9463                // calling code always writes the install permissions state but
9464                // the runtime ones are written only if changed. The only cases of
9465                // changed runtime permissions here are promotion of an install to
9466                // runtime and revocation of a runtime from a shared user.
9467                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9468                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9469                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9470                    runtimePermissionsRevoked = true;
9471                }
9472            }
9473        }
9474
9475        permissionsState.setGlobalGids(mGlobalGids);
9476
9477        final int N = pkg.requestedPermissions.size();
9478        for (int i=0; i<N; i++) {
9479            final String name = pkg.requestedPermissions.get(i);
9480            final BasePermission bp = mSettings.mPermissions.get(name);
9481
9482            if (DEBUG_INSTALL) {
9483                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9484            }
9485
9486            if (bp == null || bp.packageSetting == null) {
9487                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9488                    Slog.w(TAG, "Unknown permission " + name
9489                            + " in package " + pkg.packageName);
9490                }
9491                continue;
9492            }
9493
9494            final String perm = bp.name;
9495            boolean allowedSig = false;
9496            int grant = GRANT_DENIED;
9497
9498            // Keep track of app op permissions.
9499            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9500                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9501                if (pkgs == null) {
9502                    pkgs = new ArraySet<>();
9503                    mAppOpPermissionPackages.put(bp.name, pkgs);
9504                }
9505                pkgs.add(pkg.packageName);
9506            }
9507
9508            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9509            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9510                    >= Build.VERSION_CODES.M;
9511            switch (level) {
9512                case PermissionInfo.PROTECTION_NORMAL: {
9513                    // For all apps normal permissions are install time ones.
9514                    grant = GRANT_INSTALL;
9515                } break;
9516
9517                case PermissionInfo.PROTECTION_DANGEROUS: {
9518                    // If a permission review is required for legacy apps we represent
9519                    // their permissions as always granted runtime ones since we need
9520                    // to keep the review required permission flag per user while an
9521                    // install permission's state is shared across all users.
9522                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9523                        // For legacy apps dangerous permissions are install time ones.
9524                        grant = GRANT_INSTALL;
9525                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9526                        // For legacy apps that became modern, install becomes runtime.
9527                        grant = GRANT_UPGRADE;
9528                    } else if (mPromoteSystemApps
9529                            && isSystemApp(ps)
9530                            && mExistingSystemPackages.contains(ps.name)) {
9531                        // For legacy system apps, install becomes runtime.
9532                        // We cannot check hasInstallPermission() for system apps since those
9533                        // permissions were granted implicitly and not persisted pre-M.
9534                        grant = GRANT_UPGRADE;
9535                    } else {
9536                        // For modern apps keep runtime permissions unchanged.
9537                        grant = GRANT_RUNTIME;
9538                    }
9539                } break;
9540
9541                case PermissionInfo.PROTECTION_SIGNATURE: {
9542                    // For all apps signature permissions are install time ones.
9543                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9544                    if (allowedSig) {
9545                        grant = GRANT_INSTALL;
9546                    }
9547                } break;
9548            }
9549
9550            if (DEBUG_INSTALL) {
9551                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9552            }
9553
9554            if (grant != GRANT_DENIED) {
9555                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9556                    // If this is an existing, non-system package, then
9557                    // we can't add any new permissions to it.
9558                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9559                        // Except...  if this is a permission that was added
9560                        // to the platform (note: need to only do this when
9561                        // updating the platform).
9562                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9563                            grant = GRANT_DENIED;
9564                        }
9565                    }
9566                }
9567
9568                switch (grant) {
9569                    case GRANT_INSTALL: {
9570                        // Revoke this as runtime permission to handle the case of
9571                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9572                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9573                            if (origPermissions.getRuntimePermissionState(
9574                                    bp.name, userId) != null) {
9575                                // Revoke the runtime permission and clear the flags.
9576                                origPermissions.revokeRuntimePermission(bp, userId);
9577                                origPermissions.updatePermissionFlags(bp, userId,
9578                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9579                                // If we revoked a permission permission, we have to write.
9580                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9581                                        changedRuntimePermissionUserIds, userId);
9582                            }
9583                        }
9584                        // Grant an install permission.
9585                        if (permissionsState.grantInstallPermission(bp) !=
9586                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9587                            changedInstallPermission = true;
9588                        }
9589                    } break;
9590
9591                    case GRANT_RUNTIME: {
9592                        // Grant previously granted runtime permissions.
9593                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9594                            PermissionState permissionState = origPermissions
9595                                    .getRuntimePermissionState(bp.name, userId);
9596                            int flags = permissionState != null
9597                                    ? permissionState.getFlags() : 0;
9598                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9599                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9600                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9601                                    // If we cannot put the permission as it was, we have to write.
9602                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9603                                            changedRuntimePermissionUserIds, userId);
9604                                }
9605                                // If the app supports runtime permissions no need for a review.
9606                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9607                                        && appSupportsRuntimePermissions
9608                                        && (flags & PackageManager
9609                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9610                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9611                                    // Since we changed the flags, we have to write.
9612                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9613                                            changedRuntimePermissionUserIds, userId);
9614                                }
9615                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9616                                    && !appSupportsRuntimePermissions) {
9617                                // For legacy apps that need a permission review, every new
9618                                // runtime permission is granted but it is pending a review.
9619                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9620                                    permissionsState.grantRuntimePermission(bp, userId);
9621                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9622                                    // We changed the permission and flags, hence have to write.
9623                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9624                                            changedRuntimePermissionUserIds, userId);
9625                                }
9626                            }
9627                            // Propagate the permission flags.
9628                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9629                        }
9630                    } break;
9631
9632                    case GRANT_UPGRADE: {
9633                        // Grant runtime permissions for a previously held install permission.
9634                        PermissionState permissionState = origPermissions
9635                                .getInstallPermissionState(bp.name);
9636                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9637
9638                        if (origPermissions.revokeInstallPermission(bp)
9639                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9640                            // We will be transferring the permission flags, so clear them.
9641                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9642                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9643                            changedInstallPermission = true;
9644                        }
9645
9646                        // If the permission is not to be promoted to runtime we ignore it and
9647                        // also its other flags as they are not applicable to install permissions.
9648                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9649                            for (int userId : currentUserIds) {
9650                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9651                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9652                                    // Transfer the permission flags.
9653                                    permissionsState.updatePermissionFlags(bp, userId,
9654                                            flags, flags);
9655                                    // If we granted the permission, we have to write.
9656                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9657                                            changedRuntimePermissionUserIds, userId);
9658                                }
9659                            }
9660                        }
9661                    } break;
9662
9663                    default: {
9664                        if (packageOfInterest == null
9665                                || packageOfInterest.equals(pkg.packageName)) {
9666                            Slog.w(TAG, "Not granting permission " + perm
9667                                    + " to package " + pkg.packageName
9668                                    + " because it was previously installed without");
9669                        }
9670                    } break;
9671                }
9672            } else {
9673                if (permissionsState.revokeInstallPermission(bp) !=
9674                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9675                    // Also drop the permission flags.
9676                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9677                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9678                    changedInstallPermission = true;
9679                    Slog.i(TAG, "Un-granting permission " + perm
9680                            + " from package " + pkg.packageName
9681                            + " (protectionLevel=" + bp.protectionLevel
9682                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9683                            + ")");
9684                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9685                    // Don't print warning for app op permissions, since it is fine for them
9686                    // not to be granted, there is a UI for the user to decide.
9687                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9688                        Slog.w(TAG, "Not granting permission " + perm
9689                                + " to package " + pkg.packageName
9690                                + " (protectionLevel=" + bp.protectionLevel
9691                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9692                                + ")");
9693                    }
9694                }
9695            }
9696        }
9697
9698        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9699                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9700            // This is the first that we have heard about this package, so the
9701            // permissions we have now selected are fixed until explicitly
9702            // changed.
9703            ps.installPermissionsFixed = true;
9704        }
9705
9706        // Persist the runtime permissions state for users with changes. If permissions
9707        // were revoked because no app in the shared user declares them we have to
9708        // write synchronously to avoid losing runtime permissions state.
9709        for (int userId : changedRuntimePermissionUserIds) {
9710            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9711        }
9712
9713        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9714    }
9715
9716    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9717        boolean allowed = false;
9718        final int NP = PackageParser.NEW_PERMISSIONS.length;
9719        for (int ip=0; ip<NP; ip++) {
9720            final PackageParser.NewPermissionInfo npi
9721                    = PackageParser.NEW_PERMISSIONS[ip];
9722            if (npi.name.equals(perm)
9723                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9724                allowed = true;
9725                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9726                        + pkg.packageName);
9727                break;
9728            }
9729        }
9730        return allowed;
9731    }
9732
9733    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9734            BasePermission bp, PermissionsState origPermissions) {
9735        boolean allowed;
9736        allowed = (compareSignatures(
9737                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9738                        == PackageManager.SIGNATURE_MATCH)
9739                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9740                        == PackageManager.SIGNATURE_MATCH);
9741        if (!allowed && (bp.protectionLevel
9742                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9743            if (isSystemApp(pkg)) {
9744                // For updated system applications, a system permission
9745                // is granted only if it had been defined by the original application.
9746                if (pkg.isUpdatedSystemApp()) {
9747                    final PackageSetting sysPs = mSettings
9748                            .getDisabledSystemPkgLPr(pkg.packageName);
9749                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9750                        // If the original was granted this permission, we take
9751                        // that grant decision as read and propagate it to the
9752                        // update.
9753                        if (sysPs.isPrivileged()) {
9754                            allowed = true;
9755                        }
9756                    } else {
9757                        // The system apk may have been updated with an older
9758                        // version of the one on the data partition, but which
9759                        // granted a new system permission that it didn't have
9760                        // before.  In this case we do want to allow the app to
9761                        // now get the new permission if the ancestral apk is
9762                        // privileged to get it.
9763                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9764                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9765                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9766                                    allowed = true;
9767                                    break;
9768                                }
9769                            }
9770                        }
9771                        // Also if a privileged parent package on the system image or any of
9772                        // its children requested a privileged permission, the updated child
9773                        // packages can also get the permission.
9774                        if (pkg.parentPackage != null) {
9775                            final PackageSetting disabledSysParentPs = mSettings
9776                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9777                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9778                                    && disabledSysParentPs.isPrivileged()) {
9779                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9780                                    allowed = true;
9781                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9782                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9783                                    for (int i = 0; i < count; i++) {
9784                                        PackageParser.Package disabledSysChildPkg =
9785                                                disabledSysParentPs.pkg.childPackages.get(i);
9786                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9787                                                perm)) {
9788                                            allowed = true;
9789                                            break;
9790                                        }
9791                                    }
9792                                }
9793                            }
9794                        }
9795                    }
9796                } else {
9797                    allowed = isPrivilegedApp(pkg);
9798                }
9799            }
9800        }
9801        if (!allowed) {
9802            if (!allowed && (bp.protectionLevel
9803                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9804                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9805                // If this was a previously normal/dangerous permission that got moved
9806                // to a system permission as part of the runtime permission redesign, then
9807                // we still want to blindly grant it to old apps.
9808                allowed = true;
9809            }
9810            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9811                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9812                // If this permission is to be granted to the system installer and
9813                // this app is an installer, then it gets the permission.
9814                allowed = true;
9815            }
9816            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9817                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9818                // If this permission is to be granted to the system verifier and
9819                // this app is a verifier, then it gets the permission.
9820                allowed = true;
9821            }
9822            if (!allowed && (bp.protectionLevel
9823                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9824                    && isSystemApp(pkg)) {
9825                // Any pre-installed system app is allowed to get this permission.
9826                allowed = true;
9827            }
9828            if (!allowed && (bp.protectionLevel
9829                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9830                // For development permissions, a development permission
9831                // is granted only if it was already granted.
9832                allowed = origPermissions.hasInstallPermission(perm);
9833            }
9834            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9835                    && pkg.packageName.equals(mSetupWizardPackage)) {
9836                // If this permission is to be granted to the system setup wizard and
9837                // this app is a setup wizard, then it gets the permission.
9838                allowed = true;
9839            }
9840        }
9841        return allowed;
9842    }
9843
9844    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9845        final int permCount = pkg.requestedPermissions.size();
9846        for (int j = 0; j < permCount; j++) {
9847            String requestedPermission = pkg.requestedPermissions.get(j);
9848            if (permission.equals(requestedPermission)) {
9849                return true;
9850            }
9851        }
9852        return false;
9853    }
9854
9855    final class ActivityIntentResolver
9856            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9857        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9858                boolean defaultOnly, int userId) {
9859            if (!sUserManager.exists(userId)) return null;
9860            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9861            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9862        }
9863
9864        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9865                int userId) {
9866            if (!sUserManager.exists(userId)) return null;
9867            mFlags = flags;
9868            return super.queryIntent(intent, resolvedType,
9869                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9870        }
9871
9872        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9873                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9874            if (!sUserManager.exists(userId)) return null;
9875            if (packageActivities == null) {
9876                return null;
9877            }
9878            mFlags = flags;
9879            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9880            final int N = packageActivities.size();
9881            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9882                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9883
9884            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9885            for (int i = 0; i < N; ++i) {
9886                intentFilters = packageActivities.get(i).intents;
9887                if (intentFilters != null && intentFilters.size() > 0) {
9888                    PackageParser.ActivityIntentInfo[] array =
9889                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9890                    intentFilters.toArray(array);
9891                    listCut.add(array);
9892                }
9893            }
9894            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9895        }
9896
9897        /**
9898         * Finds a privileged activity that matches the specified activity names.
9899         */
9900        private PackageParser.Activity findMatchingActivity(
9901                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
9902            for (PackageParser.Activity sysActivity : activityList) {
9903                if (sysActivity.info.name.equals(activityInfo.name)) {
9904                    return sysActivity;
9905                }
9906                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
9907                    return sysActivity;
9908                }
9909                if (sysActivity.info.targetActivity != null) {
9910                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
9911                        return sysActivity;
9912                    }
9913                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
9914                        return sysActivity;
9915                    }
9916                }
9917            }
9918            return null;
9919        }
9920
9921        public class IterGenerator<E> {
9922            public Iterator<E> generate(ActivityIntentInfo info) {
9923                return null;
9924            }
9925        }
9926
9927        public class ActionIterGenerator extends IterGenerator<String> {
9928            @Override
9929            public Iterator<String> generate(ActivityIntentInfo info) {
9930                return info.actionsIterator();
9931            }
9932        }
9933
9934        public class CategoriesIterGenerator extends IterGenerator<String> {
9935            @Override
9936            public Iterator<String> generate(ActivityIntentInfo info) {
9937                return info.categoriesIterator();
9938            }
9939        }
9940
9941        public class SchemesIterGenerator extends IterGenerator<String> {
9942            @Override
9943            public Iterator<String> generate(ActivityIntentInfo info) {
9944                return info.schemesIterator();
9945            }
9946        }
9947
9948        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
9949            @Override
9950            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
9951                return info.authoritiesIterator();
9952            }
9953        }
9954
9955        /**
9956         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
9957         * MODIFIED. Do not pass in a list that should not be changed.
9958         */
9959        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
9960                IterGenerator<T> generator, Iterator<T> searchIterator) {
9961            // loop through the set of actions; every one must be found in the intent filter
9962            while (searchIterator.hasNext()) {
9963                // we must have at least one filter in the list to consider a match
9964                if (intentList.size() == 0) {
9965                    break;
9966                }
9967
9968                final T searchAction = searchIterator.next();
9969
9970                // loop through the set of intent filters
9971                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
9972                while (intentIter.hasNext()) {
9973                    final ActivityIntentInfo intentInfo = intentIter.next();
9974                    boolean selectionFound = false;
9975
9976                    // loop through the intent filter's selection criteria; at least one
9977                    // of them must match the searched criteria
9978                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
9979                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
9980                        final T intentSelection = intentSelectionIter.next();
9981                        if (intentSelection != null && intentSelection.equals(searchAction)) {
9982                            selectionFound = true;
9983                            break;
9984                        }
9985                    }
9986
9987                    // the selection criteria wasn't found in this filter's set; this filter
9988                    // is not a potential match
9989                    if (!selectionFound) {
9990                        intentIter.remove();
9991                    }
9992                }
9993            }
9994        }
9995
9996        private boolean isProtectedAction(ActivityIntentInfo filter) {
9997            final Iterator<String> actionsIter = filter.actionsIterator();
9998            while (actionsIter != null && actionsIter.hasNext()) {
9999                final String filterAction = actionsIter.next();
10000                if (PROTECTED_ACTIONS.contains(filterAction)) {
10001                    return true;
10002                }
10003            }
10004            return false;
10005        }
10006
10007        /**
10008         * Adjusts the priority of the given intent filter according to policy.
10009         * <p>
10010         * <ul>
10011         * <li>The priority for non privileged applications is capped to '0'</li>
10012         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10013         * <li>The priority for unbundled updates to privileged applications is capped to the
10014         *      priority defined on the system partition</li>
10015         * </ul>
10016         * <p>
10017         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10018         * allowed to obtain any priority on any action.
10019         */
10020        private void adjustPriority(
10021                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10022            // nothing to do; priority is fine as-is
10023            if (intent.getPriority() <= 0) {
10024                return;
10025            }
10026
10027            final ActivityInfo activityInfo = intent.activity.info;
10028            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10029
10030            final boolean privilegedApp =
10031                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10032            if (!privilegedApp) {
10033                // non-privileged applications can never define a priority >0
10034                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10035                        + " package: " + applicationInfo.packageName
10036                        + " activity: " + intent.activity.className
10037                        + " origPrio: " + intent.getPriority());
10038                intent.setPriority(0);
10039                return;
10040            }
10041
10042            if (systemActivities == null) {
10043                // the system package is not disabled; we're parsing the system partition
10044                if (isProtectedAction(intent)) {
10045                    if (mDeferProtectedFilters) {
10046                        // We can't deal with these just yet. No component should ever obtain a
10047                        // >0 priority for a protected actions, with ONE exception -- the setup
10048                        // wizard. The setup wizard, however, cannot be known until we're able to
10049                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10050                        // until all intent filters have been processed. Chicken, meet egg.
10051                        // Let the filter temporarily have a high priority and rectify the
10052                        // priorities after all system packages have been scanned.
10053                        mProtectedFilters.add(intent);
10054                        if (DEBUG_FILTERS) {
10055                            Slog.i(TAG, "Protected action; save for later;"
10056                                    + " package: " + applicationInfo.packageName
10057                                    + " activity: " + intent.activity.className
10058                                    + " origPrio: " + intent.getPriority());
10059                        }
10060                        return;
10061                    } else {
10062                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10063                            Slog.i(TAG, "No setup wizard;"
10064                                + " All protected intents capped to priority 0");
10065                        }
10066                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10067                            if (DEBUG_FILTERS) {
10068                                Slog.i(TAG, "Found setup wizard;"
10069                                    + " allow priority " + intent.getPriority() + ";"
10070                                    + " package: " + intent.activity.info.packageName
10071                                    + " activity: " + intent.activity.className
10072                                    + " priority: " + intent.getPriority());
10073                            }
10074                            // setup wizard gets whatever it wants
10075                            return;
10076                        }
10077                        Slog.w(TAG, "Protected action; cap priority to 0;"
10078                                + " package: " + intent.activity.info.packageName
10079                                + " activity: " + intent.activity.className
10080                                + " origPrio: " + intent.getPriority());
10081                        intent.setPriority(0);
10082                        return;
10083                    }
10084                }
10085                // privileged apps on the system image get whatever priority they request
10086                return;
10087            }
10088
10089            // privileged app unbundled update ... try to find the same activity
10090            final PackageParser.Activity foundActivity =
10091                    findMatchingActivity(systemActivities, activityInfo);
10092            if (foundActivity == null) {
10093                // this is a new activity; it cannot obtain >0 priority
10094                if (DEBUG_FILTERS) {
10095                    Slog.i(TAG, "New activity; cap priority to 0;"
10096                            + " package: " + applicationInfo.packageName
10097                            + " activity: " + intent.activity.className
10098                            + " origPrio: " + intent.getPriority());
10099                }
10100                intent.setPriority(0);
10101                return;
10102            }
10103
10104            // found activity, now check for filter equivalence
10105
10106            // a shallow copy is enough; we modify the list, not its contents
10107            final List<ActivityIntentInfo> intentListCopy =
10108                    new ArrayList<>(foundActivity.intents);
10109            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10110
10111            // find matching action subsets
10112            final Iterator<String> actionsIterator = intent.actionsIterator();
10113            if (actionsIterator != null) {
10114                getIntentListSubset(
10115                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10116                if (intentListCopy.size() == 0) {
10117                    // no more intents to match; we're not equivalent
10118                    if (DEBUG_FILTERS) {
10119                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10120                                + " package: " + applicationInfo.packageName
10121                                + " activity: " + intent.activity.className
10122                                + " origPrio: " + intent.getPriority());
10123                    }
10124                    intent.setPriority(0);
10125                    return;
10126                }
10127            }
10128
10129            // find matching category subsets
10130            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10131            if (categoriesIterator != null) {
10132                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10133                        categoriesIterator);
10134                if (intentListCopy.size() == 0) {
10135                    // no more intents to match; we're not equivalent
10136                    if (DEBUG_FILTERS) {
10137                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10138                                + " package: " + applicationInfo.packageName
10139                                + " activity: " + intent.activity.className
10140                                + " origPrio: " + intent.getPriority());
10141                    }
10142                    intent.setPriority(0);
10143                    return;
10144                }
10145            }
10146
10147            // find matching schemes subsets
10148            final Iterator<String> schemesIterator = intent.schemesIterator();
10149            if (schemesIterator != null) {
10150                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10151                        schemesIterator);
10152                if (intentListCopy.size() == 0) {
10153                    // no more intents to match; we're not equivalent
10154                    if (DEBUG_FILTERS) {
10155                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10156                                + " package: " + applicationInfo.packageName
10157                                + " activity: " + intent.activity.className
10158                                + " origPrio: " + intent.getPriority());
10159                    }
10160                    intent.setPriority(0);
10161                    return;
10162                }
10163            }
10164
10165            // find matching authorities subsets
10166            final Iterator<IntentFilter.AuthorityEntry>
10167                    authoritiesIterator = intent.authoritiesIterator();
10168            if (authoritiesIterator != null) {
10169                getIntentListSubset(intentListCopy,
10170                        new AuthoritiesIterGenerator(),
10171                        authoritiesIterator);
10172                if (intentListCopy.size() == 0) {
10173                    // no more intents to match; we're not equivalent
10174                    if (DEBUG_FILTERS) {
10175                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10176                                + " package: " + applicationInfo.packageName
10177                                + " activity: " + intent.activity.className
10178                                + " origPrio: " + intent.getPriority());
10179                    }
10180                    intent.setPriority(0);
10181                    return;
10182                }
10183            }
10184
10185            // we found matching filter(s); app gets the max priority of all intents
10186            int cappedPriority = 0;
10187            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10188                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10189            }
10190            if (intent.getPriority() > cappedPriority) {
10191                if (DEBUG_FILTERS) {
10192                    Slog.i(TAG, "Found matching filter(s);"
10193                            + " cap priority to " + cappedPriority + ";"
10194                            + " package: " + applicationInfo.packageName
10195                            + " activity: " + intent.activity.className
10196                            + " origPrio: " + intent.getPriority());
10197                }
10198                intent.setPriority(cappedPriority);
10199                return;
10200            }
10201            // all this for nothing; the requested priority was <= what was on the system
10202        }
10203
10204        public final void addActivity(PackageParser.Activity a, String type) {
10205            mActivities.put(a.getComponentName(), a);
10206            if (DEBUG_SHOW_INFO)
10207                Log.v(
10208                TAG, "  " + type + " " +
10209                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10210            if (DEBUG_SHOW_INFO)
10211                Log.v(TAG, "    Class=" + a.info.name);
10212            final int NI = a.intents.size();
10213            for (int j=0; j<NI; j++) {
10214                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10215                if ("activity".equals(type)) {
10216                    final PackageSetting ps =
10217                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10218                    final List<PackageParser.Activity> systemActivities =
10219                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10220                    adjustPriority(systemActivities, intent);
10221                }
10222                if (DEBUG_SHOW_INFO) {
10223                    Log.v(TAG, "    IntentFilter:");
10224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10225                }
10226                if (!intent.debugCheck()) {
10227                    Log.w(TAG, "==> For Activity " + a.info.name);
10228                }
10229                addFilter(intent);
10230            }
10231        }
10232
10233        public final void removeActivity(PackageParser.Activity a, String type) {
10234            mActivities.remove(a.getComponentName());
10235            if (DEBUG_SHOW_INFO) {
10236                Log.v(TAG, "  " + type + " "
10237                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10238                                : a.info.name) + ":");
10239                Log.v(TAG, "    Class=" + a.info.name);
10240            }
10241            final int NI = a.intents.size();
10242            for (int j=0; j<NI; j++) {
10243                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10244                if (DEBUG_SHOW_INFO) {
10245                    Log.v(TAG, "    IntentFilter:");
10246                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10247                }
10248                removeFilter(intent);
10249            }
10250        }
10251
10252        @Override
10253        protected boolean allowFilterResult(
10254                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10255            ActivityInfo filterAi = filter.activity.info;
10256            for (int i=dest.size()-1; i>=0; i--) {
10257                ActivityInfo destAi = dest.get(i).activityInfo;
10258                if (destAi.name == filterAi.name
10259                        && destAi.packageName == filterAi.packageName) {
10260                    return false;
10261                }
10262            }
10263            return true;
10264        }
10265
10266        @Override
10267        protected ActivityIntentInfo[] newArray(int size) {
10268            return new ActivityIntentInfo[size];
10269        }
10270
10271        @Override
10272        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10273            if (!sUserManager.exists(userId)) return true;
10274            PackageParser.Package p = filter.activity.owner;
10275            if (p != null) {
10276                PackageSetting ps = (PackageSetting)p.mExtras;
10277                if (ps != null) {
10278                    // System apps are never considered stopped for purposes of
10279                    // filtering, because there may be no way for the user to
10280                    // actually re-launch them.
10281                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10282                            && ps.getStopped(userId);
10283                }
10284            }
10285            return false;
10286        }
10287
10288        @Override
10289        protected boolean isPackageForFilter(String packageName,
10290                PackageParser.ActivityIntentInfo info) {
10291            return packageName.equals(info.activity.owner.packageName);
10292        }
10293
10294        @Override
10295        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10296                int match, int userId) {
10297            if (!sUserManager.exists(userId)) return null;
10298            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10299                return null;
10300            }
10301            final PackageParser.Activity activity = info.activity;
10302            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10303            if (ps == null) {
10304                return null;
10305            }
10306            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10307                    ps.readUserState(userId), userId);
10308            if (ai == null) {
10309                return null;
10310            }
10311            final ResolveInfo res = new ResolveInfo();
10312            res.activityInfo = ai;
10313            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10314                res.filter = info;
10315            }
10316            if (info != null) {
10317                res.handleAllWebDataURI = info.handleAllWebDataURI();
10318            }
10319            res.priority = info.getPriority();
10320            res.preferredOrder = activity.owner.mPreferredOrder;
10321            //System.out.println("Result: " + res.activityInfo.className +
10322            //                   " = " + res.priority);
10323            res.match = match;
10324            res.isDefault = info.hasDefault;
10325            res.labelRes = info.labelRes;
10326            res.nonLocalizedLabel = info.nonLocalizedLabel;
10327            if (userNeedsBadging(userId)) {
10328                res.noResourceId = true;
10329            } else {
10330                res.icon = info.icon;
10331            }
10332            res.iconResourceId = info.icon;
10333            res.system = res.activityInfo.applicationInfo.isSystemApp();
10334            return res;
10335        }
10336
10337        @Override
10338        protected void sortResults(List<ResolveInfo> results) {
10339            Collections.sort(results, mResolvePrioritySorter);
10340        }
10341
10342        @Override
10343        protected void dumpFilter(PrintWriter out, String prefix,
10344                PackageParser.ActivityIntentInfo filter) {
10345            out.print(prefix); out.print(
10346                    Integer.toHexString(System.identityHashCode(filter.activity)));
10347                    out.print(' ');
10348                    filter.activity.printComponentShortName(out);
10349                    out.print(" filter ");
10350                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10351        }
10352
10353        @Override
10354        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10355            return filter.activity;
10356        }
10357
10358        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10359            PackageParser.Activity activity = (PackageParser.Activity)label;
10360            out.print(prefix); out.print(
10361                    Integer.toHexString(System.identityHashCode(activity)));
10362                    out.print(' ');
10363                    activity.printComponentShortName(out);
10364            if (count > 1) {
10365                out.print(" ("); out.print(count); out.print(" filters)");
10366            }
10367            out.println();
10368        }
10369
10370        // Keys are String (activity class name), values are Activity.
10371        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10372                = new ArrayMap<ComponentName, PackageParser.Activity>();
10373        private int mFlags;
10374    }
10375
10376    private final class ServiceIntentResolver
10377            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10378        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10379                boolean defaultOnly, int userId) {
10380            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10381            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10382        }
10383
10384        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10385                int userId) {
10386            if (!sUserManager.exists(userId)) return null;
10387            mFlags = flags;
10388            return super.queryIntent(intent, resolvedType,
10389                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10390        }
10391
10392        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10393                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10394            if (!sUserManager.exists(userId)) return null;
10395            if (packageServices == null) {
10396                return null;
10397            }
10398            mFlags = flags;
10399            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10400            final int N = packageServices.size();
10401            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10402                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10403
10404            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10405            for (int i = 0; i < N; ++i) {
10406                intentFilters = packageServices.get(i).intents;
10407                if (intentFilters != null && intentFilters.size() > 0) {
10408                    PackageParser.ServiceIntentInfo[] array =
10409                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10410                    intentFilters.toArray(array);
10411                    listCut.add(array);
10412                }
10413            }
10414            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10415        }
10416
10417        public final void addService(PackageParser.Service s) {
10418            mServices.put(s.getComponentName(), s);
10419            if (DEBUG_SHOW_INFO) {
10420                Log.v(TAG, "  "
10421                        + (s.info.nonLocalizedLabel != null
10422                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10423                Log.v(TAG, "    Class=" + s.info.name);
10424            }
10425            final int NI = s.intents.size();
10426            int j;
10427            for (j=0; j<NI; j++) {
10428                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10429                if (DEBUG_SHOW_INFO) {
10430                    Log.v(TAG, "    IntentFilter:");
10431                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10432                }
10433                if (!intent.debugCheck()) {
10434                    Log.w(TAG, "==> For Service " + s.info.name);
10435                }
10436                addFilter(intent);
10437            }
10438        }
10439
10440        public final void removeService(PackageParser.Service s) {
10441            mServices.remove(s.getComponentName());
10442            if (DEBUG_SHOW_INFO) {
10443                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10444                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10445                Log.v(TAG, "    Class=" + s.info.name);
10446            }
10447            final int NI = s.intents.size();
10448            int j;
10449            for (j=0; j<NI; j++) {
10450                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10451                if (DEBUG_SHOW_INFO) {
10452                    Log.v(TAG, "    IntentFilter:");
10453                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10454                }
10455                removeFilter(intent);
10456            }
10457        }
10458
10459        @Override
10460        protected boolean allowFilterResult(
10461                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10462            ServiceInfo filterSi = filter.service.info;
10463            for (int i=dest.size()-1; i>=0; i--) {
10464                ServiceInfo destAi = dest.get(i).serviceInfo;
10465                if (destAi.name == filterSi.name
10466                        && destAi.packageName == filterSi.packageName) {
10467                    return false;
10468                }
10469            }
10470            return true;
10471        }
10472
10473        @Override
10474        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10475            return new PackageParser.ServiceIntentInfo[size];
10476        }
10477
10478        @Override
10479        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10480            if (!sUserManager.exists(userId)) return true;
10481            PackageParser.Package p = filter.service.owner;
10482            if (p != null) {
10483                PackageSetting ps = (PackageSetting)p.mExtras;
10484                if (ps != null) {
10485                    // System apps are never considered stopped for purposes of
10486                    // filtering, because there may be no way for the user to
10487                    // actually re-launch them.
10488                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10489                            && ps.getStopped(userId);
10490                }
10491            }
10492            return false;
10493        }
10494
10495        @Override
10496        protected boolean isPackageForFilter(String packageName,
10497                PackageParser.ServiceIntentInfo info) {
10498            return packageName.equals(info.service.owner.packageName);
10499        }
10500
10501        @Override
10502        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10503                int match, int userId) {
10504            if (!sUserManager.exists(userId)) return null;
10505            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10506            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10507                return null;
10508            }
10509            final PackageParser.Service service = info.service;
10510            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10511            if (ps == null) {
10512                return null;
10513            }
10514            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10515                    ps.readUserState(userId), userId);
10516            if (si == null) {
10517                return null;
10518            }
10519            final ResolveInfo res = new ResolveInfo();
10520            res.serviceInfo = si;
10521            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10522                res.filter = filter;
10523            }
10524            res.priority = info.getPriority();
10525            res.preferredOrder = service.owner.mPreferredOrder;
10526            res.match = match;
10527            res.isDefault = info.hasDefault;
10528            res.labelRes = info.labelRes;
10529            res.nonLocalizedLabel = info.nonLocalizedLabel;
10530            res.icon = info.icon;
10531            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10532            return res;
10533        }
10534
10535        @Override
10536        protected void sortResults(List<ResolveInfo> results) {
10537            Collections.sort(results, mResolvePrioritySorter);
10538        }
10539
10540        @Override
10541        protected void dumpFilter(PrintWriter out, String prefix,
10542                PackageParser.ServiceIntentInfo filter) {
10543            out.print(prefix); out.print(
10544                    Integer.toHexString(System.identityHashCode(filter.service)));
10545                    out.print(' ');
10546                    filter.service.printComponentShortName(out);
10547                    out.print(" filter ");
10548                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10549        }
10550
10551        @Override
10552        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10553            return filter.service;
10554        }
10555
10556        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10557            PackageParser.Service service = (PackageParser.Service)label;
10558            out.print(prefix); out.print(
10559                    Integer.toHexString(System.identityHashCode(service)));
10560                    out.print(' ');
10561                    service.printComponentShortName(out);
10562            if (count > 1) {
10563                out.print(" ("); out.print(count); out.print(" filters)");
10564            }
10565            out.println();
10566        }
10567
10568//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10569//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10570//            final List<ResolveInfo> retList = Lists.newArrayList();
10571//            while (i.hasNext()) {
10572//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10573//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10574//                    retList.add(resolveInfo);
10575//                }
10576//            }
10577//            return retList;
10578//        }
10579
10580        // Keys are String (activity class name), values are Activity.
10581        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10582                = new ArrayMap<ComponentName, PackageParser.Service>();
10583        private int mFlags;
10584    };
10585
10586    private final class ProviderIntentResolver
10587            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10588        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10589                boolean defaultOnly, int userId) {
10590            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10591            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10592        }
10593
10594        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10595                int userId) {
10596            if (!sUserManager.exists(userId))
10597                return null;
10598            mFlags = flags;
10599            return super.queryIntent(intent, resolvedType,
10600                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10601        }
10602
10603        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10604                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10605            if (!sUserManager.exists(userId))
10606                return null;
10607            if (packageProviders == null) {
10608                return null;
10609            }
10610            mFlags = flags;
10611            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10612            final int N = packageProviders.size();
10613            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10614                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10615
10616            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10617            for (int i = 0; i < N; ++i) {
10618                intentFilters = packageProviders.get(i).intents;
10619                if (intentFilters != null && intentFilters.size() > 0) {
10620                    PackageParser.ProviderIntentInfo[] array =
10621                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10622                    intentFilters.toArray(array);
10623                    listCut.add(array);
10624                }
10625            }
10626            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10627        }
10628
10629        public final void addProvider(PackageParser.Provider p) {
10630            if (mProviders.containsKey(p.getComponentName())) {
10631                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10632                return;
10633            }
10634
10635            mProviders.put(p.getComponentName(), p);
10636            if (DEBUG_SHOW_INFO) {
10637                Log.v(TAG, "  "
10638                        + (p.info.nonLocalizedLabel != null
10639                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10640                Log.v(TAG, "    Class=" + p.info.name);
10641            }
10642            final int NI = p.intents.size();
10643            int j;
10644            for (j = 0; j < NI; j++) {
10645                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10646                if (DEBUG_SHOW_INFO) {
10647                    Log.v(TAG, "    IntentFilter:");
10648                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10649                }
10650                if (!intent.debugCheck()) {
10651                    Log.w(TAG, "==> For Provider " + p.info.name);
10652                }
10653                addFilter(intent);
10654            }
10655        }
10656
10657        public final void removeProvider(PackageParser.Provider p) {
10658            mProviders.remove(p.getComponentName());
10659            if (DEBUG_SHOW_INFO) {
10660                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10661                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10662                Log.v(TAG, "    Class=" + p.info.name);
10663            }
10664            final int NI = p.intents.size();
10665            int j;
10666            for (j = 0; j < NI; j++) {
10667                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10668                if (DEBUG_SHOW_INFO) {
10669                    Log.v(TAG, "    IntentFilter:");
10670                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10671                }
10672                removeFilter(intent);
10673            }
10674        }
10675
10676        @Override
10677        protected boolean allowFilterResult(
10678                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10679            ProviderInfo filterPi = filter.provider.info;
10680            for (int i = dest.size() - 1; i >= 0; i--) {
10681                ProviderInfo destPi = dest.get(i).providerInfo;
10682                if (destPi.name == filterPi.name
10683                        && destPi.packageName == filterPi.packageName) {
10684                    return false;
10685                }
10686            }
10687            return true;
10688        }
10689
10690        @Override
10691        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10692            return new PackageParser.ProviderIntentInfo[size];
10693        }
10694
10695        @Override
10696        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10697            if (!sUserManager.exists(userId))
10698                return true;
10699            PackageParser.Package p = filter.provider.owner;
10700            if (p != null) {
10701                PackageSetting ps = (PackageSetting) p.mExtras;
10702                if (ps != null) {
10703                    // System apps are never considered stopped for purposes of
10704                    // filtering, because there may be no way for the user to
10705                    // actually re-launch them.
10706                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10707                            && ps.getStopped(userId);
10708                }
10709            }
10710            return false;
10711        }
10712
10713        @Override
10714        protected boolean isPackageForFilter(String packageName,
10715                PackageParser.ProviderIntentInfo info) {
10716            return packageName.equals(info.provider.owner.packageName);
10717        }
10718
10719        @Override
10720        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10721                int match, int userId) {
10722            if (!sUserManager.exists(userId))
10723                return null;
10724            final PackageParser.ProviderIntentInfo info = filter;
10725            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10726                return null;
10727            }
10728            final PackageParser.Provider provider = info.provider;
10729            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10730            if (ps == null) {
10731                return null;
10732            }
10733            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10734                    ps.readUserState(userId), userId);
10735            if (pi == null) {
10736                return null;
10737            }
10738            final ResolveInfo res = new ResolveInfo();
10739            res.providerInfo = pi;
10740            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10741                res.filter = filter;
10742            }
10743            res.priority = info.getPriority();
10744            res.preferredOrder = provider.owner.mPreferredOrder;
10745            res.match = match;
10746            res.isDefault = info.hasDefault;
10747            res.labelRes = info.labelRes;
10748            res.nonLocalizedLabel = info.nonLocalizedLabel;
10749            res.icon = info.icon;
10750            res.system = res.providerInfo.applicationInfo.isSystemApp();
10751            return res;
10752        }
10753
10754        @Override
10755        protected void sortResults(List<ResolveInfo> results) {
10756            Collections.sort(results, mResolvePrioritySorter);
10757        }
10758
10759        @Override
10760        protected void dumpFilter(PrintWriter out, String prefix,
10761                PackageParser.ProviderIntentInfo filter) {
10762            out.print(prefix);
10763            out.print(
10764                    Integer.toHexString(System.identityHashCode(filter.provider)));
10765            out.print(' ');
10766            filter.provider.printComponentShortName(out);
10767            out.print(" filter ");
10768            out.println(Integer.toHexString(System.identityHashCode(filter)));
10769        }
10770
10771        @Override
10772        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10773            return filter.provider;
10774        }
10775
10776        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10777            PackageParser.Provider provider = (PackageParser.Provider)label;
10778            out.print(prefix); out.print(
10779                    Integer.toHexString(System.identityHashCode(provider)));
10780                    out.print(' ');
10781                    provider.printComponentShortName(out);
10782            if (count > 1) {
10783                out.print(" ("); out.print(count); out.print(" filters)");
10784            }
10785            out.println();
10786        }
10787
10788        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10789                = new ArrayMap<ComponentName, PackageParser.Provider>();
10790        private int mFlags;
10791    }
10792
10793    private static final class EphemeralIntentResolver
10794            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10795        @Override
10796        protected EphemeralResolveIntentInfo[] newArray(int size) {
10797            return new EphemeralResolveIntentInfo[size];
10798        }
10799
10800        @Override
10801        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10802            return true;
10803        }
10804
10805        @Override
10806        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10807                int userId) {
10808            if (!sUserManager.exists(userId)) {
10809                return null;
10810            }
10811            return info.getEphemeralResolveInfo();
10812        }
10813    }
10814
10815    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10816            new Comparator<ResolveInfo>() {
10817        public int compare(ResolveInfo r1, ResolveInfo r2) {
10818            int v1 = r1.priority;
10819            int v2 = r2.priority;
10820            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10821            if (v1 != v2) {
10822                return (v1 > v2) ? -1 : 1;
10823            }
10824            v1 = r1.preferredOrder;
10825            v2 = r2.preferredOrder;
10826            if (v1 != v2) {
10827                return (v1 > v2) ? -1 : 1;
10828            }
10829            if (r1.isDefault != r2.isDefault) {
10830                return r1.isDefault ? -1 : 1;
10831            }
10832            v1 = r1.match;
10833            v2 = r2.match;
10834            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10835            if (v1 != v2) {
10836                return (v1 > v2) ? -1 : 1;
10837            }
10838            if (r1.system != r2.system) {
10839                return r1.system ? -1 : 1;
10840            }
10841            if (r1.activityInfo != null) {
10842                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10843            }
10844            if (r1.serviceInfo != null) {
10845                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10846            }
10847            if (r1.providerInfo != null) {
10848                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10849            }
10850            return 0;
10851        }
10852    };
10853
10854    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10855            new Comparator<ProviderInfo>() {
10856        public int compare(ProviderInfo p1, ProviderInfo p2) {
10857            final int v1 = p1.initOrder;
10858            final int v2 = p2.initOrder;
10859            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10860        }
10861    };
10862
10863    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10864            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10865            final int[] userIds) {
10866        mHandler.post(new Runnable() {
10867            @Override
10868            public void run() {
10869                try {
10870                    final IActivityManager am = ActivityManagerNative.getDefault();
10871                    if (am == null) return;
10872                    final int[] resolvedUserIds;
10873                    if (userIds == null) {
10874                        resolvedUserIds = am.getRunningUserIds();
10875                    } else {
10876                        resolvedUserIds = userIds;
10877                    }
10878                    for (int id : resolvedUserIds) {
10879                        final Intent intent = new Intent(action,
10880                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10881                        if (extras != null) {
10882                            intent.putExtras(extras);
10883                        }
10884                        if (targetPkg != null) {
10885                            intent.setPackage(targetPkg);
10886                        }
10887                        // Modify the UID when posting to other users
10888                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10889                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10890                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10891                            intent.putExtra(Intent.EXTRA_UID, uid);
10892                        }
10893                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10894                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10895                        if (DEBUG_BROADCASTS) {
10896                            RuntimeException here = new RuntimeException("here");
10897                            here.fillInStackTrace();
10898                            Slog.d(TAG, "Sending to user " + id + ": "
10899                                    + intent.toShortString(false, true, false, false)
10900                                    + " " + intent.getExtras(), here);
10901                        }
10902                        am.broadcastIntent(null, intent, null, finishedReceiver,
10903                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10904                                null, finishedReceiver != null, false, id);
10905                    }
10906                } catch (RemoteException ex) {
10907                }
10908            }
10909        });
10910    }
10911
10912    /**
10913     * Check if the external storage media is available. This is true if there
10914     * is a mounted external storage medium or if the external storage is
10915     * emulated.
10916     */
10917    private boolean isExternalMediaAvailable() {
10918        return mMediaMounted || Environment.isExternalStorageEmulated();
10919    }
10920
10921    @Override
10922    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10923        // writer
10924        synchronized (mPackages) {
10925            if (!isExternalMediaAvailable()) {
10926                // If the external storage is no longer mounted at this point,
10927                // the caller may not have been able to delete all of this
10928                // packages files and can not delete any more.  Bail.
10929                return null;
10930            }
10931            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10932            if (lastPackage != null) {
10933                pkgs.remove(lastPackage);
10934            }
10935            if (pkgs.size() > 0) {
10936                return pkgs.get(0);
10937            }
10938        }
10939        return null;
10940    }
10941
10942    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10943        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10944                userId, andCode ? 1 : 0, packageName);
10945        if (mSystemReady) {
10946            msg.sendToTarget();
10947        } else {
10948            if (mPostSystemReadyMessages == null) {
10949                mPostSystemReadyMessages = new ArrayList<>();
10950            }
10951            mPostSystemReadyMessages.add(msg);
10952        }
10953    }
10954
10955    void startCleaningPackages() {
10956        // reader
10957        if (!isExternalMediaAvailable()) {
10958            return;
10959        }
10960        synchronized (mPackages) {
10961            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10962                return;
10963            }
10964        }
10965        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10966        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10967        IActivityManager am = ActivityManagerNative.getDefault();
10968        if (am != null) {
10969            try {
10970                am.startService(null, intent, null, mContext.getOpPackageName(),
10971                        UserHandle.USER_SYSTEM);
10972            } catch (RemoteException e) {
10973            }
10974        }
10975    }
10976
10977    @Override
10978    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10979            int installFlags, String installerPackageName, int userId) {
10980        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10981
10982        final int callingUid = Binder.getCallingUid();
10983        enforceCrossUserPermission(callingUid, userId,
10984                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10985
10986        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10987            try {
10988                if (observer != null) {
10989                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10990                }
10991            } catch (RemoteException re) {
10992            }
10993            return;
10994        }
10995
10996        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10997            installFlags |= PackageManager.INSTALL_FROM_ADB;
10998
10999        } else {
11000            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11001            // about installerPackageName.
11002
11003            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11004            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11005        }
11006
11007        UserHandle user;
11008        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11009            user = UserHandle.ALL;
11010        } else {
11011            user = new UserHandle(userId);
11012        }
11013
11014        // Only system components can circumvent runtime permissions when installing.
11015        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11016                && mContext.checkCallingOrSelfPermission(Manifest.permission
11017                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11018            throw new SecurityException("You need the "
11019                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11020                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11021        }
11022
11023        final File originFile = new File(originPath);
11024        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11025
11026        final Message msg = mHandler.obtainMessage(INIT_COPY);
11027        final VerificationInfo verificationInfo = new VerificationInfo(
11028                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11029        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11030                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11031                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11032                null /*certificates*/);
11033        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11034        msg.obj = params;
11035
11036        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11037                System.identityHashCode(msg.obj));
11038        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11039                System.identityHashCode(msg.obj));
11040
11041        mHandler.sendMessage(msg);
11042    }
11043
11044    void installStage(String packageName, File stagedDir, String stagedCid,
11045            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11046            String installerPackageName, int installerUid, UserHandle user,
11047            Certificate[][] certificates) {
11048        if (DEBUG_EPHEMERAL) {
11049            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11050                Slog.d(TAG, "Ephemeral install of " + packageName);
11051            }
11052        }
11053        final VerificationInfo verificationInfo = new VerificationInfo(
11054                sessionParams.originatingUri, sessionParams.referrerUri,
11055                sessionParams.originatingUid, installerUid);
11056
11057        final OriginInfo origin;
11058        if (stagedDir != null) {
11059            origin = OriginInfo.fromStagedFile(stagedDir);
11060        } else {
11061            origin = OriginInfo.fromStagedContainer(stagedCid);
11062        }
11063
11064        final Message msg = mHandler.obtainMessage(INIT_COPY);
11065        final InstallParams params = new InstallParams(origin, null, observer,
11066                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11067                verificationInfo, user, sessionParams.abiOverride,
11068                sessionParams.grantedRuntimePermissions, certificates);
11069        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11070        msg.obj = params;
11071
11072        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11073                System.identityHashCode(msg.obj));
11074        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11075                System.identityHashCode(msg.obj));
11076
11077        mHandler.sendMessage(msg);
11078    }
11079
11080    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11081            int userId) {
11082        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11083        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11084    }
11085
11086    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11087            int appId, int userId) {
11088        Bundle extras = new Bundle(1);
11089        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11090
11091        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11092                packageName, extras, 0, null, null, new int[] {userId});
11093        try {
11094            IActivityManager am = ActivityManagerNative.getDefault();
11095            if (isSystem && am.isUserRunning(userId, 0)) {
11096                // The just-installed/enabled app is bundled on the system, so presumed
11097                // to be able to run automatically without needing an explicit launch.
11098                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11099                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11100                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11101                        .setPackage(packageName);
11102                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11103                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11104            }
11105        } catch (RemoteException e) {
11106            // shouldn't happen
11107            Slog.w(TAG, "Unable to bootstrap installed package", e);
11108        }
11109    }
11110
11111    @Override
11112    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11113            int userId) {
11114        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11115        PackageSetting pkgSetting;
11116        final int uid = Binder.getCallingUid();
11117        enforceCrossUserPermission(uid, userId,
11118                true /* requireFullPermission */, true /* checkShell */,
11119                "setApplicationHiddenSetting for user " + userId);
11120
11121        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11122            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11123            return false;
11124        }
11125
11126        long callingId = Binder.clearCallingIdentity();
11127        try {
11128            boolean sendAdded = false;
11129            boolean sendRemoved = false;
11130            // writer
11131            synchronized (mPackages) {
11132                pkgSetting = mSettings.mPackages.get(packageName);
11133                if (pkgSetting == null) {
11134                    return false;
11135                }
11136                if (pkgSetting.getHidden(userId) != hidden) {
11137                    pkgSetting.setHidden(hidden, userId);
11138                    mSettings.writePackageRestrictionsLPr(userId);
11139                    if (hidden) {
11140                        sendRemoved = true;
11141                    } else {
11142                        sendAdded = true;
11143                    }
11144                }
11145            }
11146            if (sendAdded) {
11147                sendPackageAddedForUser(packageName, pkgSetting, userId);
11148                return true;
11149            }
11150            if (sendRemoved) {
11151                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11152                        "hiding pkg");
11153                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11154                return true;
11155            }
11156        } finally {
11157            Binder.restoreCallingIdentity(callingId);
11158        }
11159        return false;
11160    }
11161
11162    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11163            int userId) {
11164        final PackageRemovedInfo info = new PackageRemovedInfo();
11165        info.removedPackage = packageName;
11166        info.removedUsers = new int[] {userId};
11167        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11168        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11169    }
11170
11171    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11172        if (pkgList.length > 0) {
11173            Bundle extras = new Bundle(1);
11174            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11175
11176            sendPackageBroadcast(
11177                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11178                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11179                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11180                    new int[] {userId});
11181        }
11182    }
11183
11184    /**
11185     * Returns true if application is not found or there was an error. Otherwise it returns
11186     * the hidden state of the package for the given user.
11187     */
11188    @Override
11189    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11190        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11191        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11192                true /* requireFullPermission */, false /* checkShell */,
11193                "getApplicationHidden for user " + userId);
11194        PackageSetting pkgSetting;
11195        long callingId = Binder.clearCallingIdentity();
11196        try {
11197            // writer
11198            synchronized (mPackages) {
11199                pkgSetting = mSettings.mPackages.get(packageName);
11200                if (pkgSetting == null) {
11201                    return true;
11202                }
11203                return pkgSetting.getHidden(userId);
11204            }
11205        } finally {
11206            Binder.restoreCallingIdentity(callingId);
11207        }
11208    }
11209
11210    /**
11211     * @hide
11212     */
11213    @Override
11214    public int installExistingPackageAsUser(String packageName, int userId) {
11215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11216                null);
11217        PackageSetting pkgSetting;
11218        final int uid = Binder.getCallingUid();
11219        enforceCrossUserPermission(uid, userId,
11220                true /* requireFullPermission */, true /* checkShell */,
11221                "installExistingPackage for user " + userId);
11222        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11223            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11224        }
11225
11226        long callingId = Binder.clearCallingIdentity();
11227        try {
11228            boolean installed = false;
11229
11230            // writer
11231            synchronized (mPackages) {
11232                pkgSetting = mSettings.mPackages.get(packageName);
11233                if (pkgSetting == null) {
11234                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11235                }
11236                if (!pkgSetting.getInstalled(userId)) {
11237                    pkgSetting.setInstalled(true, userId);
11238                    pkgSetting.setHidden(false, userId);
11239                    mSettings.writePackageRestrictionsLPr(userId);
11240                    installed = true;
11241                }
11242            }
11243
11244            if (installed) {
11245                if (pkgSetting.pkg != null) {
11246                    synchronized (mInstallLock) {
11247                        // We don't need to freeze for a brand new install
11248                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11249                    }
11250                }
11251                sendPackageAddedForUser(packageName, pkgSetting, userId);
11252            }
11253        } finally {
11254            Binder.restoreCallingIdentity(callingId);
11255        }
11256
11257        return PackageManager.INSTALL_SUCCEEDED;
11258    }
11259
11260    boolean isUserRestricted(int userId, String restrictionKey) {
11261        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11262        if (restrictions.getBoolean(restrictionKey, false)) {
11263            Log.w(TAG, "User is restricted: " + restrictionKey);
11264            return true;
11265        }
11266        return false;
11267    }
11268
11269    @Override
11270    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11271            int userId) {
11272        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11274                true /* requireFullPermission */, true /* checkShell */,
11275                "setPackagesSuspended for user " + userId);
11276
11277        if (ArrayUtils.isEmpty(packageNames)) {
11278            return packageNames;
11279        }
11280
11281        // List of package names for whom the suspended state has changed.
11282        List<String> changedPackages = new ArrayList<>(packageNames.length);
11283        // List of package names for whom the suspended state is not set as requested in this
11284        // method.
11285        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11286        for (int i = 0; i < packageNames.length; i++) {
11287            String packageName = packageNames[i];
11288            long callingId = Binder.clearCallingIdentity();
11289            try {
11290                boolean changed = false;
11291                final int appId;
11292                synchronized (mPackages) {
11293                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11294                    if (pkgSetting == null) {
11295                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11296                                + "\". Skipping suspending/un-suspending.");
11297                        unactionedPackages.add(packageName);
11298                        continue;
11299                    }
11300                    appId = pkgSetting.appId;
11301                    if (pkgSetting.getSuspended(userId) != suspended) {
11302                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11303                            unactionedPackages.add(packageName);
11304                            continue;
11305                        }
11306                        pkgSetting.setSuspended(suspended, userId);
11307                        mSettings.writePackageRestrictionsLPr(userId);
11308                        changed = true;
11309                        changedPackages.add(packageName);
11310                    }
11311                }
11312
11313                if (changed && suspended) {
11314                    killApplication(packageName, UserHandle.getUid(userId, appId),
11315                            "suspending package");
11316                }
11317            } finally {
11318                Binder.restoreCallingIdentity(callingId);
11319            }
11320        }
11321
11322        if (!changedPackages.isEmpty()) {
11323            sendPackagesSuspendedForUser(changedPackages.toArray(
11324                    new String[changedPackages.size()]), userId, suspended);
11325        }
11326
11327        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11328    }
11329
11330    @Override
11331    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11333                true /* requireFullPermission */, false /* checkShell */,
11334                "isPackageSuspendedForUser for user " + userId);
11335        synchronized (mPackages) {
11336            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11337            if (pkgSetting == null) {
11338                throw new IllegalArgumentException("Unknown target package: " + packageName);
11339            }
11340            return pkgSetting.getSuspended(userId);
11341        }
11342    }
11343
11344    /**
11345     * TODO: cache and disallow blocking the active dialer.
11346     *
11347     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11348     */
11349    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11350        if (isPackageDeviceAdmin(packageName, userId)) {
11351            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11352                    + "\": has an active device admin");
11353            return false;
11354        }
11355
11356        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11357        if (packageName.equals(activeLauncherPackageName)) {
11358            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11359                    + "\": contains the active launcher");
11360            return false;
11361        }
11362
11363        if (packageName.equals(mRequiredInstallerPackage)) {
11364            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11365                    + "\": required for package installation");
11366            return false;
11367        }
11368
11369        if (packageName.equals(mRequiredVerifierPackage)) {
11370            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11371                    + "\": required for package verification");
11372            return false;
11373        }
11374
11375        final PackageParser.Package pkg = mPackages.get(packageName);
11376        if (pkg != null && isPrivilegedApp(pkg)) {
11377            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11378                    + "\": is a privileged app");
11379            return false;
11380        }
11381
11382        return true;
11383    }
11384
11385    private String getActiveLauncherPackageName(int userId) {
11386        Intent intent = new Intent(Intent.ACTION_MAIN);
11387        intent.addCategory(Intent.CATEGORY_HOME);
11388        ResolveInfo resolveInfo = resolveIntent(
11389                intent,
11390                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11391                PackageManager.MATCH_DEFAULT_ONLY,
11392                userId);
11393
11394        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11395    }
11396
11397    @Override
11398    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11399        mContext.enforceCallingOrSelfPermission(
11400                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11401                "Only package verification agents can verify applications");
11402
11403        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11404        final PackageVerificationResponse response = new PackageVerificationResponse(
11405                verificationCode, Binder.getCallingUid());
11406        msg.arg1 = id;
11407        msg.obj = response;
11408        mHandler.sendMessage(msg);
11409    }
11410
11411    @Override
11412    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11413            long millisecondsToDelay) {
11414        mContext.enforceCallingOrSelfPermission(
11415                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11416                "Only package verification agents can extend verification timeouts");
11417
11418        final PackageVerificationState state = mPendingVerification.get(id);
11419        final PackageVerificationResponse response = new PackageVerificationResponse(
11420                verificationCodeAtTimeout, Binder.getCallingUid());
11421
11422        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11423            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11424        }
11425        if (millisecondsToDelay < 0) {
11426            millisecondsToDelay = 0;
11427        }
11428        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11429                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11430            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11431        }
11432
11433        if ((state != null) && !state.timeoutExtended()) {
11434            state.extendTimeout();
11435
11436            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11437            msg.arg1 = id;
11438            msg.obj = response;
11439            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11440        }
11441    }
11442
11443    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11444            int verificationCode, UserHandle user) {
11445        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11446        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11447        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11448        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11449        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11450
11451        mContext.sendBroadcastAsUser(intent, user,
11452                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11453    }
11454
11455    private ComponentName matchComponentForVerifier(String packageName,
11456            List<ResolveInfo> receivers) {
11457        ActivityInfo targetReceiver = null;
11458
11459        final int NR = receivers.size();
11460        for (int i = 0; i < NR; i++) {
11461            final ResolveInfo info = receivers.get(i);
11462            if (info.activityInfo == null) {
11463                continue;
11464            }
11465
11466            if (packageName.equals(info.activityInfo.packageName)) {
11467                targetReceiver = info.activityInfo;
11468                break;
11469            }
11470        }
11471
11472        if (targetReceiver == null) {
11473            return null;
11474        }
11475
11476        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11477    }
11478
11479    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11480            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11481        if (pkgInfo.verifiers.length == 0) {
11482            return null;
11483        }
11484
11485        final int N = pkgInfo.verifiers.length;
11486        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11487        for (int i = 0; i < N; i++) {
11488            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11489
11490            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11491                    receivers);
11492            if (comp == null) {
11493                continue;
11494            }
11495
11496            final int verifierUid = getUidForVerifier(verifierInfo);
11497            if (verifierUid == -1) {
11498                continue;
11499            }
11500
11501            if (DEBUG_VERIFY) {
11502                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11503                        + " with the correct signature");
11504            }
11505            sufficientVerifiers.add(comp);
11506            verificationState.addSufficientVerifier(verifierUid);
11507        }
11508
11509        return sufficientVerifiers;
11510    }
11511
11512    private int getUidForVerifier(VerifierInfo verifierInfo) {
11513        synchronized (mPackages) {
11514            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11515            if (pkg == null) {
11516                return -1;
11517            } else if (pkg.mSignatures.length != 1) {
11518                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11519                        + " has more than one signature; ignoring");
11520                return -1;
11521            }
11522
11523            /*
11524             * If the public key of the package's signature does not match
11525             * our expected public key, then this is a different package and
11526             * we should skip.
11527             */
11528
11529            final byte[] expectedPublicKey;
11530            try {
11531                final Signature verifierSig = pkg.mSignatures[0];
11532                final PublicKey publicKey = verifierSig.getPublicKey();
11533                expectedPublicKey = publicKey.getEncoded();
11534            } catch (CertificateException e) {
11535                return -1;
11536            }
11537
11538            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11539
11540            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11541                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11542                        + " does not have the expected public key; ignoring");
11543                return -1;
11544            }
11545
11546            return pkg.applicationInfo.uid;
11547        }
11548    }
11549
11550    @Override
11551    public void finishPackageInstall(int token) {
11552        enforceSystemOrRoot("Only the system is allowed to finish installs");
11553
11554        if (DEBUG_INSTALL) {
11555            Slog.v(TAG, "BM finishing package install for " + token);
11556        }
11557        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11558
11559        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11560        mHandler.sendMessage(msg);
11561    }
11562
11563    /**
11564     * Get the verification agent timeout.
11565     *
11566     * @return verification timeout in milliseconds
11567     */
11568    private long getVerificationTimeout() {
11569        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11570                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11571                DEFAULT_VERIFICATION_TIMEOUT);
11572    }
11573
11574    /**
11575     * Get the default verification agent response code.
11576     *
11577     * @return default verification response code
11578     */
11579    private int getDefaultVerificationResponse() {
11580        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11581                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11582                DEFAULT_VERIFICATION_RESPONSE);
11583    }
11584
11585    /**
11586     * Check whether or not package verification has been enabled.
11587     *
11588     * @return true if verification should be performed
11589     */
11590    private boolean isVerificationEnabled(int userId, int installFlags) {
11591        if (!DEFAULT_VERIFY_ENABLE) {
11592            return false;
11593        }
11594        // Ephemeral apps don't get the full verification treatment
11595        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11596            if (DEBUG_EPHEMERAL) {
11597                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11598            }
11599            return false;
11600        }
11601
11602        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11603
11604        // Check if installing from ADB
11605        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11606            // Do not run verification in a test harness environment
11607            if (ActivityManager.isRunningInTestHarness()) {
11608                return false;
11609            }
11610            if (ensureVerifyAppsEnabled) {
11611                return true;
11612            }
11613            // Check if the developer does not want package verification for ADB installs
11614            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11615                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11616                return false;
11617            }
11618        }
11619
11620        if (ensureVerifyAppsEnabled) {
11621            return true;
11622        }
11623
11624        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11625                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11626    }
11627
11628    @Override
11629    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11630            throws RemoteException {
11631        mContext.enforceCallingOrSelfPermission(
11632                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11633                "Only intentfilter verification agents can verify applications");
11634
11635        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11636        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11637                Binder.getCallingUid(), verificationCode, failedDomains);
11638        msg.arg1 = id;
11639        msg.obj = response;
11640        mHandler.sendMessage(msg);
11641    }
11642
11643    @Override
11644    public int getIntentVerificationStatus(String packageName, int userId) {
11645        synchronized (mPackages) {
11646            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11647        }
11648    }
11649
11650    @Override
11651    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11652        mContext.enforceCallingOrSelfPermission(
11653                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11654
11655        boolean result = false;
11656        synchronized (mPackages) {
11657            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11658        }
11659        if (result) {
11660            scheduleWritePackageRestrictionsLocked(userId);
11661        }
11662        return result;
11663    }
11664
11665    @Override
11666    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11667            String packageName) {
11668        synchronized (mPackages) {
11669            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11670        }
11671    }
11672
11673    @Override
11674    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11675        if (TextUtils.isEmpty(packageName)) {
11676            return ParceledListSlice.emptyList();
11677        }
11678        synchronized (mPackages) {
11679            PackageParser.Package pkg = mPackages.get(packageName);
11680            if (pkg == null || pkg.activities == null) {
11681                return ParceledListSlice.emptyList();
11682            }
11683            final int count = pkg.activities.size();
11684            ArrayList<IntentFilter> result = new ArrayList<>();
11685            for (int n=0; n<count; n++) {
11686                PackageParser.Activity activity = pkg.activities.get(n);
11687                if (activity.intents != null && activity.intents.size() > 0) {
11688                    result.addAll(activity.intents);
11689                }
11690            }
11691            return new ParceledListSlice<>(result);
11692        }
11693    }
11694
11695    @Override
11696    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11697        mContext.enforceCallingOrSelfPermission(
11698                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11699
11700        synchronized (mPackages) {
11701            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11702            if (packageName != null) {
11703                result |= updateIntentVerificationStatus(packageName,
11704                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11705                        userId);
11706                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11707                        packageName, userId);
11708            }
11709            return result;
11710        }
11711    }
11712
11713    @Override
11714    public String getDefaultBrowserPackageName(int userId) {
11715        synchronized (mPackages) {
11716            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11717        }
11718    }
11719
11720    /**
11721     * Get the "allow unknown sources" setting.
11722     *
11723     * @return the current "allow unknown sources" setting
11724     */
11725    private int getUnknownSourcesSettings() {
11726        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11727                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11728                -1);
11729    }
11730
11731    @Override
11732    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11733        final int uid = Binder.getCallingUid();
11734        // writer
11735        synchronized (mPackages) {
11736            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11737            if (targetPackageSetting == null) {
11738                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11739            }
11740
11741            PackageSetting installerPackageSetting;
11742            if (installerPackageName != null) {
11743                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11744                if (installerPackageSetting == null) {
11745                    throw new IllegalArgumentException("Unknown installer package: "
11746                            + installerPackageName);
11747                }
11748            } else {
11749                installerPackageSetting = null;
11750            }
11751
11752            Signature[] callerSignature;
11753            Object obj = mSettings.getUserIdLPr(uid);
11754            if (obj != null) {
11755                if (obj instanceof SharedUserSetting) {
11756                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11757                } else if (obj instanceof PackageSetting) {
11758                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11759                } else {
11760                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11761                }
11762            } else {
11763                throw new SecurityException("Unknown calling UID: " + uid);
11764            }
11765
11766            // Verify: can't set installerPackageName to a package that is
11767            // not signed with the same cert as the caller.
11768            if (installerPackageSetting != null) {
11769                if (compareSignatures(callerSignature,
11770                        installerPackageSetting.signatures.mSignatures)
11771                        != PackageManager.SIGNATURE_MATCH) {
11772                    throw new SecurityException(
11773                            "Caller does not have same cert as new installer package "
11774                            + installerPackageName);
11775                }
11776            }
11777
11778            // Verify: if target already has an installer package, it must
11779            // be signed with the same cert as the caller.
11780            if (targetPackageSetting.installerPackageName != null) {
11781                PackageSetting setting = mSettings.mPackages.get(
11782                        targetPackageSetting.installerPackageName);
11783                // If the currently set package isn't valid, then it's always
11784                // okay to change it.
11785                if (setting != null) {
11786                    if (compareSignatures(callerSignature,
11787                            setting.signatures.mSignatures)
11788                            != PackageManager.SIGNATURE_MATCH) {
11789                        throw new SecurityException(
11790                                "Caller does not have same cert as old installer package "
11791                                + targetPackageSetting.installerPackageName);
11792                    }
11793                }
11794            }
11795
11796            // Okay!
11797            targetPackageSetting.installerPackageName = installerPackageName;
11798            if (installerPackageName != null) {
11799                mSettings.mInstallerPackages.add(installerPackageName);
11800            }
11801            scheduleWriteSettingsLocked();
11802        }
11803    }
11804
11805    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11806        // Queue up an async operation since the package installation may take a little while.
11807        mHandler.post(new Runnable() {
11808            public void run() {
11809                mHandler.removeCallbacks(this);
11810                 // Result object to be returned
11811                PackageInstalledInfo res = new PackageInstalledInfo();
11812                res.setReturnCode(currentStatus);
11813                res.uid = -1;
11814                res.pkg = null;
11815                res.removedInfo = null;
11816                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11817                    args.doPreInstall(res.returnCode);
11818                    synchronized (mInstallLock) {
11819                        installPackageTracedLI(args, res);
11820                    }
11821                    args.doPostInstall(res.returnCode, res.uid);
11822                }
11823
11824                // A restore should be performed at this point if (a) the install
11825                // succeeded, (b) the operation is not an update, and (c) the new
11826                // package has not opted out of backup participation.
11827                final boolean update = res.removedInfo != null
11828                        && res.removedInfo.removedPackage != null;
11829                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11830                boolean doRestore = !update
11831                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11832
11833                // Set up the post-install work request bookkeeping.  This will be used
11834                // and cleaned up by the post-install event handling regardless of whether
11835                // there's a restore pass performed.  Token values are >= 1.
11836                int token;
11837                if (mNextInstallToken < 0) mNextInstallToken = 1;
11838                token = mNextInstallToken++;
11839
11840                PostInstallData data = new PostInstallData(args, res);
11841                mRunningInstalls.put(token, data);
11842                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11843
11844                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11845                    // Pass responsibility to the Backup Manager.  It will perform a
11846                    // restore if appropriate, then pass responsibility back to the
11847                    // Package Manager to run the post-install observer callbacks
11848                    // and broadcasts.
11849                    IBackupManager bm = IBackupManager.Stub.asInterface(
11850                            ServiceManager.getService(Context.BACKUP_SERVICE));
11851                    if (bm != null) {
11852                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11853                                + " to BM for possible restore");
11854                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11855                        try {
11856                            // TODO: http://b/22388012
11857                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11858                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11859                            } else {
11860                                doRestore = false;
11861                            }
11862                        } catch (RemoteException e) {
11863                            // can't happen; the backup manager is local
11864                        } catch (Exception e) {
11865                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11866                            doRestore = false;
11867                        }
11868                    } else {
11869                        Slog.e(TAG, "Backup Manager not found!");
11870                        doRestore = false;
11871                    }
11872                }
11873
11874                if (!doRestore) {
11875                    // No restore possible, or the Backup Manager was mysteriously not
11876                    // available -- just fire the post-install work request directly.
11877                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11878
11879                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11880
11881                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11882                    mHandler.sendMessage(msg);
11883                }
11884            }
11885        });
11886    }
11887
11888    private abstract class HandlerParams {
11889        private static final int MAX_RETRIES = 4;
11890
11891        /**
11892         * Number of times startCopy() has been attempted and had a non-fatal
11893         * error.
11894         */
11895        private int mRetries = 0;
11896
11897        /** User handle for the user requesting the information or installation. */
11898        private final UserHandle mUser;
11899        String traceMethod;
11900        int traceCookie;
11901
11902        HandlerParams(UserHandle user) {
11903            mUser = user;
11904        }
11905
11906        UserHandle getUser() {
11907            return mUser;
11908        }
11909
11910        HandlerParams setTraceMethod(String traceMethod) {
11911            this.traceMethod = traceMethod;
11912            return this;
11913        }
11914
11915        HandlerParams setTraceCookie(int traceCookie) {
11916            this.traceCookie = traceCookie;
11917            return this;
11918        }
11919
11920        final boolean startCopy() {
11921            boolean res;
11922            try {
11923                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11924
11925                if (++mRetries > MAX_RETRIES) {
11926                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11927                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11928                    handleServiceError();
11929                    return false;
11930                } else {
11931                    handleStartCopy();
11932                    res = true;
11933                }
11934            } catch (RemoteException e) {
11935                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11936                mHandler.sendEmptyMessage(MCS_RECONNECT);
11937                res = false;
11938            }
11939            handleReturnCode();
11940            return res;
11941        }
11942
11943        final void serviceError() {
11944            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11945            handleServiceError();
11946            handleReturnCode();
11947        }
11948
11949        abstract void handleStartCopy() throws RemoteException;
11950        abstract void handleServiceError();
11951        abstract void handleReturnCode();
11952    }
11953
11954    class MeasureParams extends HandlerParams {
11955        private final PackageStats mStats;
11956        private boolean mSuccess;
11957
11958        private final IPackageStatsObserver mObserver;
11959
11960        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11961            super(new UserHandle(stats.userHandle));
11962            mObserver = observer;
11963            mStats = stats;
11964        }
11965
11966        @Override
11967        public String toString() {
11968            return "MeasureParams{"
11969                + Integer.toHexString(System.identityHashCode(this))
11970                + " " + mStats.packageName + "}";
11971        }
11972
11973        @Override
11974        void handleStartCopy() throws RemoteException {
11975            synchronized (mInstallLock) {
11976                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11977            }
11978
11979            if (mSuccess) {
11980                final boolean mounted;
11981                if (Environment.isExternalStorageEmulated()) {
11982                    mounted = true;
11983                } else {
11984                    final String status = Environment.getExternalStorageState();
11985                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11986                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11987                }
11988
11989                if (mounted) {
11990                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11991
11992                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11993                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11994
11995                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11996                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11997
11998                    // Always subtract cache size, since it's a subdirectory
11999                    mStats.externalDataSize -= mStats.externalCacheSize;
12000
12001                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12002                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12003
12004                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12005                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12006                }
12007            }
12008        }
12009
12010        @Override
12011        void handleReturnCode() {
12012            if (mObserver != null) {
12013                try {
12014                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12015                } catch (RemoteException e) {
12016                    Slog.i(TAG, "Observer no longer exists.");
12017                }
12018            }
12019        }
12020
12021        @Override
12022        void handleServiceError() {
12023            Slog.e(TAG, "Could not measure application " + mStats.packageName
12024                            + " external storage");
12025        }
12026    }
12027
12028    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12029            throws RemoteException {
12030        long result = 0;
12031        for (File path : paths) {
12032            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12033        }
12034        return result;
12035    }
12036
12037    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12038        for (File path : paths) {
12039            try {
12040                mcs.clearDirectory(path.getAbsolutePath());
12041            } catch (RemoteException e) {
12042            }
12043        }
12044    }
12045
12046    static class OriginInfo {
12047        /**
12048         * Location where install is coming from, before it has been
12049         * copied/renamed into place. This could be a single monolithic APK
12050         * file, or a cluster directory. This location may be untrusted.
12051         */
12052        final File file;
12053        final String cid;
12054
12055        /**
12056         * Flag indicating that {@link #file} or {@link #cid} has already been
12057         * staged, meaning downstream users don't need to defensively copy the
12058         * contents.
12059         */
12060        final boolean staged;
12061
12062        /**
12063         * Flag indicating that {@link #file} or {@link #cid} is an already
12064         * installed app that is being moved.
12065         */
12066        final boolean existing;
12067
12068        final String resolvedPath;
12069        final File resolvedFile;
12070
12071        static OriginInfo fromNothing() {
12072            return new OriginInfo(null, null, false, false);
12073        }
12074
12075        static OriginInfo fromUntrustedFile(File file) {
12076            return new OriginInfo(file, null, false, false);
12077        }
12078
12079        static OriginInfo fromExistingFile(File file) {
12080            return new OriginInfo(file, null, false, true);
12081        }
12082
12083        static OriginInfo fromStagedFile(File file) {
12084            return new OriginInfo(file, null, true, false);
12085        }
12086
12087        static OriginInfo fromStagedContainer(String cid) {
12088            return new OriginInfo(null, cid, true, false);
12089        }
12090
12091        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12092            this.file = file;
12093            this.cid = cid;
12094            this.staged = staged;
12095            this.existing = existing;
12096
12097            if (cid != null) {
12098                resolvedPath = PackageHelper.getSdDir(cid);
12099                resolvedFile = new File(resolvedPath);
12100            } else if (file != null) {
12101                resolvedPath = file.getAbsolutePath();
12102                resolvedFile = file;
12103            } else {
12104                resolvedPath = null;
12105                resolvedFile = null;
12106            }
12107        }
12108    }
12109
12110    static class MoveInfo {
12111        final int moveId;
12112        final String fromUuid;
12113        final String toUuid;
12114        final String packageName;
12115        final String dataAppName;
12116        final int appId;
12117        final String seinfo;
12118        final int targetSdkVersion;
12119
12120        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12121                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12122            this.moveId = moveId;
12123            this.fromUuid = fromUuid;
12124            this.toUuid = toUuid;
12125            this.packageName = packageName;
12126            this.dataAppName = dataAppName;
12127            this.appId = appId;
12128            this.seinfo = seinfo;
12129            this.targetSdkVersion = targetSdkVersion;
12130        }
12131    }
12132
12133    static class VerificationInfo {
12134        /** A constant used to indicate that a uid value is not present. */
12135        public static final int NO_UID = -1;
12136
12137        /** URI referencing where the package was downloaded from. */
12138        final Uri originatingUri;
12139
12140        /** HTTP referrer URI associated with the originatingURI. */
12141        final Uri referrer;
12142
12143        /** UID of the application that the install request originated from. */
12144        final int originatingUid;
12145
12146        /** UID of application requesting the install */
12147        final int installerUid;
12148
12149        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12150            this.originatingUri = originatingUri;
12151            this.referrer = referrer;
12152            this.originatingUid = originatingUid;
12153            this.installerUid = installerUid;
12154        }
12155    }
12156
12157    class InstallParams extends HandlerParams {
12158        final OriginInfo origin;
12159        final MoveInfo move;
12160        final IPackageInstallObserver2 observer;
12161        int installFlags;
12162        final String installerPackageName;
12163        final String volumeUuid;
12164        private InstallArgs mArgs;
12165        private int mRet;
12166        final String packageAbiOverride;
12167        final String[] grantedRuntimePermissions;
12168        final VerificationInfo verificationInfo;
12169        final Certificate[][] certificates;
12170
12171        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12172                int installFlags, String installerPackageName, String volumeUuid,
12173                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12174                String[] grantedPermissions, Certificate[][] certificates) {
12175            super(user);
12176            this.origin = origin;
12177            this.move = move;
12178            this.observer = observer;
12179            this.installFlags = installFlags;
12180            this.installerPackageName = installerPackageName;
12181            this.volumeUuid = volumeUuid;
12182            this.verificationInfo = verificationInfo;
12183            this.packageAbiOverride = packageAbiOverride;
12184            this.grantedRuntimePermissions = grantedPermissions;
12185            this.certificates = certificates;
12186        }
12187
12188        @Override
12189        public String toString() {
12190            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12191                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12192        }
12193
12194        private int installLocationPolicy(PackageInfoLite pkgLite) {
12195            String packageName = pkgLite.packageName;
12196            int installLocation = pkgLite.installLocation;
12197            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12198            // reader
12199            synchronized (mPackages) {
12200                // Currently installed package which the new package is attempting to replace or
12201                // null if no such package is installed.
12202                PackageParser.Package installedPkg = mPackages.get(packageName);
12203                // Package which currently owns the data which the new package will own if installed.
12204                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12205                // will be null whereas dataOwnerPkg will contain information about the package
12206                // which was uninstalled while keeping its data.
12207                PackageParser.Package dataOwnerPkg = installedPkg;
12208                if (dataOwnerPkg  == null) {
12209                    PackageSetting ps = mSettings.mPackages.get(packageName);
12210                    if (ps != null) {
12211                        dataOwnerPkg = ps.pkg;
12212                    }
12213                }
12214
12215                if (dataOwnerPkg != null) {
12216                    // If installed, the package will get access to data left on the device by its
12217                    // predecessor. As a security measure, this is permited only if this is not a
12218                    // version downgrade or if the predecessor package is marked as debuggable and
12219                    // a downgrade is explicitly requested.
12220                    //
12221                    // On debuggable platform builds, downgrades are permitted even for
12222                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12223                    // not offer security guarantees and thus it's OK to disable some security
12224                    // mechanisms to make debugging/testing easier on those builds. However, even on
12225                    // debuggable builds downgrades of packages are permitted only if requested via
12226                    // installFlags. This is because we aim to keep the behavior of debuggable
12227                    // platform builds as close as possible to the behavior of non-debuggable
12228                    // platform builds.
12229                    final boolean downgradeRequested =
12230                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12231                    final boolean packageDebuggable =
12232                                (dataOwnerPkg.applicationInfo.flags
12233                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12234                    final boolean downgradePermitted =
12235                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12236                    if (!downgradePermitted) {
12237                        try {
12238                            checkDowngrade(dataOwnerPkg, pkgLite);
12239                        } catch (PackageManagerException e) {
12240                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12241                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12242                        }
12243                    }
12244                }
12245
12246                if (installedPkg != null) {
12247                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12248                        // Check for updated system application.
12249                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12250                            if (onSd) {
12251                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12252                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12253                            }
12254                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12255                        } else {
12256                            if (onSd) {
12257                                // Install flag overrides everything.
12258                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12259                            }
12260                            // If current upgrade specifies particular preference
12261                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12262                                // Application explicitly specified internal.
12263                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12264                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12265                                // App explictly prefers external. Let policy decide
12266                            } else {
12267                                // Prefer previous location
12268                                if (isExternal(installedPkg)) {
12269                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12270                                }
12271                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12272                            }
12273                        }
12274                    } else {
12275                        // Invalid install. Return error code
12276                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12277                    }
12278                }
12279            }
12280            // All the special cases have been taken care of.
12281            // Return result based on recommended install location.
12282            if (onSd) {
12283                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12284            }
12285            return pkgLite.recommendedInstallLocation;
12286        }
12287
12288        /*
12289         * Invoke remote method to get package information and install
12290         * location values. Override install location based on default
12291         * policy if needed and then create install arguments based
12292         * on the install location.
12293         */
12294        public void handleStartCopy() throws RemoteException {
12295            int ret = PackageManager.INSTALL_SUCCEEDED;
12296
12297            // If we're already staged, we've firmly committed to an install location
12298            if (origin.staged) {
12299                if (origin.file != null) {
12300                    installFlags |= PackageManager.INSTALL_INTERNAL;
12301                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12302                } else if (origin.cid != null) {
12303                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12304                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12305                } else {
12306                    throw new IllegalStateException("Invalid stage location");
12307                }
12308            }
12309
12310            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12311            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12312            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12313            PackageInfoLite pkgLite = null;
12314
12315            if (onInt && onSd) {
12316                // Check if both bits are set.
12317                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12318                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12319            } else if (onSd && ephemeral) {
12320                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12321                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12322            } else {
12323                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12324                        packageAbiOverride);
12325
12326                if (DEBUG_EPHEMERAL && ephemeral) {
12327                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12328                }
12329
12330                /*
12331                 * If we have too little free space, try to free cache
12332                 * before giving up.
12333                 */
12334                if (!origin.staged && pkgLite.recommendedInstallLocation
12335                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12336                    // TODO: focus freeing disk space on the target device
12337                    final StorageManager storage = StorageManager.from(mContext);
12338                    final long lowThreshold = storage.getStorageLowBytes(
12339                            Environment.getDataDirectory());
12340
12341                    final long sizeBytes = mContainerService.calculateInstalledSize(
12342                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12343
12344                    try {
12345                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12346                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12347                                installFlags, packageAbiOverride);
12348                    } catch (InstallerException e) {
12349                        Slog.w(TAG, "Failed to free cache", e);
12350                    }
12351
12352                    /*
12353                     * The cache free must have deleted the file we
12354                     * downloaded to install.
12355                     *
12356                     * TODO: fix the "freeCache" call to not delete
12357                     *       the file we care about.
12358                     */
12359                    if (pkgLite.recommendedInstallLocation
12360                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12361                        pkgLite.recommendedInstallLocation
12362                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12363                    }
12364                }
12365            }
12366
12367            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12368                int loc = pkgLite.recommendedInstallLocation;
12369                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12370                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12371                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12372                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12373                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12374                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12375                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12376                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12377                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12378                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12379                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12380                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12381                } else {
12382                    // Override with defaults if needed.
12383                    loc = installLocationPolicy(pkgLite);
12384                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12385                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12386                    } else if (!onSd && !onInt) {
12387                        // Override install location with flags
12388                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12389                            // Set the flag to install on external media.
12390                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12391                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12392                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12393                            if (DEBUG_EPHEMERAL) {
12394                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12395                            }
12396                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12397                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12398                                    |PackageManager.INSTALL_INTERNAL);
12399                        } else {
12400                            // Make sure the flag for installing on external
12401                            // media is unset
12402                            installFlags |= PackageManager.INSTALL_INTERNAL;
12403                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12404                        }
12405                    }
12406                }
12407            }
12408
12409            final InstallArgs args = createInstallArgs(this);
12410            mArgs = args;
12411
12412            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12413                // TODO: http://b/22976637
12414                // Apps installed for "all" users use the device owner to verify the app
12415                UserHandle verifierUser = getUser();
12416                if (verifierUser == UserHandle.ALL) {
12417                    verifierUser = UserHandle.SYSTEM;
12418                }
12419
12420                /*
12421                 * Determine if we have any installed package verifiers. If we
12422                 * do, then we'll defer to them to verify the packages.
12423                 */
12424                final int requiredUid = mRequiredVerifierPackage == null ? -1
12425                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12426                                verifierUser.getIdentifier());
12427                if (!origin.existing && requiredUid != -1
12428                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12429                    final Intent verification = new Intent(
12430                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12431                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12432                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12433                            PACKAGE_MIME_TYPE);
12434                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12435
12436                    // Query all live verifiers based on current user state
12437                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12438                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12439
12440                    if (DEBUG_VERIFY) {
12441                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12442                                + verification.toString() + " with " + pkgLite.verifiers.length
12443                                + " optional verifiers");
12444                    }
12445
12446                    final int verificationId = mPendingVerificationToken++;
12447
12448                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12449
12450                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12451                            installerPackageName);
12452
12453                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12454                            installFlags);
12455
12456                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12457                            pkgLite.packageName);
12458
12459                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12460                            pkgLite.versionCode);
12461
12462                    if (verificationInfo != null) {
12463                        if (verificationInfo.originatingUri != null) {
12464                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12465                                    verificationInfo.originatingUri);
12466                        }
12467                        if (verificationInfo.referrer != null) {
12468                            verification.putExtra(Intent.EXTRA_REFERRER,
12469                                    verificationInfo.referrer);
12470                        }
12471                        if (verificationInfo.originatingUid >= 0) {
12472                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12473                                    verificationInfo.originatingUid);
12474                        }
12475                        if (verificationInfo.installerUid >= 0) {
12476                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12477                                    verificationInfo.installerUid);
12478                        }
12479                    }
12480
12481                    final PackageVerificationState verificationState = new PackageVerificationState(
12482                            requiredUid, args);
12483
12484                    mPendingVerification.append(verificationId, verificationState);
12485
12486                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12487                            receivers, verificationState);
12488
12489                    /*
12490                     * If any sufficient verifiers were listed in the package
12491                     * manifest, attempt to ask them.
12492                     */
12493                    if (sufficientVerifiers != null) {
12494                        final int N = sufficientVerifiers.size();
12495                        if (N == 0) {
12496                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12497                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12498                        } else {
12499                            for (int i = 0; i < N; i++) {
12500                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12501
12502                                final Intent sufficientIntent = new Intent(verification);
12503                                sufficientIntent.setComponent(verifierComponent);
12504                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12505                            }
12506                        }
12507                    }
12508
12509                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12510                            mRequiredVerifierPackage, receivers);
12511                    if (ret == PackageManager.INSTALL_SUCCEEDED
12512                            && mRequiredVerifierPackage != null) {
12513                        Trace.asyncTraceBegin(
12514                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12515                        /*
12516                         * Send the intent to the required verification agent,
12517                         * but only start the verification timeout after the
12518                         * target BroadcastReceivers have run.
12519                         */
12520                        verification.setComponent(requiredVerifierComponent);
12521                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12522                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12523                                new BroadcastReceiver() {
12524                                    @Override
12525                                    public void onReceive(Context context, Intent intent) {
12526                                        final Message msg = mHandler
12527                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12528                                        msg.arg1 = verificationId;
12529                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12530                                    }
12531                                }, null, 0, null, null);
12532
12533                        /*
12534                         * We don't want the copy to proceed until verification
12535                         * succeeds, so null out this field.
12536                         */
12537                        mArgs = null;
12538                    }
12539                } else {
12540                    /*
12541                     * No package verification is enabled, so immediately start
12542                     * the remote call to initiate copy using temporary file.
12543                     */
12544                    ret = args.copyApk(mContainerService, true);
12545                }
12546            }
12547
12548            mRet = ret;
12549        }
12550
12551        @Override
12552        void handleReturnCode() {
12553            // If mArgs is null, then MCS couldn't be reached. When it
12554            // reconnects, it will try again to install. At that point, this
12555            // will succeed.
12556            if (mArgs != null) {
12557                processPendingInstall(mArgs, mRet);
12558            }
12559        }
12560
12561        @Override
12562        void handleServiceError() {
12563            mArgs = createInstallArgs(this);
12564            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12565        }
12566
12567        public boolean isForwardLocked() {
12568            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12569        }
12570    }
12571
12572    /**
12573     * Used during creation of InstallArgs
12574     *
12575     * @param installFlags package installation flags
12576     * @return true if should be installed on external storage
12577     */
12578    private static boolean installOnExternalAsec(int installFlags) {
12579        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12580            return false;
12581        }
12582        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12583            return true;
12584        }
12585        return false;
12586    }
12587
12588    /**
12589     * Used during creation of InstallArgs
12590     *
12591     * @param installFlags package installation flags
12592     * @return true if should be installed as forward locked
12593     */
12594    private static boolean installForwardLocked(int installFlags) {
12595        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12596    }
12597
12598    private InstallArgs createInstallArgs(InstallParams params) {
12599        if (params.move != null) {
12600            return new MoveInstallArgs(params);
12601        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12602            return new AsecInstallArgs(params);
12603        } else {
12604            return new FileInstallArgs(params);
12605        }
12606    }
12607
12608    /**
12609     * Create args that describe an existing installed package. Typically used
12610     * when cleaning up old installs, or used as a move source.
12611     */
12612    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12613            String resourcePath, String[] instructionSets) {
12614        final boolean isInAsec;
12615        if (installOnExternalAsec(installFlags)) {
12616            /* Apps on SD card are always in ASEC containers. */
12617            isInAsec = true;
12618        } else if (installForwardLocked(installFlags)
12619                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12620            /*
12621             * Forward-locked apps are only in ASEC containers if they're the
12622             * new style
12623             */
12624            isInAsec = true;
12625        } else {
12626            isInAsec = false;
12627        }
12628
12629        if (isInAsec) {
12630            return new AsecInstallArgs(codePath, instructionSets,
12631                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12632        } else {
12633            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12634        }
12635    }
12636
12637    static abstract class InstallArgs {
12638        /** @see InstallParams#origin */
12639        final OriginInfo origin;
12640        /** @see InstallParams#move */
12641        final MoveInfo move;
12642
12643        final IPackageInstallObserver2 observer;
12644        // Always refers to PackageManager flags only
12645        final int installFlags;
12646        final String installerPackageName;
12647        final String volumeUuid;
12648        final UserHandle user;
12649        final String abiOverride;
12650        final String[] installGrantPermissions;
12651        /** If non-null, drop an async trace when the install completes */
12652        final String traceMethod;
12653        final int traceCookie;
12654        final Certificate[][] certificates;
12655
12656        // The list of instruction sets supported by this app. This is currently
12657        // only used during the rmdex() phase to clean up resources. We can get rid of this
12658        // if we move dex files under the common app path.
12659        /* nullable */ String[] instructionSets;
12660
12661        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12662                int installFlags, String installerPackageName, String volumeUuid,
12663                UserHandle user, String[] instructionSets,
12664                String abiOverride, String[] installGrantPermissions,
12665                String traceMethod, int traceCookie, Certificate[][] certificates) {
12666            this.origin = origin;
12667            this.move = move;
12668            this.installFlags = installFlags;
12669            this.observer = observer;
12670            this.installerPackageName = installerPackageName;
12671            this.volumeUuid = volumeUuid;
12672            this.user = user;
12673            this.instructionSets = instructionSets;
12674            this.abiOverride = abiOverride;
12675            this.installGrantPermissions = installGrantPermissions;
12676            this.traceMethod = traceMethod;
12677            this.traceCookie = traceCookie;
12678            this.certificates = certificates;
12679        }
12680
12681        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12682        abstract int doPreInstall(int status);
12683
12684        /**
12685         * Rename package into final resting place. All paths on the given
12686         * scanned package should be updated to reflect the rename.
12687         */
12688        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12689        abstract int doPostInstall(int status, int uid);
12690
12691        /** @see PackageSettingBase#codePathString */
12692        abstract String getCodePath();
12693        /** @see PackageSettingBase#resourcePathString */
12694        abstract String getResourcePath();
12695
12696        // Need installer lock especially for dex file removal.
12697        abstract void cleanUpResourcesLI();
12698        abstract boolean doPostDeleteLI(boolean delete);
12699
12700        /**
12701         * Called before the source arguments are copied. This is used mostly
12702         * for MoveParams when it needs to read the source file to put it in the
12703         * destination.
12704         */
12705        int doPreCopy() {
12706            return PackageManager.INSTALL_SUCCEEDED;
12707        }
12708
12709        /**
12710         * Called after the source arguments are copied. This is used mostly for
12711         * MoveParams when it needs to read the source file to put it in the
12712         * destination.
12713         */
12714        int doPostCopy(int uid) {
12715            return PackageManager.INSTALL_SUCCEEDED;
12716        }
12717
12718        protected boolean isFwdLocked() {
12719            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12720        }
12721
12722        protected boolean isExternalAsec() {
12723            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12724        }
12725
12726        protected boolean isEphemeral() {
12727            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12728        }
12729
12730        UserHandle getUser() {
12731            return user;
12732        }
12733    }
12734
12735    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12736        if (!allCodePaths.isEmpty()) {
12737            if (instructionSets == null) {
12738                throw new IllegalStateException("instructionSet == null");
12739            }
12740            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12741            for (String codePath : allCodePaths) {
12742                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12743                    try {
12744                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12745                    } catch (InstallerException ignored) {
12746                    }
12747                }
12748            }
12749        }
12750    }
12751
12752    /**
12753     * Logic to handle installation of non-ASEC applications, including copying
12754     * and renaming logic.
12755     */
12756    class FileInstallArgs extends InstallArgs {
12757        private File codeFile;
12758        private File resourceFile;
12759
12760        // Example topology:
12761        // /data/app/com.example/base.apk
12762        // /data/app/com.example/split_foo.apk
12763        // /data/app/com.example/lib/arm/libfoo.so
12764        // /data/app/com.example/lib/arm64/libfoo.so
12765        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12766
12767        /** New install */
12768        FileInstallArgs(InstallParams params) {
12769            super(params.origin, params.move, params.observer, params.installFlags,
12770                    params.installerPackageName, params.volumeUuid,
12771                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12772                    params.grantedRuntimePermissions,
12773                    params.traceMethod, params.traceCookie, params.certificates);
12774            if (isFwdLocked()) {
12775                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12776            }
12777        }
12778
12779        /** Existing install */
12780        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12781            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12782                    null, null, null, 0, null /*certificates*/);
12783            this.codeFile = (codePath != null) ? new File(codePath) : null;
12784            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12785        }
12786
12787        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12789            try {
12790                return doCopyApk(imcs, temp);
12791            } finally {
12792                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12793            }
12794        }
12795
12796        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12797            if (origin.staged) {
12798                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12799                codeFile = origin.file;
12800                resourceFile = origin.file;
12801                return PackageManager.INSTALL_SUCCEEDED;
12802            }
12803
12804            try {
12805                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12806                final File tempDir =
12807                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12808                codeFile = tempDir;
12809                resourceFile = tempDir;
12810            } catch (IOException e) {
12811                Slog.w(TAG, "Failed to create copy file: " + e);
12812                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12813            }
12814
12815            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12816                @Override
12817                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12818                    if (!FileUtils.isValidExtFilename(name)) {
12819                        throw new IllegalArgumentException("Invalid filename: " + name);
12820                    }
12821                    try {
12822                        final File file = new File(codeFile, name);
12823                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12824                                O_RDWR | O_CREAT, 0644);
12825                        Os.chmod(file.getAbsolutePath(), 0644);
12826                        return new ParcelFileDescriptor(fd);
12827                    } catch (ErrnoException e) {
12828                        throw new RemoteException("Failed to open: " + e.getMessage());
12829                    }
12830                }
12831            };
12832
12833            int ret = PackageManager.INSTALL_SUCCEEDED;
12834            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12835            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12836                Slog.e(TAG, "Failed to copy package");
12837                return ret;
12838            }
12839
12840            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12841            NativeLibraryHelper.Handle handle = null;
12842            try {
12843                handle = NativeLibraryHelper.Handle.create(codeFile);
12844                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12845                        abiOverride);
12846            } catch (IOException e) {
12847                Slog.e(TAG, "Copying native libraries failed", e);
12848                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12849            } finally {
12850                IoUtils.closeQuietly(handle);
12851            }
12852
12853            return ret;
12854        }
12855
12856        int doPreInstall(int status) {
12857            if (status != PackageManager.INSTALL_SUCCEEDED) {
12858                cleanUp();
12859            }
12860            return status;
12861        }
12862
12863        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12864            if (status != PackageManager.INSTALL_SUCCEEDED) {
12865                cleanUp();
12866                return false;
12867            }
12868
12869            final File targetDir = codeFile.getParentFile();
12870            final File beforeCodeFile = codeFile;
12871            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12872
12873            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12874            try {
12875                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12876            } catch (ErrnoException e) {
12877                Slog.w(TAG, "Failed to rename", e);
12878                return false;
12879            }
12880
12881            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12882                Slog.w(TAG, "Failed to restorecon");
12883                return false;
12884            }
12885
12886            // Reflect the rename internally
12887            codeFile = afterCodeFile;
12888            resourceFile = afterCodeFile;
12889
12890            // Reflect the rename in scanned details
12891            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12892            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12893                    afterCodeFile, pkg.baseCodePath));
12894            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12895                    afterCodeFile, pkg.splitCodePaths));
12896
12897            // Reflect the rename in app info
12898            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12899            pkg.setApplicationInfoCodePath(pkg.codePath);
12900            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12901            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12902            pkg.setApplicationInfoResourcePath(pkg.codePath);
12903            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12904            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12905
12906            return true;
12907        }
12908
12909        int doPostInstall(int status, int uid) {
12910            if (status != PackageManager.INSTALL_SUCCEEDED) {
12911                cleanUp();
12912            }
12913            return status;
12914        }
12915
12916        @Override
12917        String getCodePath() {
12918            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12919        }
12920
12921        @Override
12922        String getResourcePath() {
12923            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12924        }
12925
12926        private boolean cleanUp() {
12927            if (codeFile == null || !codeFile.exists()) {
12928                return false;
12929            }
12930
12931            removeCodePathLI(codeFile);
12932
12933            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12934                resourceFile.delete();
12935            }
12936
12937            return true;
12938        }
12939
12940        void cleanUpResourcesLI() {
12941            // Try enumerating all code paths before deleting
12942            List<String> allCodePaths = Collections.EMPTY_LIST;
12943            if (codeFile != null && codeFile.exists()) {
12944                try {
12945                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12946                    allCodePaths = pkg.getAllCodePaths();
12947                } catch (PackageParserException e) {
12948                    // Ignored; we tried our best
12949                }
12950            }
12951
12952            cleanUp();
12953            removeDexFiles(allCodePaths, instructionSets);
12954        }
12955
12956        boolean doPostDeleteLI(boolean delete) {
12957            // XXX err, shouldn't we respect the delete flag?
12958            cleanUpResourcesLI();
12959            return true;
12960        }
12961    }
12962
12963    private boolean isAsecExternal(String cid) {
12964        final String asecPath = PackageHelper.getSdFilesystem(cid);
12965        return !asecPath.startsWith(mAsecInternalPath);
12966    }
12967
12968    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12969            PackageManagerException {
12970        if (copyRet < 0) {
12971            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12972                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12973                throw new PackageManagerException(copyRet, message);
12974            }
12975        }
12976    }
12977
12978    /**
12979     * Extract the MountService "container ID" from the full code path of an
12980     * .apk.
12981     */
12982    static String cidFromCodePath(String fullCodePath) {
12983        int eidx = fullCodePath.lastIndexOf("/");
12984        String subStr1 = fullCodePath.substring(0, eidx);
12985        int sidx = subStr1.lastIndexOf("/");
12986        return subStr1.substring(sidx+1, eidx);
12987    }
12988
12989    /**
12990     * Logic to handle installation of ASEC applications, including copying and
12991     * renaming logic.
12992     */
12993    class AsecInstallArgs extends InstallArgs {
12994        static final String RES_FILE_NAME = "pkg.apk";
12995        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12996
12997        String cid;
12998        String packagePath;
12999        String resourcePath;
13000
13001        /** New install */
13002        AsecInstallArgs(InstallParams params) {
13003            super(params.origin, params.move, params.observer, params.installFlags,
13004                    params.installerPackageName, params.volumeUuid,
13005                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13006                    params.grantedRuntimePermissions,
13007                    params.traceMethod, params.traceCookie, params.certificates);
13008        }
13009
13010        /** Existing install */
13011        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13012                        boolean isExternal, boolean isForwardLocked) {
13013            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13014              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13015                    instructionSets, null, null, null, 0, null /*certificates*/);
13016            // Hackily pretend we're still looking at a full code path
13017            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13018                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13019            }
13020
13021            // Extract cid from fullCodePath
13022            int eidx = fullCodePath.lastIndexOf("/");
13023            String subStr1 = fullCodePath.substring(0, eidx);
13024            int sidx = subStr1.lastIndexOf("/");
13025            cid = subStr1.substring(sidx+1, eidx);
13026            setMountPath(subStr1);
13027        }
13028
13029        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13030            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13031              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13032                    instructionSets, null, null, null, 0, null /*certificates*/);
13033            this.cid = cid;
13034            setMountPath(PackageHelper.getSdDir(cid));
13035        }
13036
13037        void createCopyFile() {
13038            cid = mInstallerService.allocateExternalStageCidLegacy();
13039        }
13040
13041        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13042            if (origin.staged && origin.cid != null) {
13043                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13044                cid = origin.cid;
13045                setMountPath(PackageHelper.getSdDir(cid));
13046                return PackageManager.INSTALL_SUCCEEDED;
13047            }
13048
13049            if (temp) {
13050                createCopyFile();
13051            } else {
13052                /*
13053                 * Pre-emptively destroy the container since it's destroyed if
13054                 * copying fails due to it existing anyway.
13055                 */
13056                PackageHelper.destroySdDir(cid);
13057            }
13058
13059            final String newMountPath = imcs.copyPackageToContainer(
13060                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13061                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13062
13063            if (newMountPath != null) {
13064                setMountPath(newMountPath);
13065                return PackageManager.INSTALL_SUCCEEDED;
13066            } else {
13067                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13068            }
13069        }
13070
13071        @Override
13072        String getCodePath() {
13073            return packagePath;
13074        }
13075
13076        @Override
13077        String getResourcePath() {
13078            return resourcePath;
13079        }
13080
13081        int doPreInstall(int status) {
13082            if (status != PackageManager.INSTALL_SUCCEEDED) {
13083                // Destroy container
13084                PackageHelper.destroySdDir(cid);
13085            } else {
13086                boolean mounted = PackageHelper.isContainerMounted(cid);
13087                if (!mounted) {
13088                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13089                            Process.SYSTEM_UID);
13090                    if (newMountPath != null) {
13091                        setMountPath(newMountPath);
13092                    } else {
13093                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13094                    }
13095                }
13096            }
13097            return status;
13098        }
13099
13100        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13101            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13102            String newMountPath = null;
13103            if (PackageHelper.isContainerMounted(cid)) {
13104                // Unmount the container
13105                if (!PackageHelper.unMountSdDir(cid)) {
13106                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13107                    return false;
13108                }
13109            }
13110            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13111                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13112                        " which might be stale. Will try to clean up.");
13113                // Clean up the stale container and proceed to recreate.
13114                if (!PackageHelper.destroySdDir(newCacheId)) {
13115                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13116                    return false;
13117                }
13118                // Successfully cleaned up stale container. Try to rename again.
13119                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13120                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13121                            + " inspite of cleaning it up.");
13122                    return false;
13123                }
13124            }
13125            if (!PackageHelper.isContainerMounted(newCacheId)) {
13126                Slog.w(TAG, "Mounting container " + newCacheId);
13127                newMountPath = PackageHelper.mountSdDir(newCacheId,
13128                        getEncryptKey(), Process.SYSTEM_UID);
13129            } else {
13130                newMountPath = PackageHelper.getSdDir(newCacheId);
13131            }
13132            if (newMountPath == null) {
13133                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13134                return false;
13135            }
13136            Log.i(TAG, "Succesfully renamed " + cid +
13137                    " to " + newCacheId +
13138                    " at new path: " + newMountPath);
13139            cid = newCacheId;
13140
13141            final File beforeCodeFile = new File(packagePath);
13142            setMountPath(newMountPath);
13143            final File afterCodeFile = new File(packagePath);
13144
13145            // Reflect the rename in scanned details
13146            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13147            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13148                    afterCodeFile, pkg.baseCodePath));
13149            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13150                    afterCodeFile, pkg.splitCodePaths));
13151
13152            // Reflect the rename in app info
13153            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13154            pkg.setApplicationInfoCodePath(pkg.codePath);
13155            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13156            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13157            pkg.setApplicationInfoResourcePath(pkg.codePath);
13158            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13159            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13160
13161            return true;
13162        }
13163
13164        private void setMountPath(String mountPath) {
13165            final File mountFile = new File(mountPath);
13166
13167            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13168            if (monolithicFile.exists()) {
13169                packagePath = monolithicFile.getAbsolutePath();
13170                if (isFwdLocked()) {
13171                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13172                } else {
13173                    resourcePath = packagePath;
13174                }
13175            } else {
13176                packagePath = mountFile.getAbsolutePath();
13177                resourcePath = packagePath;
13178            }
13179        }
13180
13181        int doPostInstall(int status, int uid) {
13182            if (status != PackageManager.INSTALL_SUCCEEDED) {
13183                cleanUp();
13184            } else {
13185                final int groupOwner;
13186                final String protectedFile;
13187                if (isFwdLocked()) {
13188                    groupOwner = UserHandle.getSharedAppGid(uid);
13189                    protectedFile = RES_FILE_NAME;
13190                } else {
13191                    groupOwner = -1;
13192                    protectedFile = null;
13193                }
13194
13195                if (uid < Process.FIRST_APPLICATION_UID
13196                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13197                    Slog.e(TAG, "Failed to finalize " + cid);
13198                    PackageHelper.destroySdDir(cid);
13199                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13200                }
13201
13202                boolean mounted = PackageHelper.isContainerMounted(cid);
13203                if (!mounted) {
13204                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13205                }
13206            }
13207            return status;
13208        }
13209
13210        private void cleanUp() {
13211            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13212
13213            // Destroy secure container
13214            PackageHelper.destroySdDir(cid);
13215        }
13216
13217        private List<String> getAllCodePaths() {
13218            final File codeFile = new File(getCodePath());
13219            if (codeFile != null && codeFile.exists()) {
13220                try {
13221                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13222                    return pkg.getAllCodePaths();
13223                } catch (PackageParserException e) {
13224                    // Ignored; we tried our best
13225                }
13226            }
13227            return Collections.EMPTY_LIST;
13228        }
13229
13230        void cleanUpResourcesLI() {
13231            // Enumerate all code paths before deleting
13232            cleanUpResourcesLI(getAllCodePaths());
13233        }
13234
13235        private void cleanUpResourcesLI(List<String> allCodePaths) {
13236            cleanUp();
13237            removeDexFiles(allCodePaths, instructionSets);
13238        }
13239
13240        String getPackageName() {
13241            return getAsecPackageName(cid);
13242        }
13243
13244        boolean doPostDeleteLI(boolean delete) {
13245            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13246            final List<String> allCodePaths = getAllCodePaths();
13247            boolean mounted = PackageHelper.isContainerMounted(cid);
13248            if (mounted) {
13249                // Unmount first
13250                if (PackageHelper.unMountSdDir(cid)) {
13251                    mounted = false;
13252                }
13253            }
13254            if (!mounted && delete) {
13255                cleanUpResourcesLI(allCodePaths);
13256            }
13257            return !mounted;
13258        }
13259
13260        @Override
13261        int doPreCopy() {
13262            if (isFwdLocked()) {
13263                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13264                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13265                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13266                }
13267            }
13268
13269            return PackageManager.INSTALL_SUCCEEDED;
13270        }
13271
13272        @Override
13273        int doPostCopy(int uid) {
13274            if (isFwdLocked()) {
13275                if (uid < Process.FIRST_APPLICATION_UID
13276                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13277                                RES_FILE_NAME)) {
13278                    Slog.e(TAG, "Failed to finalize " + cid);
13279                    PackageHelper.destroySdDir(cid);
13280                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13281                }
13282            }
13283
13284            return PackageManager.INSTALL_SUCCEEDED;
13285        }
13286    }
13287
13288    /**
13289     * Logic to handle movement of existing installed applications.
13290     */
13291    class MoveInstallArgs extends InstallArgs {
13292        private File codeFile;
13293        private File resourceFile;
13294
13295        /** New install */
13296        MoveInstallArgs(InstallParams params) {
13297            super(params.origin, params.move, params.observer, params.installFlags,
13298                    params.installerPackageName, params.volumeUuid,
13299                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13300                    params.grantedRuntimePermissions,
13301                    params.traceMethod, params.traceCookie, params.certificates);
13302        }
13303
13304        int copyApk(IMediaContainerService imcs, boolean temp) {
13305            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13306                    + move.fromUuid + " to " + move.toUuid);
13307            synchronized (mInstaller) {
13308                try {
13309                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13310                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13311                } catch (InstallerException e) {
13312                    Slog.w(TAG, "Failed to move app", e);
13313                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13314                }
13315            }
13316
13317            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13318            resourceFile = codeFile;
13319            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13320
13321            return PackageManager.INSTALL_SUCCEEDED;
13322        }
13323
13324        int doPreInstall(int status) {
13325            if (status != PackageManager.INSTALL_SUCCEEDED) {
13326                cleanUp(move.toUuid);
13327            }
13328            return status;
13329        }
13330
13331        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13332            if (status != PackageManager.INSTALL_SUCCEEDED) {
13333                cleanUp(move.toUuid);
13334                return false;
13335            }
13336
13337            // Reflect the move in app info
13338            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13339            pkg.setApplicationInfoCodePath(pkg.codePath);
13340            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13341            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13342            pkg.setApplicationInfoResourcePath(pkg.codePath);
13343            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13344            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13345
13346            return true;
13347        }
13348
13349        int doPostInstall(int status, int uid) {
13350            if (status == PackageManager.INSTALL_SUCCEEDED) {
13351                cleanUp(move.fromUuid);
13352            } else {
13353                cleanUp(move.toUuid);
13354            }
13355            return status;
13356        }
13357
13358        @Override
13359        String getCodePath() {
13360            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13361        }
13362
13363        @Override
13364        String getResourcePath() {
13365            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13366        }
13367
13368        private boolean cleanUp(String volumeUuid) {
13369            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13370                    move.dataAppName);
13371            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13372            synchronized (mInstallLock) {
13373                // Clean up both app data and code
13374                // All package moves are frozen until finished
13375                try {
13376                    mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL,
13377                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13378                } catch (InstallerException e) {
13379                    Slog.w(TAG, String.valueOf(e));
13380                }
13381                removeCodePathLI(codeFile);
13382            }
13383            return true;
13384        }
13385
13386        void cleanUpResourcesLI() {
13387            throw new UnsupportedOperationException();
13388        }
13389
13390        boolean doPostDeleteLI(boolean delete) {
13391            throw new UnsupportedOperationException();
13392        }
13393    }
13394
13395    static String getAsecPackageName(String packageCid) {
13396        int idx = packageCid.lastIndexOf("-");
13397        if (idx == -1) {
13398            return packageCid;
13399        }
13400        return packageCid.substring(0, idx);
13401    }
13402
13403    // Utility method used to create code paths based on package name and available index.
13404    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13405        String idxStr = "";
13406        int idx = 1;
13407        // Fall back to default value of idx=1 if prefix is not
13408        // part of oldCodePath
13409        if (oldCodePath != null) {
13410            String subStr = oldCodePath;
13411            // Drop the suffix right away
13412            if (suffix != null && subStr.endsWith(suffix)) {
13413                subStr = subStr.substring(0, subStr.length() - suffix.length());
13414            }
13415            // If oldCodePath already contains prefix find out the
13416            // ending index to either increment or decrement.
13417            int sidx = subStr.lastIndexOf(prefix);
13418            if (sidx != -1) {
13419                subStr = subStr.substring(sidx + prefix.length());
13420                if (subStr != null) {
13421                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13422                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13423                    }
13424                    try {
13425                        idx = Integer.parseInt(subStr);
13426                        if (idx <= 1) {
13427                            idx++;
13428                        } else {
13429                            idx--;
13430                        }
13431                    } catch(NumberFormatException e) {
13432                    }
13433                }
13434            }
13435        }
13436        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13437        return prefix + idxStr;
13438    }
13439
13440    private File getNextCodePath(File targetDir, String packageName) {
13441        int suffix = 1;
13442        File result;
13443        do {
13444            result = new File(targetDir, packageName + "-" + suffix);
13445            suffix++;
13446        } while (result.exists());
13447        return result;
13448    }
13449
13450    // Utility method that returns the relative package path with respect
13451    // to the installation directory. Like say for /data/data/com.test-1.apk
13452    // string com.test-1 is returned.
13453    static String deriveCodePathName(String codePath) {
13454        if (codePath == null) {
13455            return null;
13456        }
13457        final File codeFile = new File(codePath);
13458        final String name = codeFile.getName();
13459        if (codeFile.isDirectory()) {
13460            return name;
13461        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13462            final int lastDot = name.lastIndexOf('.');
13463            return name.substring(0, lastDot);
13464        } else {
13465            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13466            return null;
13467        }
13468    }
13469
13470    static class PackageInstalledInfo {
13471        String name;
13472        int uid;
13473        // The set of users that originally had this package installed.
13474        int[] origUsers;
13475        // The set of users that now have this package installed.
13476        int[] newUsers;
13477        PackageParser.Package pkg;
13478        int returnCode;
13479        String returnMsg;
13480        PackageRemovedInfo removedInfo;
13481        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13482
13483        public void setError(int code, String msg) {
13484            setReturnCode(code);
13485            setReturnMessage(msg);
13486            Slog.w(TAG, msg);
13487        }
13488
13489        public void setError(String msg, PackageParserException e) {
13490            setReturnCode(e.error);
13491            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13492            Slog.w(TAG, msg, e);
13493        }
13494
13495        public void setError(String msg, PackageManagerException e) {
13496            returnCode = e.error;
13497            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13498            Slog.w(TAG, msg, e);
13499        }
13500
13501        public void setReturnCode(int returnCode) {
13502            this.returnCode = returnCode;
13503            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13504            for (int i = 0; i < childCount; i++) {
13505                addedChildPackages.valueAt(i).returnCode = returnCode;
13506            }
13507        }
13508
13509        private void setReturnMessage(String returnMsg) {
13510            this.returnMsg = returnMsg;
13511            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13512            for (int i = 0; i < childCount; i++) {
13513                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13514            }
13515        }
13516
13517        // In some error cases we want to convey more info back to the observer
13518        String origPackage;
13519        String origPermission;
13520    }
13521
13522    /*
13523     * Install a non-existing package.
13524     */
13525    private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags,
13526            UserHandle user, String installerPackageName, String volumeUuid,
13527            PackageInstalledInfo res) {
13528        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13529
13530        // Remember this for later, in case we need to rollback this install
13531        String pkgName = pkg.packageName;
13532
13533        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13534
13535        synchronized(mPackages) {
13536            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13537                // A package with the same name is already installed, though
13538                // it has been renamed to an older name.  The package we
13539                // are trying to install should be installed as an update to
13540                // the existing one, but that has not been requested, so bail.
13541                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13542                        + " without first uninstalling package running as "
13543                        + mSettings.mRenamedPackages.get(pkgName));
13544                return;
13545            }
13546            if (mPackages.containsKey(pkgName)) {
13547                // Don't allow installation over an existing package with the same name.
13548                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13549                        + " without first uninstalling.");
13550                return;
13551            }
13552        }
13553
13554        try {
13555            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13556                    System.currentTimeMillis(), user);
13557
13558            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13559
13560            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13561                prepareAppDataAfterInstallLIF(newPackage);
13562
13563            } else {
13564                // Remove package from internal structures, but keep around any
13565                // data that might have already existed
13566                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13567                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13568            }
13569        } catch (PackageManagerException e) {
13570            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13571        }
13572
13573        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13574    }
13575
13576    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13577        // Can't rotate keys during boot or if sharedUser.
13578        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13579                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13580            return false;
13581        }
13582        // app is using upgradeKeySets; make sure all are valid
13583        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13584        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13585        for (int i = 0; i < upgradeKeySets.length; i++) {
13586            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13587                Slog.wtf(TAG, "Package "
13588                         + (oldPs.name != null ? oldPs.name : "<null>")
13589                         + " contains upgrade-key-set reference to unknown key-set: "
13590                         + upgradeKeySets[i]
13591                         + " reverting to signatures check.");
13592                return false;
13593            }
13594        }
13595        return true;
13596    }
13597
13598    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13599        // Upgrade keysets are being used.  Determine if new package has a superset of the
13600        // required keys.
13601        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13602        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13603        for (int i = 0; i < upgradeKeySets.length; i++) {
13604            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13605            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13606                return true;
13607            }
13608        }
13609        return false;
13610    }
13611
13612    private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags,
13613            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13614        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13615
13616        final PackageParser.Package oldPackage;
13617        final String pkgName = pkg.packageName;
13618        final int[] allUsers;
13619
13620        // First find the old package info and check signatures
13621        synchronized(mPackages) {
13622            oldPackage = mPackages.get(pkgName);
13623            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13624            if (isEphemeral && !oldIsEphemeral) {
13625                // can't downgrade from full to ephemeral
13626                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13627                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13628                return;
13629            }
13630            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13631            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13632            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13633                if (!checkUpgradeKeySetLP(ps, pkg)) {
13634                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13635                            "New package not signed by keys specified by upgrade-keysets: "
13636                                    + pkgName);
13637                    return;
13638                }
13639            } else {
13640                // default to original signature matching
13641                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13642                        != PackageManager.SIGNATURE_MATCH) {
13643                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13644                            "New package has a different signature: " + pkgName);
13645                    return;
13646                }
13647            }
13648
13649            // In case of rollback, remember per-user/profile install state
13650            allUsers = sUserManager.getUserIds();
13651        }
13652
13653        // Update what is removed
13654        res.removedInfo = new PackageRemovedInfo();
13655        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13656        res.removedInfo.removedPackage = oldPackage.packageName;
13657        res.removedInfo.isUpdate = true;
13658        final int childCount = (oldPackage.childPackages != null)
13659                ? oldPackage.childPackages.size() : 0;
13660        for (int i = 0; i < childCount; i++) {
13661            boolean childPackageUpdated = false;
13662            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13663            if (res.addedChildPackages != null) {
13664                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13665                if (childRes != null) {
13666                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13667                    childRes.removedInfo.removedPackage = childPkg.packageName;
13668                    childRes.removedInfo.isUpdate = true;
13669                    childPackageUpdated = true;
13670                }
13671            }
13672            if (!childPackageUpdated) {
13673                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13674                childRemovedRes.removedPackage = childPkg.packageName;
13675                childRemovedRes.isUpdate = false;
13676                childRemovedRes.dataRemoved = true;
13677                synchronized (mPackages) {
13678                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13679                    if (childPs != null) {
13680                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13681                    }
13682                }
13683                if (res.removedInfo.removedChildPackages == null) {
13684                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13685                }
13686                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13687            }
13688        }
13689
13690        boolean sysPkg = (isSystemApp(oldPackage));
13691        if (sysPkg) {
13692            replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
13693                    user, allUsers, installerPackageName, res);
13694        } else {
13695            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
13696                    user, allUsers, installerPackageName, res);
13697        }
13698    }
13699
13700    public List<String> getPreviousCodePaths(String packageName) {
13701        final PackageSetting ps = mSettings.mPackages.get(packageName);
13702        final List<String> result = new ArrayList<String>();
13703        if (ps != null && ps.oldCodePaths != null) {
13704            result.addAll(ps.oldCodePaths);
13705        }
13706        return result;
13707    }
13708
13709    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13710            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13711            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13712        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13713                + deletedPackage);
13714
13715        String pkgName = deletedPackage.packageName;
13716        boolean deletedPkg = true;
13717        boolean addedPkg = false;
13718        boolean updatedSettings = false;
13719        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13720        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13721                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13722
13723        final long origUpdateTime = (pkg.mExtras != null)
13724                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13725
13726        // First delete the existing package while retaining the data directory
13727        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13728                res.removedInfo, true, pkg)) {
13729            // If the existing package wasn't successfully deleted
13730            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13731            deletedPkg = false;
13732        } else {
13733            // Successfully deleted the old package; proceed with replace.
13734
13735            // If deleted package lived in a container, give users a chance to
13736            // relinquish resources before killing.
13737            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13738                if (DEBUG_INSTALL) {
13739                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13740                }
13741                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13742                final ArrayList<String> pkgList = new ArrayList<String>(1);
13743                pkgList.add(deletedPackage.applicationInfo.packageName);
13744                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13745            }
13746
13747            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13748                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13749            clearAppProfilesLIF(pkg);
13750
13751            try {
13752                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13753                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13754                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13755
13756                // Update the in-memory copy of the previous code paths.
13757                PackageSetting ps = mSettings.mPackages.get(pkgName);
13758                if (!killApp) {
13759                    if (ps.oldCodePaths == null) {
13760                        ps.oldCodePaths = new ArraySet<>();
13761                    }
13762                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13763                    if (deletedPackage.splitCodePaths != null) {
13764                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13765                    }
13766                } else {
13767                    ps.oldCodePaths = null;
13768                }
13769                if (ps.childPackageNames != null) {
13770                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13771                        final String childPkgName = ps.childPackageNames.get(i);
13772                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13773                        childPs.oldCodePaths = ps.oldCodePaths;
13774                    }
13775                }
13776                prepareAppDataAfterInstallLIF(newPackage);
13777                addedPkg = true;
13778            } catch (PackageManagerException e) {
13779                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13780            }
13781        }
13782
13783        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13784            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13785
13786            // Revert all internal state mutations and added folders for the failed install
13787            if (addedPkg) {
13788                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13789                        res.removedInfo, true, null);
13790            }
13791
13792            // Restore the old package
13793            if (deletedPkg) {
13794                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13795                File restoreFile = new File(deletedPackage.codePath);
13796                // Parse old package
13797                boolean oldExternal = isExternal(deletedPackage);
13798                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13799                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13800                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13801                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13802                try {
13803                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13804                            null);
13805                } catch (PackageManagerException e) {
13806                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13807                            + e.getMessage());
13808                    return;
13809                }
13810
13811                synchronized (mPackages) {
13812                    // Ensure the installer package name up to date
13813                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13814
13815                    // Update permissions for restored package
13816                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13817
13818                    mSettings.writeLPr();
13819                }
13820
13821                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13822            }
13823        } else {
13824            synchronized (mPackages) {
13825                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13826                if (ps != null) {
13827                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13828                    if (res.removedInfo.removedChildPackages != null) {
13829                        final int childCount = res.removedInfo.removedChildPackages.size();
13830                        // Iterate in reverse as we may modify the collection
13831                        for (int i = childCount - 1; i >= 0; i--) {
13832                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13833                            if (res.addedChildPackages.containsKey(childPackageName)) {
13834                                res.removedInfo.removedChildPackages.removeAt(i);
13835                            } else {
13836                                PackageRemovedInfo childInfo = res.removedInfo
13837                                        .removedChildPackages.valueAt(i);
13838                                childInfo.removedForAllUsers = mPackages.get(
13839                                        childInfo.removedPackage) == null;
13840                            }
13841                        }
13842                    }
13843                }
13844            }
13845        }
13846    }
13847
13848    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
13849            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13850            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13851        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13852                + ", old=" + deletedPackage);
13853
13854        final boolean disabledSystem;
13855
13856        // Set the system/privileged flags as needed
13857        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13858        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13859                != 0) {
13860            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13861        }
13862
13863        // Remove existing system package
13864        removePackageLI(deletedPackage, true);
13865
13866        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13867        if (!disabledSystem) {
13868            // We didn't need to disable the .apk as a current system package,
13869            // which means we are replacing another update that is already
13870            // installed.  We need to make sure to delete the older one's .apk.
13871            res.removedInfo.args = createInstallArgsForExisting(0,
13872                    deletedPackage.applicationInfo.getCodePath(),
13873                    deletedPackage.applicationInfo.getResourcePath(),
13874                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13875        } else {
13876            res.removedInfo.args = null;
13877        }
13878
13879        // Successfully disabled the old package. Now proceed with re-installation
13880        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13881                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13882        clearAppProfilesLIF(pkg);
13883
13884        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13885        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13886                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13887
13888        PackageParser.Package newPackage = null;
13889        try {
13890            // Add the package to the internal data structures
13891            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13892
13893            // Set the update and install times
13894            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13895            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13896                    System.currentTimeMillis());
13897
13898            // Check for shared user id changes
13899            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13900                    deletedPackage, newPackage);
13901            if (invalidPackageName != null) {
13902                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13903                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13904                                + " to " + invalidPackageName);
13905            }
13906
13907            // Update the package dynamic state if succeeded
13908            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13909                // Now that the install succeeded make sure we remove data
13910                // directories for any child package the update removed.
13911                final int deletedChildCount = (deletedPackage.childPackages != null)
13912                        ? deletedPackage.childPackages.size() : 0;
13913                final int newChildCount = (newPackage.childPackages != null)
13914                        ? newPackage.childPackages.size() : 0;
13915                for (int i = 0; i < deletedChildCount; i++) {
13916                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13917                    boolean childPackageDeleted = true;
13918                    for (int j = 0; j < newChildCount; j++) {
13919                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13920                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13921                            childPackageDeleted = false;
13922                            break;
13923                        }
13924                    }
13925                    if (childPackageDeleted) {
13926                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13927                                deletedChildPkg.packageName);
13928                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13929                            PackageRemovedInfo removedChildRes = res.removedInfo
13930                                    .removedChildPackages.get(deletedChildPkg.packageName);
13931                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
13932                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13933                        }
13934                    }
13935                }
13936
13937                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13938                prepareAppDataAfterInstallLIF(newPackage);
13939            }
13940        } catch (PackageManagerException e) {
13941            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13942            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13943        }
13944
13945        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13946            // Re installation failed. Restore old information
13947            // Remove new pkg information
13948            if (newPackage != null) {
13949                removeInstalledPackageLI(newPackage, true);
13950            }
13951            // Add back the old system package
13952            try {
13953                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13954            } catch (PackageManagerException e) {
13955                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13956            }
13957
13958            synchronized (mPackages) {
13959                if (disabledSystem) {
13960                    enableSystemPackageLPw(deletedPackage);
13961                }
13962
13963                // Ensure the installer package name up to date
13964                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13965
13966                // Update permissions for restored package
13967                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13968
13969                mSettings.writeLPr();
13970            }
13971
13972            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13973                    + " after failed upgrade");
13974        }
13975    }
13976
13977    /**
13978     * Checks whether the parent or any of the child packages have a change shared
13979     * user. For a package to be a valid update the shred users of the parent and
13980     * the children should match. We may later support changing child shared users.
13981     * @param oldPkg The updated package.
13982     * @param newPkg The update package.
13983     * @return The shared user that change between the versions.
13984     */
13985    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13986            PackageParser.Package newPkg) {
13987        // Check parent shared user
13988        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13989            return newPkg.packageName;
13990        }
13991        // Check child shared users
13992        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13993        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13994        for (int i = 0; i < newChildCount; i++) {
13995            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13996            // If this child was present, did it have the same shared user?
13997            for (int j = 0; j < oldChildCount; j++) {
13998                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13999                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14000                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14001                    return newChildPkg.packageName;
14002                }
14003            }
14004        }
14005        return null;
14006    }
14007
14008    private void removeNativeBinariesLI(PackageSetting ps) {
14009        // Remove the lib path for the parent package
14010        if (ps != null) {
14011            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14012            // Remove the lib path for the child packages
14013            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14014            for (int i = 0; i < childCount; i++) {
14015                PackageSetting childPs = null;
14016                synchronized (mPackages) {
14017                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14018                }
14019                if (childPs != null) {
14020                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14021                            .legacyNativeLibraryPathString);
14022                }
14023            }
14024        }
14025    }
14026
14027    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14028        // Enable the parent package
14029        mSettings.enableSystemPackageLPw(pkg.packageName);
14030        // Enable the child packages
14031        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14032        for (int i = 0; i < childCount; i++) {
14033            PackageParser.Package childPkg = pkg.childPackages.get(i);
14034            mSettings.enableSystemPackageLPw(childPkg.packageName);
14035        }
14036    }
14037
14038    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14039            PackageParser.Package newPkg) {
14040        // Disable the parent package (parent always replaced)
14041        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14042        // Disable the child packages
14043        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14044        for (int i = 0; i < childCount; i++) {
14045            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14046            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14047            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14048        }
14049        return disabled;
14050    }
14051
14052    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14053            String installerPackageName) {
14054        // Enable the parent package
14055        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14056        // Enable the child packages
14057        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14058        for (int i = 0; i < childCount; i++) {
14059            PackageParser.Package childPkg = pkg.childPackages.get(i);
14060            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14061        }
14062    }
14063
14064    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14065        // Collect all used permissions in the UID
14066        ArraySet<String> usedPermissions = new ArraySet<>();
14067        final int packageCount = su.packages.size();
14068        for (int i = 0; i < packageCount; i++) {
14069            PackageSetting ps = su.packages.valueAt(i);
14070            if (ps.pkg == null) {
14071                continue;
14072            }
14073            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14074            for (int j = 0; j < requestedPermCount; j++) {
14075                String permission = ps.pkg.requestedPermissions.get(j);
14076                BasePermission bp = mSettings.mPermissions.get(permission);
14077                if (bp != null) {
14078                    usedPermissions.add(permission);
14079                }
14080            }
14081        }
14082
14083        PermissionsState permissionsState = su.getPermissionsState();
14084        // Prune install permissions
14085        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14086        final int installPermCount = installPermStates.size();
14087        for (int i = installPermCount - 1; i >= 0;  i--) {
14088            PermissionState permissionState = installPermStates.get(i);
14089            if (!usedPermissions.contains(permissionState.getName())) {
14090                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14091                if (bp != null) {
14092                    permissionsState.revokeInstallPermission(bp);
14093                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14094                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14095                }
14096            }
14097        }
14098
14099        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14100
14101        // Prune runtime permissions
14102        for (int userId : allUserIds) {
14103            List<PermissionState> runtimePermStates = permissionsState
14104                    .getRuntimePermissionStates(userId);
14105            final int runtimePermCount = runtimePermStates.size();
14106            for (int i = runtimePermCount - 1; i >= 0; i--) {
14107                PermissionState permissionState = runtimePermStates.get(i);
14108                if (!usedPermissions.contains(permissionState.getName())) {
14109                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14110                    if (bp != null) {
14111                        permissionsState.revokeRuntimePermission(bp, userId);
14112                        permissionsState.updatePermissionFlags(bp, userId,
14113                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14114                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14115                                runtimePermissionChangedUserIds, userId);
14116                    }
14117                }
14118            }
14119        }
14120
14121        return runtimePermissionChangedUserIds;
14122    }
14123
14124    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14125            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14126        // Update the parent package setting
14127        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14128                res, user);
14129        // Update the child packages setting
14130        final int childCount = (newPackage.childPackages != null)
14131                ? newPackage.childPackages.size() : 0;
14132        for (int i = 0; i < childCount; i++) {
14133            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14134            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14135            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14136                    childRes.origUsers, childRes, user);
14137        }
14138    }
14139
14140    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14141            String installerPackageName, int[] allUsers, int[] installedForUsers,
14142            PackageInstalledInfo res, UserHandle user) {
14143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14144
14145        String pkgName = newPackage.packageName;
14146        synchronized (mPackages) {
14147            //write settings. the installStatus will be incomplete at this stage.
14148            //note that the new package setting would have already been
14149            //added to mPackages. It hasn't been persisted yet.
14150            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14151            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14152            mSettings.writeLPr();
14153            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14154        }
14155
14156        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14157        synchronized (mPackages) {
14158            updatePermissionsLPw(newPackage.packageName, newPackage,
14159                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14160                            ? UPDATE_PERMISSIONS_ALL : 0));
14161            // For system-bundled packages, we assume that installing an upgraded version
14162            // of the package implies that the user actually wants to run that new code,
14163            // so we enable the package.
14164            PackageSetting ps = mSettings.mPackages.get(pkgName);
14165            final int userId = user.getIdentifier();
14166            if (ps != null) {
14167                if (isSystemApp(newPackage)) {
14168                    if (DEBUG_INSTALL) {
14169                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14170                    }
14171                    // Enable system package for requested users
14172                    if (res.origUsers != null) {
14173                        for (int origUserId : res.origUsers) {
14174                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14175                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14176                                        origUserId, installerPackageName);
14177                            }
14178                        }
14179                    }
14180                    // Also convey the prior install/uninstall state
14181                    if (allUsers != null && installedForUsers != null) {
14182                        for (int currentUserId : allUsers) {
14183                            final boolean installed = ArrayUtils.contains(
14184                                    installedForUsers, currentUserId);
14185                            if (DEBUG_INSTALL) {
14186                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14187                            }
14188                            ps.setInstalled(installed, currentUserId);
14189                        }
14190                        // these install state changes will be persisted in the
14191                        // upcoming call to mSettings.writeLPr().
14192                    }
14193                }
14194                // It's implied that when a user requests installation, they want the app to be
14195                // installed and enabled.
14196                if (userId != UserHandle.USER_ALL) {
14197                    ps.setInstalled(true, userId);
14198                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14199                }
14200            }
14201            res.name = pkgName;
14202            res.uid = newPackage.applicationInfo.uid;
14203            res.pkg = newPackage;
14204            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14205            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14206            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14207            //to update install status
14208            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14209            mSettings.writeLPr();
14210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14211        }
14212
14213        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14214    }
14215
14216    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14217        try {
14218            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14219            installPackageLI(args, res);
14220        } finally {
14221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14222        }
14223    }
14224
14225    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14226        final int installFlags = args.installFlags;
14227        final String installerPackageName = args.installerPackageName;
14228        final String volumeUuid = args.volumeUuid;
14229        final File tmpPackageFile = new File(args.getCodePath());
14230        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14231        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14232                || (args.volumeUuid != null));
14233        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14234        boolean replace = false;
14235        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14236        if (args.move != null) {
14237            // moving a complete application; perform an initial scan on the new install location
14238            scanFlags |= SCAN_INITIAL;
14239        }
14240        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14241            scanFlags |= SCAN_DONT_KILL_APP;
14242        }
14243
14244        // Result object to be returned
14245        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14246
14247        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14248
14249        // Sanity check
14250        if (ephemeral && (forwardLocked || onExternal)) {
14251            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14252                    + " external=" + onExternal);
14253            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14254            return;
14255        }
14256
14257        // Retrieve PackageSettings and parse package
14258        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14259                | PackageParser.PARSE_ENFORCE_CODE
14260                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14261                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14262                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14263        PackageParser pp = new PackageParser();
14264        pp.setSeparateProcesses(mSeparateProcesses);
14265        pp.setDisplayMetrics(mMetrics);
14266
14267        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14268        final PackageParser.Package pkg;
14269        try {
14270            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14271        } catch (PackageParserException e) {
14272            res.setError("Failed parse during installPackageLI", e);
14273            return;
14274        } finally {
14275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14276        }
14277
14278        // If we are installing a clustered package add results for the children
14279        if (pkg.childPackages != null) {
14280            synchronized (mPackages) {
14281                final int childCount = pkg.childPackages.size();
14282                for (int i = 0; i < childCount; i++) {
14283                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14284                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14285                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14286                    childRes.pkg = childPkg;
14287                    childRes.name = childPkg.packageName;
14288                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14289                    if (childPs != null) {
14290                        childRes.origUsers = childPs.queryInstalledUsers(
14291                                sUserManager.getUserIds(), true);
14292                    }
14293                    if ((mPackages.containsKey(childPkg.packageName))) {
14294                        childRes.removedInfo = new PackageRemovedInfo();
14295                        childRes.removedInfo.removedPackage = childPkg.packageName;
14296                    }
14297                    if (res.addedChildPackages == null) {
14298                        res.addedChildPackages = new ArrayMap<>();
14299                    }
14300                    res.addedChildPackages.put(childPkg.packageName, childRes);
14301                }
14302            }
14303        }
14304
14305        // If package doesn't declare API override, mark that we have an install
14306        // time CPU ABI override.
14307        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14308            pkg.cpuAbiOverride = args.abiOverride;
14309        }
14310
14311        String pkgName = res.name = pkg.packageName;
14312        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14313            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14314                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14315                return;
14316            }
14317        }
14318
14319        try {
14320            // either use what we've been given or parse directly from the APK
14321            if (args.certificates != null) {
14322                try {
14323                    PackageParser.populateCertificates(pkg, args.certificates);
14324                } catch (PackageParserException e) {
14325                    // there was something wrong with the certificates we were given;
14326                    // try to pull them from the APK
14327                    PackageParser.collectCertificates(pkg, parseFlags);
14328                }
14329            } else {
14330                PackageParser.collectCertificates(pkg, parseFlags);
14331            }
14332        } catch (PackageParserException e) {
14333            res.setError("Failed collect during installPackageLI", e);
14334            return;
14335        }
14336
14337        // Get rid of all references to package scan path via parser.
14338        pp = null;
14339        String oldCodePath = null;
14340        boolean systemApp = false;
14341        synchronized (mPackages) {
14342            // Check if installing already existing package
14343            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14344                String oldName = mSettings.mRenamedPackages.get(pkgName);
14345                if (pkg.mOriginalPackages != null
14346                        && pkg.mOriginalPackages.contains(oldName)
14347                        && mPackages.containsKey(oldName)) {
14348                    // This package is derived from an original package,
14349                    // and this device has been updating from that original
14350                    // name.  We must continue using the original name, so
14351                    // rename the new package here.
14352                    pkg.setPackageName(oldName);
14353                    pkgName = pkg.packageName;
14354                    replace = true;
14355                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14356                            + oldName + " pkgName=" + pkgName);
14357                } else if (mPackages.containsKey(pkgName)) {
14358                    // This package, under its official name, already exists
14359                    // on the device; we should replace it.
14360                    replace = true;
14361                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14362                }
14363
14364                // Child packages are installed through the parent package
14365                if (pkg.parentPackage != null) {
14366                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14367                            "Package " + pkg.packageName + " is child of package "
14368                                    + pkg.parentPackage.parentPackage + ". Child packages "
14369                                    + "can be updated only through the parent package.");
14370                    return;
14371                }
14372
14373                if (replace) {
14374                    // Prevent apps opting out from runtime permissions
14375                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14376                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14377                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14378                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14379                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14380                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14381                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14382                                        + " doesn't support runtime permissions but the old"
14383                                        + " target SDK " + oldTargetSdk + " does.");
14384                        return;
14385                    }
14386
14387                    // Prevent installing of child packages
14388                    if (oldPackage.parentPackage != null) {
14389                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14390                                "Package " + pkg.packageName + " is child of package "
14391                                        + oldPackage.parentPackage + ". Child packages "
14392                                        + "can be updated only through the parent package.");
14393                        return;
14394                    }
14395                }
14396            }
14397
14398            PackageSetting ps = mSettings.mPackages.get(pkgName);
14399            if (ps != null) {
14400                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14401
14402                // Quick sanity check that we're signed correctly if updating;
14403                // we'll check this again later when scanning, but we want to
14404                // bail early here before tripping over redefined permissions.
14405                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14406                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14407                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14408                                + pkg.packageName + " upgrade keys do not match the "
14409                                + "previously installed version");
14410                        return;
14411                    }
14412                } else {
14413                    try {
14414                        verifySignaturesLP(ps, pkg);
14415                    } catch (PackageManagerException e) {
14416                        res.setError(e.error, e.getMessage());
14417                        return;
14418                    }
14419                }
14420
14421                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14422                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14423                    systemApp = (ps.pkg.applicationInfo.flags &
14424                            ApplicationInfo.FLAG_SYSTEM) != 0;
14425                }
14426                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14427            }
14428
14429            // Check whether the newly-scanned package wants to define an already-defined perm
14430            int N = pkg.permissions.size();
14431            for (int i = N-1; i >= 0; i--) {
14432                PackageParser.Permission perm = pkg.permissions.get(i);
14433                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14434                if (bp != null) {
14435                    // If the defining package is signed with our cert, it's okay.  This
14436                    // also includes the "updating the same package" case, of course.
14437                    // "updating same package" could also involve key-rotation.
14438                    final boolean sigsOk;
14439                    if (bp.sourcePackage.equals(pkg.packageName)
14440                            && (bp.packageSetting instanceof PackageSetting)
14441                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14442                                    scanFlags))) {
14443                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14444                    } else {
14445                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14446                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14447                    }
14448                    if (!sigsOk) {
14449                        // If the owning package is the system itself, we log but allow
14450                        // install to proceed; we fail the install on all other permission
14451                        // redefinitions.
14452                        if (!bp.sourcePackage.equals("android")) {
14453                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14454                                    + pkg.packageName + " attempting to redeclare permission "
14455                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14456                            res.origPermission = perm.info.name;
14457                            res.origPackage = bp.sourcePackage;
14458                            return;
14459                        } else {
14460                            Slog.w(TAG, "Package " + pkg.packageName
14461                                    + " attempting to redeclare system permission "
14462                                    + perm.info.name + "; ignoring new declaration");
14463                            pkg.permissions.remove(i);
14464                        }
14465                    }
14466                }
14467            }
14468        }
14469
14470        if (systemApp) {
14471            if (onExternal) {
14472                // Abort update; system app can't be replaced with app on sdcard
14473                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14474                        "Cannot install updates to system apps on sdcard");
14475                return;
14476            } else if (ephemeral) {
14477                // Abort update; system app can't be replaced with an ephemeral app
14478                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14479                        "Cannot update a system app with an ephemeral app");
14480                return;
14481            }
14482        }
14483
14484        if (args.move != null) {
14485            // We did an in-place move, so dex is ready to roll
14486            scanFlags |= SCAN_NO_DEX;
14487            scanFlags |= SCAN_MOVE;
14488
14489            synchronized (mPackages) {
14490                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14491                if (ps == null) {
14492                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14493                            "Missing settings for moved package " + pkgName);
14494                }
14495
14496                // We moved the entire application as-is, so bring over the
14497                // previously derived ABI information.
14498                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14499                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14500            }
14501
14502        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14503            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14504            scanFlags |= SCAN_NO_DEX;
14505
14506            try {
14507                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14508                    args.abiOverride : pkg.cpuAbiOverride);
14509                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14510                        true /* extract libs */);
14511            } catch (PackageManagerException pme) {
14512                Slog.e(TAG, "Error deriving application ABI", pme);
14513                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14514                return;
14515            }
14516
14517
14518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14519            // Do not run PackageDexOptimizer through the local performDexOpt
14520            // method because `pkg` is not in `mPackages` yet.
14521            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14522                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14524            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14525                String msg = "Extracking package failed for " + pkgName;
14526                res.setError(INSTALL_FAILED_DEXOPT, msg);
14527                return;
14528            }
14529        }
14530
14531        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14532            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14533            return;
14534        }
14535
14536        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14537
14538        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14539                "installPackageLI")) {
14540            if (replace) {
14541                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14542                        installerPackageName, res);
14543            } else {
14544                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14545                        args.user, installerPackageName, volumeUuid, res);
14546            }
14547        }
14548        synchronized (mPackages) {
14549            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14550            if (ps != null) {
14551                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14552            }
14553
14554            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14555            for (int i = 0; i < childCount; i++) {
14556                PackageParser.Package childPkg = pkg.childPackages.get(i);
14557                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14558                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14559                if (childPs != null) {
14560                    childRes.newUsers = childPs.queryInstalledUsers(
14561                            sUserManager.getUserIds(), true);
14562                }
14563            }
14564        }
14565    }
14566
14567    private void startIntentFilterVerifications(int userId, boolean replacing,
14568            PackageParser.Package pkg) {
14569        if (mIntentFilterVerifierComponent == null) {
14570            Slog.w(TAG, "No IntentFilter verification will not be done as "
14571                    + "there is no IntentFilterVerifier available!");
14572            return;
14573        }
14574
14575        final int verifierUid = getPackageUid(
14576                mIntentFilterVerifierComponent.getPackageName(),
14577                MATCH_DEBUG_TRIAGED_MISSING,
14578                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14579
14580        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14581        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14582        mHandler.sendMessage(msg);
14583
14584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14585        for (int i = 0; i < childCount; i++) {
14586            PackageParser.Package childPkg = pkg.childPackages.get(i);
14587            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14588            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14589            mHandler.sendMessage(msg);
14590        }
14591    }
14592
14593    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14594            PackageParser.Package pkg) {
14595        int size = pkg.activities.size();
14596        if (size == 0) {
14597            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14598                    "No activity, so no need to verify any IntentFilter!");
14599            return;
14600        }
14601
14602        final boolean hasDomainURLs = hasDomainURLs(pkg);
14603        if (!hasDomainURLs) {
14604            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14605                    "No domain URLs, so no need to verify any IntentFilter!");
14606            return;
14607        }
14608
14609        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14610                + " if any IntentFilter from the " + size
14611                + " Activities needs verification ...");
14612
14613        int count = 0;
14614        final String packageName = pkg.packageName;
14615
14616        synchronized (mPackages) {
14617            // If this is a new install and we see that we've already run verification for this
14618            // package, we have nothing to do: it means the state was restored from backup.
14619            if (!replacing) {
14620                IntentFilterVerificationInfo ivi =
14621                        mSettings.getIntentFilterVerificationLPr(packageName);
14622                if (ivi != null) {
14623                    if (DEBUG_DOMAIN_VERIFICATION) {
14624                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14625                                + ivi.getStatusString());
14626                    }
14627                    return;
14628                }
14629            }
14630
14631            // If any filters need to be verified, then all need to be.
14632            boolean needToVerify = false;
14633            for (PackageParser.Activity a : pkg.activities) {
14634                for (ActivityIntentInfo filter : a.intents) {
14635                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14636                        if (DEBUG_DOMAIN_VERIFICATION) {
14637                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14638                        }
14639                        needToVerify = true;
14640                        break;
14641                    }
14642                }
14643            }
14644
14645            if (needToVerify) {
14646                final int verificationId = mIntentFilterVerificationToken++;
14647                for (PackageParser.Activity a : pkg.activities) {
14648                    for (ActivityIntentInfo filter : a.intents) {
14649                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14650                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14651                                    "Verification needed for IntentFilter:" + filter.toString());
14652                            mIntentFilterVerifier.addOneIntentFilterVerification(
14653                                    verifierUid, userId, verificationId, filter, packageName);
14654                            count++;
14655                        }
14656                    }
14657                }
14658            }
14659        }
14660
14661        if (count > 0) {
14662            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14663                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14664                    +  " for userId:" + userId);
14665            mIntentFilterVerifier.startVerifications(userId);
14666        } else {
14667            if (DEBUG_DOMAIN_VERIFICATION) {
14668                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14669            }
14670        }
14671    }
14672
14673    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14674        final ComponentName cn  = filter.activity.getComponentName();
14675        final String packageName = cn.getPackageName();
14676
14677        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14678                packageName);
14679        if (ivi == null) {
14680            return true;
14681        }
14682        int status = ivi.getStatus();
14683        switch (status) {
14684            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14685            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14686                return true;
14687
14688            default:
14689                // Nothing to do
14690                return false;
14691        }
14692    }
14693
14694    private static boolean isMultiArch(ApplicationInfo info) {
14695        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14696    }
14697
14698    private static boolean isExternal(PackageParser.Package pkg) {
14699        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14700    }
14701
14702    private static boolean isExternal(PackageSetting ps) {
14703        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14704    }
14705
14706    private static boolean isEphemeral(PackageParser.Package pkg) {
14707        return pkg.applicationInfo.isEphemeralApp();
14708    }
14709
14710    private static boolean isEphemeral(PackageSetting ps) {
14711        return ps.pkg != null && isEphemeral(ps.pkg);
14712    }
14713
14714    private static boolean isSystemApp(PackageParser.Package pkg) {
14715        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14716    }
14717
14718    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14719        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14720    }
14721
14722    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14723        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14724    }
14725
14726    private static boolean isSystemApp(PackageSetting ps) {
14727        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14728    }
14729
14730    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14731        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14732    }
14733
14734    private int packageFlagsToInstallFlags(PackageSetting ps) {
14735        int installFlags = 0;
14736        if (isEphemeral(ps)) {
14737            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14738        }
14739        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14740            // This existing package was an external ASEC install when we have
14741            // the external flag without a UUID
14742            installFlags |= PackageManager.INSTALL_EXTERNAL;
14743        }
14744        if (ps.isForwardLocked()) {
14745            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14746        }
14747        return installFlags;
14748    }
14749
14750    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14751        if (isExternal(pkg)) {
14752            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14753                return StorageManager.UUID_PRIMARY_PHYSICAL;
14754            } else {
14755                return pkg.volumeUuid;
14756            }
14757        } else {
14758            return StorageManager.UUID_PRIVATE_INTERNAL;
14759        }
14760    }
14761
14762    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14763        if (isExternal(pkg)) {
14764            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14765                return mSettings.getExternalVersion();
14766            } else {
14767                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14768            }
14769        } else {
14770            return mSettings.getInternalVersion();
14771        }
14772    }
14773
14774    private void deleteTempPackageFiles() {
14775        final FilenameFilter filter = new FilenameFilter() {
14776            public boolean accept(File dir, String name) {
14777                return name.startsWith("vmdl") && name.endsWith(".tmp");
14778            }
14779        };
14780        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14781            file.delete();
14782        }
14783    }
14784
14785    @Override
14786    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14787            int flags) {
14788        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14789                flags);
14790    }
14791
14792    @Override
14793    public void deletePackage(final String packageName,
14794            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14795        mContext.enforceCallingOrSelfPermission(
14796                android.Manifest.permission.DELETE_PACKAGES, null);
14797        Preconditions.checkNotNull(packageName);
14798        Preconditions.checkNotNull(observer);
14799        final int uid = Binder.getCallingUid();
14800        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
14801        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14802        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14803            mContext.enforceCallingOrSelfPermission(
14804                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14805                    "deletePackage for user " + userId);
14806        }
14807
14808        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14809            try {
14810                observer.onPackageDeleted(packageName,
14811                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14812            } catch (RemoteException re) {
14813            }
14814            return;
14815        }
14816
14817        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14818            try {
14819                observer.onPackageDeleted(packageName,
14820                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14821            } catch (RemoteException re) {
14822            }
14823            return;
14824        }
14825
14826        if (DEBUG_REMOVE) {
14827            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14828                    + " deleteAllUsers: " + deleteAllUsers );
14829        }
14830        // Queue up an async operation since the package deletion may take a little while.
14831        mHandler.post(new Runnable() {
14832            public void run() {
14833                mHandler.removeCallbacks(this);
14834                int returnCode;
14835                if (!deleteAllUsers) {
14836                    returnCode = deletePackageX(packageName, userId, deleteFlags);
14837                } else {
14838                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14839                    // If nobody is blocking uninstall, proceed with delete for all users
14840                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14841                        returnCode = deletePackageX(packageName, userId, deleteFlags);
14842                    } else {
14843                        // Otherwise uninstall individually for users with blockUninstalls=false
14844                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
14845                        for (int userId : users) {
14846                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14847                                returnCode = deletePackageX(packageName, userId, userFlags);
14848                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14849                                    Slog.w(TAG, "Package delete failed for user " + userId
14850                                            + ", returnCode " + returnCode);
14851                                }
14852                            }
14853                        }
14854                        // The app has only been marked uninstalled for certain users.
14855                        // We still need to report that delete was blocked
14856                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14857                    }
14858                }
14859                try {
14860                    observer.onPackageDeleted(packageName, returnCode, null);
14861                } catch (RemoteException e) {
14862                    Log.i(TAG, "Observer no longer exists.");
14863                } //end catch
14864            } //end run
14865        });
14866    }
14867
14868    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14869        int[] result = EMPTY_INT_ARRAY;
14870        for (int userId : userIds) {
14871            if (getBlockUninstallForUser(packageName, userId)) {
14872                result = ArrayUtils.appendInt(result, userId);
14873            }
14874        }
14875        return result;
14876    }
14877
14878    @Override
14879    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14880        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14881    }
14882
14883    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14884        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14885                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14886        try {
14887            if (dpm != null) {
14888                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14889                        /* callingUserOnly =*/ false);
14890                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14891                        : deviceOwnerComponentName.getPackageName();
14892                // Does the package contains the device owner?
14893                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14894                // this check is probably not needed, since DO should be registered as a device
14895                // admin on some user too. (Original bug for this: b/17657954)
14896                if (packageName.equals(deviceOwnerPackageName)) {
14897                    return true;
14898                }
14899                // Does it contain a device admin for any user?
14900                int[] users;
14901                if (userId == UserHandle.USER_ALL) {
14902                    users = sUserManager.getUserIds();
14903                } else {
14904                    users = new int[]{userId};
14905                }
14906                for (int i = 0; i < users.length; ++i) {
14907                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14908                        return true;
14909                    }
14910                }
14911            }
14912        } catch (RemoteException e) {
14913        }
14914        return false;
14915    }
14916
14917    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14918        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14919    }
14920
14921    /**
14922     *  This method is an internal method that could be get invoked either
14923     *  to delete an installed package or to clean up a failed installation.
14924     *  After deleting an installed package, a broadcast is sent to notify any
14925     *  listeners that the package has been removed. For cleaning up a failed
14926     *  installation, the broadcast is not necessary since the package's
14927     *  installation wouldn't have sent the initial broadcast either
14928     *  The key steps in deleting a package are
14929     *  deleting the package information in internal structures like mPackages,
14930     *  deleting the packages base directories through installd
14931     *  updating mSettings to reflect current status
14932     *  persisting settings for later use
14933     *  sending a broadcast if necessary
14934     */
14935    private int deletePackageX(String packageName, int userId, int deleteFlags) {
14936        final PackageRemovedInfo info = new PackageRemovedInfo();
14937        final boolean res;
14938
14939        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
14940                ? UserHandle.ALL : new UserHandle(userId);
14941
14942        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14943            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14944            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14945        }
14946
14947        PackageSetting uninstalledPs = null;
14948
14949        // for the uninstall-updates case and restricted profiles, remember the per-
14950        // user handle installed state
14951        int[] allUsers;
14952        synchronized (mPackages) {
14953            uninstalledPs = mSettings.mPackages.get(packageName);
14954            if (uninstalledPs == null) {
14955                Slog.w(TAG, "Not removing non-existent package " + packageName);
14956                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14957            }
14958            allUsers = sUserManager.getUserIds();
14959            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14960        }
14961
14962        synchronized (mInstallLock) {
14963            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14964            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
14965                    "deletePackageX")) {
14966                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
14967                        deleteFlags | REMOVE_CHATTY, info, true, null);
14968            }
14969            synchronized (mPackages) {
14970                if (res) {
14971                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14972                }
14973            }
14974        }
14975
14976        if (res) {
14977            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
14978            info.sendPackageRemovedBroadcasts(killApp);
14979            info.sendSystemPackageUpdatedBroadcasts();
14980            info.sendSystemPackageAppearedBroadcasts();
14981        }
14982        // Force a gc here.
14983        Runtime.getRuntime().gc();
14984        // Delete the resources here after sending the broadcast to let
14985        // other processes clean up before deleting resources.
14986        if (info.args != null) {
14987            synchronized (mInstallLock) {
14988                info.args.doPostDeleteLI(true);
14989            }
14990        }
14991
14992        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14993    }
14994
14995    class PackageRemovedInfo {
14996        String removedPackage;
14997        int uid = -1;
14998        int removedAppId = -1;
14999        int[] origUsers;
15000        int[] removedUsers = null;
15001        boolean isRemovedPackageSystemUpdate = false;
15002        boolean isUpdate;
15003        boolean dataRemoved;
15004        boolean removedForAllUsers;
15005        // Clean up resources deleted packages.
15006        InstallArgs args = null;
15007        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15008        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15009
15010        void sendPackageRemovedBroadcasts(boolean killApp) {
15011            sendPackageRemovedBroadcastInternal(killApp);
15012            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15013            for (int i = 0; i < childCount; i++) {
15014                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15015                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15016            }
15017        }
15018
15019        void sendSystemPackageUpdatedBroadcasts() {
15020            if (isRemovedPackageSystemUpdate) {
15021                sendSystemPackageUpdatedBroadcastsInternal();
15022                final int childCount = (removedChildPackages != null)
15023                        ? removedChildPackages.size() : 0;
15024                for (int i = 0; i < childCount; i++) {
15025                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15026                    if (childInfo.isRemovedPackageSystemUpdate) {
15027                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15028                    }
15029                }
15030            }
15031        }
15032
15033        void sendSystemPackageAppearedBroadcasts() {
15034            final int packageCount = (appearedChildPackages != null)
15035                    ? appearedChildPackages.size() : 0;
15036            for (int i = 0; i < packageCount; i++) {
15037                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15038                for (int userId : installedInfo.newUsers) {
15039                    sendPackageAddedForUser(installedInfo.name, true,
15040                            UserHandle.getAppId(installedInfo.uid), userId);
15041                }
15042            }
15043        }
15044
15045        private void sendSystemPackageUpdatedBroadcastsInternal() {
15046            Bundle extras = new Bundle(2);
15047            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15048            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15049            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15050                    extras, 0, null, null, null);
15051            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15052                    extras, 0, null, null, null);
15053            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15054                    null, 0, removedPackage, null, null);
15055        }
15056
15057        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15058            Bundle extras = new Bundle(2);
15059            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15060            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15061            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15062            if (isUpdate || isRemovedPackageSystemUpdate) {
15063                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15064            }
15065            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15066            if (removedPackage != null) {
15067                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15068                        extras, 0, null, null, removedUsers);
15069                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15070                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15071                            removedPackage, extras, 0, null, null, removedUsers);
15072                }
15073            }
15074            if (removedAppId >= 0) {
15075                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15076                        removedUsers);
15077            }
15078        }
15079    }
15080
15081    /*
15082     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15083     * flag is not set, the data directory is removed as well.
15084     * make sure this flag is set for partially installed apps. If not its meaningless to
15085     * delete a partially installed application.
15086     */
15087    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15088            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15089        String packageName = ps.name;
15090        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15091        // Retrieve object to delete permissions for shared user later on
15092        final PackageParser.Package deletedPkg;
15093        final PackageSetting deletedPs;
15094        // reader
15095        synchronized (mPackages) {
15096            deletedPkg = mPackages.get(packageName);
15097            deletedPs = mSettings.mPackages.get(packageName);
15098            if (outInfo != null) {
15099                outInfo.removedPackage = packageName;
15100                outInfo.removedUsers = deletedPs != null
15101                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15102                        : null;
15103            }
15104        }
15105
15106        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15107
15108        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15109            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15110                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15111            destroyAppProfilesLIF(deletedPkg);
15112            if (outInfo != null) {
15113                outInfo.dataRemoved = true;
15114            }
15115            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15116        }
15117
15118        // writer
15119        synchronized (mPackages) {
15120            if (deletedPs != null) {
15121                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15122                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15123                    clearDefaultBrowserIfNeeded(packageName);
15124                    if (outInfo != null) {
15125                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15126                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15127                    }
15128                    updatePermissionsLPw(deletedPs.name, null, 0);
15129                    if (deletedPs.sharedUser != null) {
15130                        // Remove permissions associated with package. Since runtime
15131                        // permissions are per user we have to kill the removed package
15132                        // or packages running under the shared user of the removed
15133                        // package if revoking the permissions requested only by the removed
15134                        // package is successful and this causes a change in gids.
15135                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15136                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15137                                    userId);
15138                            if (userIdToKill == UserHandle.USER_ALL
15139                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15140                                // If gids changed for this user, kill all affected packages.
15141                                mHandler.post(new Runnable() {
15142                                    @Override
15143                                    public void run() {
15144                                        // This has to happen with no lock held.
15145                                        killApplication(deletedPs.name, deletedPs.appId,
15146                                                KILL_APP_REASON_GIDS_CHANGED);
15147                                    }
15148                                });
15149                                break;
15150                            }
15151                        }
15152                    }
15153                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15154                }
15155                // make sure to preserve per-user disabled state if this removal was just
15156                // a downgrade of a system app to the factory package
15157                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15158                    if (DEBUG_REMOVE) {
15159                        Slog.d(TAG, "Propagating install state across downgrade");
15160                    }
15161                    for (int userId : allUserHandles) {
15162                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15163                        if (DEBUG_REMOVE) {
15164                            Slog.d(TAG, "    user " + userId + " => " + installed);
15165                        }
15166                        ps.setInstalled(installed, userId);
15167                    }
15168                }
15169            }
15170            // can downgrade to reader
15171            if (writeSettings) {
15172                // Save settings now
15173                mSettings.writeLPr();
15174            }
15175        }
15176        if (outInfo != null) {
15177            // A user ID was deleted here. Go through all users and remove it
15178            // from KeyStore.
15179            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15180        }
15181    }
15182
15183    static boolean locationIsPrivileged(File path) {
15184        try {
15185            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15186                    .getCanonicalPath();
15187            return path.getCanonicalPath().startsWith(privilegedAppDir);
15188        } catch (IOException e) {
15189            Slog.e(TAG, "Unable to access code path " + path);
15190        }
15191        return false;
15192    }
15193
15194    /*
15195     * Tries to delete system package.
15196     */
15197    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15198            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15199            boolean writeSettings) {
15200        if (deletedPs.parentPackageName != null) {
15201            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15202            return false;
15203        }
15204
15205        final boolean applyUserRestrictions
15206                = (allUserHandles != null) && (outInfo.origUsers != null);
15207        final PackageSetting disabledPs;
15208        // Confirm if the system package has been updated
15209        // An updated system app can be deleted. This will also have to restore
15210        // the system pkg from system partition
15211        // reader
15212        synchronized (mPackages) {
15213            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15214        }
15215
15216        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15217                + " disabledPs=" + disabledPs);
15218
15219        if (disabledPs == null) {
15220            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15221            return false;
15222        } else if (DEBUG_REMOVE) {
15223            Slog.d(TAG, "Deleting system pkg from data partition");
15224        }
15225
15226        if (DEBUG_REMOVE) {
15227            if (applyUserRestrictions) {
15228                Slog.d(TAG, "Remembering install states:");
15229                for (int userId : allUserHandles) {
15230                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15231                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15232                }
15233            }
15234        }
15235
15236        // Delete the updated package
15237        outInfo.isRemovedPackageSystemUpdate = true;
15238        if (outInfo.removedChildPackages != null) {
15239            final int childCount = (deletedPs.childPackageNames != null)
15240                    ? deletedPs.childPackageNames.size() : 0;
15241            for (int i = 0; i < childCount; i++) {
15242                String childPackageName = deletedPs.childPackageNames.get(i);
15243                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15244                        .contains(childPackageName)) {
15245                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15246                            childPackageName);
15247                    if (childInfo != null) {
15248                        childInfo.isRemovedPackageSystemUpdate = true;
15249                    }
15250                }
15251            }
15252        }
15253
15254        if (disabledPs.versionCode < deletedPs.versionCode) {
15255            // Delete data for downgrades
15256            flags &= ~PackageManager.DELETE_KEEP_DATA;
15257        } else {
15258            // Preserve data by setting flag
15259            flags |= PackageManager.DELETE_KEEP_DATA;
15260        }
15261
15262        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15263                outInfo, writeSettings, disabledPs.pkg);
15264        if (!ret) {
15265            return false;
15266        }
15267
15268        // writer
15269        synchronized (mPackages) {
15270            // Reinstate the old system package
15271            enableSystemPackageLPw(disabledPs.pkg);
15272            // Remove any native libraries from the upgraded package.
15273            removeNativeBinariesLI(deletedPs);
15274        }
15275
15276        // Install the system package
15277        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15278        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
15279        if (locationIsPrivileged(disabledPs.codePath)) {
15280            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15281        }
15282
15283        final PackageParser.Package newPkg;
15284        try {
15285            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15286        } catch (PackageManagerException e) {
15287            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15288                    + e.getMessage());
15289            return false;
15290        }
15291
15292        prepareAppDataAfterInstallLIF(newPkg);
15293
15294        // writer
15295        synchronized (mPackages) {
15296            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15297
15298            // Propagate the permissions state as we do not want to drop on the floor
15299            // runtime permissions. The update permissions method below will take
15300            // care of removing obsolete permissions and grant install permissions.
15301            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15302            updatePermissionsLPw(newPkg.packageName, newPkg,
15303                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15304
15305            if (applyUserRestrictions) {
15306                if (DEBUG_REMOVE) {
15307                    Slog.d(TAG, "Propagating install state across reinstall");
15308                }
15309                for (int userId : allUserHandles) {
15310                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15311                    if (DEBUG_REMOVE) {
15312                        Slog.d(TAG, "    user " + userId + " => " + installed);
15313                    }
15314                    ps.setInstalled(installed, userId);
15315
15316                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15317                }
15318                // Regardless of writeSettings we need to ensure that this restriction
15319                // state propagation is persisted
15320                mSettings.writeAllUsersPackageRestrictionsLPr();
15321            }
15322            // can downgrade to reader here
15323            if (writeSettings) {
15324                mSettings.writeLPr();
15325            }
15326        }
15327        return true;
15328    }
15329
15330    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15331            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15332            PackageRemovedInfo outInfo, boolean writeSettings,
15333            PackageParser.Package replacingPackage) {
15334        synchronized (mPackages) {
15335            if (outInfo != null) {
15336                outInfo.uid = ps.appId;
15337            }
15338
15339            if (outInfo != null && outInfo.removedChildPackages != null) {
15340                final int childCount = (ps.childPackageNames != null)
15341                        ? ps.childPackageNames.size() : 0;
15342                for (int i = 0; i < childCount; i++) {
15343                    String childPackageName = ps.childPackageNames.get(i);
15344                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15345                    if (childPs == null) {
15346                        return false;
15347                    }
15348                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15349                            childPackageName);
15350                    if (childInfo != null) {
15351                        childInfo.uid = childPs.appId;
15352                    }
15353                }
15354            }
15355        }
15356
15357        // Delete package data from internal structures and also remove data if flag is set
15358        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15359
15360        // Delete the child packages data
15361        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15362        for (int i = 0; i < childCount; i++) {
15363            PackageSetting childPs;
15364            synchronized (mPackages) {
15365                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15366            }
15367            if (childPs != null) {
15368                PackageRemovedInfo childOutInfo = (outInfo != null
15369                        && outInfo.removedChildPackages != null)
15370                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15371                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15372                        && (replacingPackage != null
15373                        && !replacingPackage.hasChildPackage(childPs.name))
15374                        ? flags & ~DELETE_KEEP_DATA : flags;
15375                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15376                        deleteFlags, writeSettings);
15377            }
15378        }
15379
15380        // Delete application code and resources only for parent packages
15381        if (ps.parentPackageName == null) {
15382            if (deleteCodeAndResources && (outInfo != null)) {
15383                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15384                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15385                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15386            }
15387        }
15388
15389        return true;
15390    }
15391
15392    @Override
15393    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15394            int userId) {
15395        mContext.enforceCallingOrSelfPermission(
15396                android.Manifest.permission.DELETE_PACKAGES, null);
15397        synchronized (mPackages) {
15398            PackageSetting ps = mSettings.mPackages.get(packageName);
15399            if (ps == null) {
15400                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15401                return false;
15402            }
15403            if (!ps.getInstalled(userId)) {
15404                // Can't block uninstall for an app that is not installed or enabled.
15405                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15406                return false;
15407            }
15408            ps.setBlockUninstall(blockUninstall, userId);
15409            mSettings.writePackageRestrictionsLPr(userId);
15410        }
15411        return true;
15412    }
15413
15414    @Override
15415    public boolean getBlockUninstallForUser(String packageName, int userId) {
15416        synchronized (mPackages) {
15417            PackageSetting ps = mSettings.mPackages.get(packageName);
15418            if (ps == null) {
15419                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15420                return false;
15421            }
15422            return ps.getBlockUninstall(userId);
15423        }
15424    }
15425
15426    @Override
15427    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15428        int callingUid = Binder.getCallingUid();
15429        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15430            throw new SecurityException(
15431                    "setRequiredForSystemUser can only be run by the system or root");
15432        }
15433        synchronized (mPackages) {
15434            PackageSetting ps = mSettings.mPackages.get(packageName);
15435            if (ps == null) {
15436                Log.w(TAG, "Package doesn't exist: " + packageName);
15437                return false;
15438            }
15439            if (systemUserApp) {
15440                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15441            } else {
15442                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15443            }
15444            mSettings.writeLPr();
15445        }
15446        return true;
15447    }
15448
15449    /*
15450     * This method handles package deletion in general
15451     */
15452    private boolean deletePackageLIF(String packageName, UserHandle user,
15453            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15454            PackageRemovedInfo outInfo, boolean writeSettings,
15455            PackageParser.Package replacingPackage) {
15456        if (packageName == null) {
15457            Slog.w(TAG, "Attempt to delete null packageName.");
15458            return false;
15459        }
15460
15461        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15462
15463        PackageSetting ps;
15464
15465        synchronized (mPackages) {
15466            ps = mSettings.mPackages.get(packageName);
15467            if (ps == null) {
15468                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15469                return false;
15470            }
15471
15472            if (ps.parentPackageName != null && (!isSystemApp(ps)
15473                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15474                if (DEBUG_REMOVE) {
15475                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15476                            + ((user == null) ? UserHandle.USER_ALL : user));
15477                }
15478                final int removedUserId = (user != null) ? user.getIdentifier()
15479                        : UserHandle.USER_ALL;
15480                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15481                    return false;
15482                }
15483                markPackageUninstalledForUserLPw(ps, user);
15484                scheduleWritePackageRestrictionsLocked(user);
15485                return true;
15486            }
15487        }
15488
15489        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15490                && user.getIdentifier() != UserHandle.USER_ALL)) {
15491            // The caller is asking that the package only be deleted for a single
15492            // user.  To do this, we just mark its uninstalled state and delete
15493            // its data. If this is a system app, we only allow this to happen if
15494            // they have set the special DELETE_SYSTEM_APP which requests different
15495            // semantics than normal for uninstalling system apps.
15496            markPackageUninstalledForUserLPw(ps, user);
15497
15498            if (!isSystemApp(ps)) {
15499                // Do not uninstall the APK if an app should be cached
15500                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15501                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15502                    // Other user still have this package installed, so all
15503                    // we need to do is clear this user's data and save that
15504                    // it is uninstalled.
15505                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15506                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15507                        return false;
15508                    }
15509                    scheduleWritePackageRestrictionsLocked(user);
15510                    return true;
15511                } else {
15512                    // We need to set it back to 'installed' so the uninstall
15513                    // broadcasts will be sent correctly.
15514                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15515                    ps.setInstalled(true, user.getIdentifier());
15516                }
15517            } else {
15518                // This is a system app, so we assume that the
15519                // other users still have this package installed, so all
15520                // we need to do is clear this user's data and save that
15521                // it is uninstalled.
15522                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15523                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15524                    return false;
15525                }
15526                scheduleWritePackageRestrictionsLocked(user);
15527                return true;
15528            }
15529        }
15530
15531        // If we are deleting a composite package for all users, keep track
15532        // of result for each child.
15533        if (ps.childPackageNames != null && outInfo != null) {
15534            synchronized (mPackages) {
15535                final int childCount = ps.childPackageNames.size();
15536                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15537                for (int i = 0; i < childCount; i++) {
15538                    String childPackageName = ps.childPackageNames.get(i);
15539                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15540                    childInfo.removedPackage = childPackageName;
15541                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15542                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15543                    if (childPs != null) {
15544                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15545                    }
15546                }
15547            }
15548        }
15549
15550        boolean ret = false;
15551        if (isSystemApp(ps)) {
15552            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15553            // When an updated system application is deleted we delete the existing resources
15554            // as well and fall back to existing code in system partition
15555            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15556        } else {
15557            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15558            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15559                    outInfo, writeSettings, replacingPackage);
15560        }
15561
15562        // Take a note whether we deleted the package for all users
15563        if (outInfo != null) {
15564            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15565            if (outInfo.removedChildPackages != null) {
15566                synchronized (mPackages) {
15567                    final int childCount = outInfo.removedChildPackages.size();
15568                    for (int i = 0; i < childCount; i++) {
15569                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15570                        if (childInfo != null) {
15571                            childInfo.removedForAllUsers = mPackages.get(
15572                                    childInfo.removedPackage) == null;
15573                        }
15574                    }
15575                }
15576            }
15577            // If we uninstalled an update to a system app there may be some
15578            // child packages that appeared as they are declared in the system
15579            // app but were not declared in the update.
15580            if (isSystemApp(ps)) {
15581                synchronized (mPackages) {
15582                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15583                    final int childCount = (updatedPs.childPackageNames != null)
15584                            ? updatedPs.childPackageNames.size() : 0;
15585                    for (int i = 0; i < childCount; i++) {
15586                        String childPackageName = updatedPs.childPackageNames.get(i);
15587                        if (outInfo.removedChildPackages == null
15588                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15589                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15590                            if (childPs == null) {
15591                                continue;
15592                            }
15593                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15594                            installRes.name = childPackageName;
15595                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15596                            installRes.pkg = mPackages.get(childPackageName);
15597                            installRes.uid = childPs.pkg.applicationInfo.uid;
15598                            if (outInfo.appearedChildPackages == null) {
15599                                outInfo.appearedChildPackages = new ArrayMap<>();
15600                            }
15601                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15602                        }
15603                    }
15604                }
15605            }
15606        }
15607
15608        return ret;
15609    }
15610
15611    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15612        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15613                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15614        for (int nextUserId : userIds) {
15615            if (DEBUG_REMOVE) {
15616                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15617            }
15618            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15619                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15620                    false /*hidden*/, false /*suspended*/, null, null, null,
15621                    false /*blockUninstall*/,
15622                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15623        }
15624    }
15625
15626    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15627            PackageRemovedInfo outInfo) {
15628        final PackageParser.Package pkg;
15629        synchronized (mPackages) {
15630            pkg = mPackages.get(ps.name);
15631        }
15632
15633        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15634                : new int[] {userId};
15635        for (int nextUserId : userIds) {
15636            if (DEBUG_REMOVE) {
15637                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15638                        + nextUserId);
15639            }
15640
15641            destroyAppDataLIF(pkg, userId,
15642                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15643            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15644            schedulePackageCleaning(ps.name, nextUserId, false);
15645            synchronized (mPackages) {
15646                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15647                    scheduleWritePackageRestrictionsLocked(nextUserId);
15648                }
15649                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15650            }
15651        }
15652
15653        if (outInfo != null) {
15654            outInfo.removedPackage = ps.name;
15655            outInfo.removedAppId = ps.appId;
15656            outInfo.removedUsers = userIds;
15657        }
15658
15659        return true;
15660    }
15661
15662    private final class ClearStorageConnection implements ServiceConnection {
15663        IMediaContainerService mContainerService;
15664
15665        @Override
15666        public void onServiceConnected(ComponentName name, IBinder service) {
15667            synchronized (this) {
15668                mContainerService = IMediaContainerService.Stub.asInterface(service);
15669                notifyAll();
15670            }
15671        }
15672
15673        @Override
15674        public void onServiceDisconnected(ComponentName name) {
15675        }
15676    }
15677
15678    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15679        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15680
15681        final boolean mounted;
15682        if (Environment.isExternalStorageEmulated()) {
15683            mounted = true;
15684        } else {
15685            final String status = Environment.getExternalStorageState();
15686
15687            mounted = status.equals(Environment.MEDIA_MOUNTED)
15688                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15689        }
15690
15691        if (!mounted) {
15692            return;
15693        }
15694
15695        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15696        int[] users;
15697        if (userId == UserHandle.USER_ALL) {
15698            users = sUserManager.getUserIds();
15699        } else {
15700            users = new int[] { userId };
15701        }
15702        final ClearStorageConnection conn = new ClearStorageConnection();
15703        if (mContext.bindServiceAsUser(
15704                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15705            try {
15706                for (int curUser : users) {
15707                    long timeout = SystemClock.uptimeMillis() + 5000;
15708                    synchronized (conn) {
15709                        long now = SystemClock.uptimeMillis();
15710                        while (conn.mContainerService == null && now < timeout) {
15711                            try {
15712                                conn.wait(timeout - now);
15713                            } catch (InterruptedException e) {
15714                            }
15715                        }
15716                    }
15717                    if (conn.mContainerService == null) {
15718                        return;
15719                    }
15720
15721                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15722                    clearDirectory(conn.mContainerService,
15723                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15724                    if (allData) {
15725                        clearDirectory(conn.mContainerService,
15726                                userEnv.buildExternalStorageAppDataDirs(packageName));
15727                        clearDirectory(conn.mContainerService,
15728                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15729                    }
15730                }
15731            } finally {
15732                mContext.unbindService(conn);
15733            }
15734        }
15735    }
15736
15737    @Override
15738    public void clearApplicationProfileData(String packageName) {
15739        enforceSystemOrRoot("Only the system can clear all profile data");
15740
15741        final PackageParser.Package pkg;
15742        synchronized (mPackages) {
15743            pkg = mPackages.get(packageName);
15744        }
15745
15746        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15747            synchronized (mInstallLock) {
15748                clearAppProfilesLIF(pkg);
15749            }
15750        }
15751    }
15752
15753    @Override
15754    public void clearApplicationUserData(final String packageName,
15755            final IPackageDataObserver observer, final int userId) {
15756        mContext.enforceCallingOrSelfPermission(
15757                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15758
15759        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15760                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15761
15762        final DevicePolicyManagerInternal dpmi = LocalServices
15763                .getService(DevicePolicyManagerInternal.class);
15764        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15765            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15766        }
15767        // Queue up an async operation since the package deletion may take a little while.
15768        mHandler.post(new Runnable() {
15769            public void run() {
15770                mHandler.removeCallbacks(this);
15771                final boolean succeeded;
15772                try (PackageFreezer freezer = freezePackage(packageName,
15773                        "clearApplicationUserData")) {
15774                    synchronized (mInstallLock) {
15775                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15776                    }
15777                    clearExternalStorageDataSync(packageName, userId, true);
15778                }
15779                if (succeeded) {
15780                    // invoke DeviceStorageMonitor's update method to clear any notifications
15781                    DeviceStorageMonitorInternal dsm = LocalServices
15782                            .getService(DeviceStorageMonitorInternal.class);
15783                    if (dsm != null) {
15784                        dsm.checkMemory();
15785                    }
15786                }
15787                if(observer != null) {
15788                    try {
15789                        observer.onRemoveCompleted(packageName, succeeded);
15790                    } catch (RemoteException e) {
15791                        Log.i(TAG, "Observer no longer exists.");
15792                    }
15793                } //end if observer
15794            } //end run
15795        });
15796    }
15797
15798    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
15799        if (packageName == null) {
15800            Slog.w(TAG, "Attempt to delete null packageName.");
15801            return false;
15802        }
15803
15804        // Try finding details about the requested package
15805        PackageParser.Package pkg;
15806        synchronized (mPackages) {
15807            pkg = mPackages.get(packageName);
15808            if (pkg == null) {
15809                final PackageSetting ps = mSettings.mPackages.get(packageName);
15810                if (ps != null) {
15811                    pkg = ps.pkg;
15812                }
15813            }
15814
15815            if (pkg == null) {
15816                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15817                return false;
15818            }
15819
15820            PackageSetting ps = (PackageSetting) pkg.mExtras;
15821            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15822        }
15823
15824        clearAppDataLIF(pkg, userId,
15825                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15826
15827        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15828        removeKeystoreDataIfNeeded(userId, appId);
15829
15830        final UserManager um = mContext.getSystemService(UserManager.class);
15831        final int flags;
15832        if (um.isUserUnlocked(userId)) {
15833            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
15834        } else if (um.isUserRunning(userId)) {
15835            flags = StorageManager.FLAG_STORAGE_DE;
15836        } else {
15837            flags = 0;
15838        }
15839        prepareAppDataContentsLIF(pkg, userId, flags);
15840
15841        return true;
15842    }
15843
15844    /**
15845     * Reverts user permission state changes (permissions and flags) in
15846     * all packages for a given user.
15847     *
15848     * @param userId The device user for which to do a reset.
15849     */
15850    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15851        final int packageCount = mPackages.size();
15852        for (int i = 0; i < packageCount; i++) {
15853            PackageParser.Package pkg = mPackages.valueAt(i);
15854            PackageSetting ps = (PackageSetting) pkg.mExtras;
15855            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15856        }
15857    }
15858
15859    /**
15860     * Reverts user permission state changes (permissions and flags).
15861     *
15862     * @param ps The package for which to reset.
15863     * @param userId The device user for which to do a reset.
15864     */
15865    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15866            final PackageSetting ps, final int userId) {
15867        if (ps.pkg == null) {
15868            return;
15869        }
15870
15871        // These are flags that can change base on user actions.
15872        final int userSettableMask = FLAG_PERMISSION_USER_SET
15873                | FLAG_PERMISSION_USER_FIXED
15874                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15875                | FLAG_PERMISSION_REVIEW_REQUIRED;
15876
15877        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15878                | FLAG_PERMISSION_POLICY_FIXED;
15879
15880        boolean writeInstallPermissions = false;
15881        boolean writeRuntimePermissions = false;
15882
15883        final int permissionCount = ps.pkg.requestedPermissions.size();
15884        for (int i = 0; i < permissionCount; i++) {
15885            String permission = ps.pkg.requestedPermissions.get(i);
15886
15887            BasePermission bp = mSettings.mPermissions.get(permission);
15888            if (bp == null) {
15889                continue;
15890            }
15891
15892            // If shared user we just reset the state to which only this app contributed.
15893            if (ps.sharedUser != null) {
15894                boolean used = false;
15895                final int packageCount = ps.sharedUser.packages.size();
15896                for (int j = 0; j < packageCount; j++) {
15897                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15898                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15899                            && pkg.pkg.requestedPermissions.contains(permission)) {
15900                        used = true;
15901                        break;
15902                    }
15903                }
15904                if (used) {
15905                    continue;
15906                }
15907            }
15908
15909            PermissionsState permissionsState = ps.getPermissionsState();
15910
15911            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15912
15913            // Always clear the user settable flags.
15914            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15915                    bp.name) != null;
15916            // If permission review is enabled and this is a legacy app, mark the
15917            // permission as requiring a review as this is the initial state.
15918            int flags = 0;
15919            if (Build.PERMISSIONS_REVIEW_REQUIRED
15920                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15921                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15922            }
15923            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15924                if (hasInstallState) {
15925                    writeInstallPermissions = true;
15926                } else {
15927                    writeRuntimePermissions = true;
15928                }
15929            }
15930
15931            // Below is only runtime permission handling.
15932            if (!bp.isRuntime()) {
15933                continue;
15934            }
15935
15936            // Never clobber system or policy.
15937            if ((oldFlags & policyOrSystemFlags) != 0) {
15938                continue;
15939            }
15940
15941            // If this permission was granted by default, make sure it is.
15942            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15943                if (permissionsState.grantRuntimePermission(bp, userId)
15944                        != PERMISSION_OPERATION_FAILURE) {
15945                    writeRuntimePermissions = true;
15946                }
15947            // If permission review is enabled the permissions for a legacy apps
15948            // are represented as constantly granted runtime ones, so don't revoke.
15949            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15950                // Otherwise, reset the permission.
15951                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15952                switch (revokeResult) {
15953                    case PERMISSION_OPERATION_SUCCESS:
15954                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15955                        writeRuntimePermissions = true;
15956                        final int appId = ps.appId;
15957                        mHandler.post(new Runnable() {
15958                            @Override
15959                            public void run() {
15960                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
15961                            }
15962                        });
15963                    } break;
15964                }
15965            }
15966        }
15967
15968        // Synchronously write as we are taking permissions away.
15969        if (writeRuntimePermissions) {
15970            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15971        }
15972
15973        // Synchronously write as we are taking permissions away.
15974        if (writeInstallPermissions) {
15975            mSettings.writeLPr();
15976        }
15977    }
15978
15979    /**
15980     * Remove entries from the keystore daemon. Will only remove it if the
15981     * {@code appId} is valid.
15982     */
15983    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15984        if (appId < 0) {
15985            return;
15986        }
15987
15988        final KeyStore keyStore = KeyStore.getInstance();
15989        if (keyStore != null) {
15990            if (userId == UserHandle.USER_ALL) {
15991                for (final int individual : sUserManager.getUserIds()) {
15992                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15993                }
15994            } else {
15995                keyStore.clearUid(UserHandle.getUid(userId, appId));
15996            }
15997        } else {
15998            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15999        }
16000    }
16001
16002    @Override
16003    public void deleteApplicationCacheFiles(final String packageName,
16004            final IPackageDataObserver observer) {
16005        mContext.enforceCallingOrSelfPermission(
16006                android.Manifest.permission.DELETE_CACHE_FILES, null);
16007        // Queue up an async operation since the package deletion may take a little while.
16008        final int userId = UserHandle.getCallingUserId();
16009
16010        final PackageParser.Package pkg;
16011        synchronized (mPackages) {
16012            pkg = mPackages.get(packageName);
16013        }
16014
16015        mHandler.post(new Runnable() {
16016            public void run() {
16017                try (PackageFreezer freezer = freezePackage(packageName,
16018                        "deleteApplicationCacheFiles")) {
16019                    synchronized (mInstallLock) {
16020                        final int flags = StorageManager.FLAG_STORAGE_DE
16021                                | StorageManager.FLAG_STORAGE_CE;
16022                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16023                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16024                    }
16025                    clearExternalStorageDataSync(packageName, userId, false);
16026                }
16027                if (observer != null) {
16028                    try {
16029                        observer.onRemoveCompleted(packageName, true);
16030                    } catch (RemoteException e) {
16031                        Log.i(TAG, "Observer no longer exists.");
16032                    }
16033                }
16034            }
16035        });
16036    }
16037
16038    @Override
16039    public void getPackageSizeInfo(final String packageName, int userHandle,
16040            final IPackageStatsObserver observer) {
16041        mContext.enforceCallingOrSelfPermission(
16042                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16043        if (packageName == null) {
16044            throw new IllegalArgumentException("Attempt to get size of null packageName");
16045        }
16046
16047        PackageStats stats = new PackageStats(packageName, userHandle);
16048
16049        /*
16050         * Queue up an async operation since the package measurement may take a
16051         * little while.
16052         */
16053        Message msg = mHandler.obtainMessage(INIT_COPY);
16054        msg.obj = new MeasureParams(stats, observer);
16055        mHandler.sendMessage(msg);
16056    }
16057
16058    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16059        final PackageSetting ps;
16060        synchronized (mPackages) {
16061            ps = mSettings.mPackages.get(packageName);
16062            if (ps == null) {
16063                Slog.w(TAG, "Failed to find settings for " + packageName);
16064                return false;
16065            }
16066        }
16067        try {
16068            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16069                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16070                    ps.getCeDataInode(userId), ps.codePathString, stats);
16071            return true;
16072        } catch (InstallerException e) {
16073            Slog.w(TAG, String.valueOf(e));
16074            return false;
16075        }
16076    }
16077
16078    private int getUidTargetSdkVersionLockedLPr(int uid) {
16079        Object obj = mSettings.getUserIdLPr(uid);
16080        if (obj instanceof SharedUserSetting) {
16081            final SharedUserSetting sus = (SharedUserSetting) obj;
16082            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16083            final Iterator<PackageSetting> it = sus.packages.iterator();
16084            while (it.hasNext()) {
16085                final PackageSetting ps = it.next();
16086                if (ps.pkg != null) {
16087                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16088                    if (v < vers) vers = v;
16089                }
16090            }
16091            return vers;
16092        } else if (obj instanceof PackageSetting) {
16093            final PackageSetting ps = (PackageSetting) obj;
16094            if (ps.pkg != null) {
16095                return ps.pkg.applicationInfo.targetSdkVersion;
16096            }
16097        }
16098        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16099    }
16100
16101    @Override
16102    public void addPreferredActivity(IntentFilter filter, int match,
16103            ComponentName[] set, ComponentName activity, int userId) {
16104        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16105                "Adding preferred");
16106    }
16107
16108    private void addPreferredActivityInternal(IntentFilter filter, int match,
16109            ComponentName[] set, ComponentName activity, boolean always, int userId,
16110            String opname) {
16111        // writer
16112        int callingUid = Binder.getCallingUid();
16113        enforceCrossUserPermission(callingUid, userId,
16114                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16115        if (filter.countActions() == 0) {
16116            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16117            return;
16118        }
16119        synchronized (mPackages) {
16120            if (mContext.checkCallingOrSelfPermission(
16121                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16122                    != PackageManager.PERMISSION_GRANTED) {
16123                if (getUidTargetSdkVersionLockedLPr(callingUid)
16124                        < Build.VERSION_CODES.FROYO) {
16125                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16126                            + callingUid);
16127                    return;
16128                }
16129                mContext.enforceCallingOrSelfPermission(
16130                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16131            }
16132
16133            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16134            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16135                    + userId + ":");
16136            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16137            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16138            scheduleWritePackageRestrictionsLocked(userId);
16139        }
16140    }
16141
16142    @Override
16143    public void replacePreferredActivity(IntentFilter filter, int match,
16144            ComponentName[] set, ComponentName activity, int userId) {
16145        if (filter.countActions() != 1) {
16146            throw new IllegalArgumentException(
16147                    "replacePreferredActivity expects filter to have only 1 action.");
16148        }
16149        if (filter.countDataAuthorities() != 0
16150                || filter.countDataPaths() != 0
16151                || filter.countDataSchemes() > 1
16152                || filter.countDataTypes() != 0) {
16153            throw new IllegalArgumentException(
16154                    "replacePreferredActivity expects filter to have no data authorities, " +
16155                    "paths, or types; and at most one scheme.");
16156        }
16157
16158        final int callingUid = Binder.getCallingUid();
16159        enforceCrossUserPermission(callingUid, userId,
16160                true /* requireFullPermission */, false /* checkShell */,
16161                "replace preferred activity");
16162        synchronized (mPackages) {
16163            if (mContext.checkCallingOrSelfPermission(
16164                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16165                    != PackageManager.PERMISSION_GRANTED) {
16166                if (getUidTargetSdkVersionLockedLPr(callingUid)
16167                        < Build.VERSION_CODES.FROYO) {
16168                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16169                            + Binder.getCallingUid());
16170                    return;
16171                }
16172                mContext.enforceCallingOrSelfPermission(
16173                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16174            }
16175
16176            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16177            if (pir != null) {
16178                // Get all of the existing entries that exactly match this filter.
16179                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16180                if (existing != null && existing.size() == 1) {
16181                    PreferredActivity cur = existing.get(0);
16182                    if (DEBUG_PREFERRED) {
16183                        Slog.i(TAG, "Checking replace of preferred:");
16184                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16185                        if (!cur.mPref.mAlways) {
16186                            Slog.i(TAG, "  -- CUR; not mAlways!");
16187                        } else {
16188                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16189                            Slog.i(TAG, "  -- CUR: mSet="
16190                                    + Arrays.toString(cur.mPref.mSetComponents));
16191                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16192                            Slog.i(TAG, "  -- NEW: mMatch="
16193                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16194                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16195                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16196                        }
16197                    }
16198                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16199                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16200                            && cur.mPref.sameSet(set)) {
16201                        // Setting the preferred activity to what it happens to be already
16202                        if (DEBUG_PREFERRED) {
16203                            Slog.i(TAG, "Replacing with same preferred activity "
16204                                    + cur.mPref.mShortComponent + " for user "
16205                                    + userId + ":");
16206                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16207                        }
16208                        return;
16209                    }
16210                }
16211
16212                if (existing != null) {
16213                    if (DEBUG_PREFERRED) {
16214                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16215                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16216                    }
16217                    for (int i = 0; i < existing.size(); i++) {
16218                        PreferredActivity pa = existing.get(i);
16219                        if (DEBUG_PREFERRED) {
16220                            Slog.i(TAG, "Removing existing preferred activity "
16221                                    + pa.mPref.mComponent + ":");
16222                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16223                        }
16224                        pir.removeFilter(pa);
16225                    }
16226                }
16227            }
16228            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16229                    "Replacing preferred");
16230        }
16231    }
16232
16233    @Override
16234    public void clearPackagePreferredActivities(String packageName) {
16235        final int uid = Binder.getCallingUid();
16236        // writer
16237        synchronized (mPackages) {
16238            PackageParser.Package pkg = mPackages.get(packageName);
16239            if (pkg == null || pkg.applicationInfo.uid != uid) {
16240                if (mContext.checkCallingOrSelfPermission(
16241                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16242                        != PackageManager.PERMISSION_GRANTED) {
16243                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16244                            < Build.VERSION_CODES.FROYO) {
16245                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16246                                + Binder.getCallingUid());
16247                        return;
16248                    }
16249                    mContext.enforceCallingOrSelfPermission(
16250                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16251                }
16252            }
16253
16254            int user = UserHandle.getCallingUserId();
16255            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16256                scheduleWritePackageRestrictionsLocked(user);
16257            }
16258        }
16259    }
16260
16261    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16262    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16263        ArrayList<PreferredActivity> removed = null;
16264        boolean changed = false;
16265        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16266            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16267            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16268            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16269                continue;
16270            }
16271            Iterator<PreferredActivity> it = pir.filterIterator();
16272            while (it.hasNext()) {
16273                PreferredActivity pa = it.next();
16274                // Mark entry for removal only if it matches the package name
16275                // and the entry is of type "always".
16276                if (packageName == null ||
16277                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16278                                && pa.mPref.mAlways)) {
16279                    if (removed == null) {
16280                        removed = new ArrayList<PreferredActivity>();
16281                    }
16282                    removed.add(pa);
16283                }
16284            }
16285            if (removed != null) {
16286                for (int j=0; j<removed.size(); j++) {
16287                    PreferredActivity pa = removed.get(j);
16288                    pir.removeFilter(pa);
16289                }
16290                changed = true;
16291            }
16292        }
16293        return changed;
16294    }
16295
16296    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16297    private void clearIntentFilterVerificationsLPw(int userId) {
16298        final int packageCount = mPackages.size();
16299        for (int i = 0; i < packageCount; i++) {
16300            PackageParser.Package pkg = mPackages.valueAt(i);
16301            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16302        }
16303    }
16304
16305    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16306    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16307        if (userId == UserHandle.USER_ALL) {
16308            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16309                    sUserManager.getUserIds())) {
16310                for (int oneUserId : sUserManager.getUserIds()) {
16311                    scheduleWritePackageRestrictionsLocked(oneUserId);
16312                }
16313            }
16314        } else {
16315            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16316                scheduleWritePackageRestrictionsLocked(userId);
16317            }
16318        }
16319    }
16320
16321    void clearDefaultBrowserIfNeeded(String packageName) {
16322        for (int oneUserId : sUserManager.getUserIds()) {
16323            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16324            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16325            if (packageName.equals(defaultBrowserPackageName)) {
16326                setDefaultBrowserPackageName(null, oneUserId);
16327            }
16328        }
16329    }
16330
16331    @Override
16332    public void resetApplicationPreferences(int userId) {
16333        mContext.enforceCallingOrSelfPermission(
16334                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16335        // writer
16336        synchronized (mPackages) {
16337            final long identity = Binder.clearCallingIdentity();
16338            try {
16339                clearPackagePreferredActivitiesLPw(null, userId);
16340                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16341                // TODO: We have to reset the default SMS and Phone. This requires
16342                // significant refactoring to keep all default apps in the package
16343                // manager (cleaner but more work) or have the services provide
16344                // callbacks to the package manager to request a default app reset.
16345                applyFactoryDefaultBrowserLPw(userId);
16346                clearIntentFilterVerificationsLPw(userId);
16347                primeDomainVerificationsLPw(userId);
16348                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16349                scheduleWritePackageRestrictionsLocked(userId);
16350            } finally {
16351                Binder.restoreCallingIdentity(identity);
16352            }
16353        }
16354    }
16355
16356    @Override
16357    public int getPreferredActivities(List<IntentFilter> outFilters,
16358            List<ComponentName> outActivities, String packageName) {
16359
16360        int num = 0;
16361        final int userId = UserHandle.getCallingUserId();
16362        // reader
16363        synchronized (mPackages) {
16364            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16365            if (pir != null) {
16366                final Iterator<PreferredActivity> it = pir.filterIterator();
16367                while (it.hasNext()) {
16368                    final PreferredActivity pa = it.next();
16369                    if (packageName == null
16370                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16371                                    && pa.mPref.mAlways)) {
16372                        if (outFilters != null) {
16373                            outFilters.add(new IntentFilter(pa));
16374                        }
16375                        if (outActivities != null) {
16376                            outActivities.add(pa.mPref.mComponent);
16377                        }
16378                    }
16379                }
16380            }
16381        }
16382
16383        return num;
16384    }
16385
16386    @Override
16387    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16388            int userId) {
16389        int callingUid = Binder.getCallingUid();
16390        if (callingUid != Process.SYSTEM_UID) {
16391            throw new SecurityException(
16392                    "addPersistentPreferredActivity can only be run by the system");
16393        }
16394        if (filter.countActions() == 0) {
16395            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16396            return;
16397        }
16398        synchronized (mPackages) {
16399            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16400                    ":");
16401            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16402            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16403                    new PersistentPreferredActivity(filter, activity));
16404            scheduleWritePackageRestrictionsLocked(userId);
16405        }
16406    }
16407
16408    @Override
16409    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16410        int callingUid = Binder.getCallingUid();
16411        if (callingUid != Process.SYSTEM_UID) {
16412            throw new SecurityException(
16413                    "clearPackagePersistentPreferredActivities can only be run by the system");
16414        }
16415        ArrayList<PersistentPreferredActivity> removed = null;
16416        boolean changed = false;
16417        synchronized (mPackages) {
16418            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16419                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16420                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16421                        .valueAt(i);
16422                if (userId != thisUserId) {
16423                    continue;
16424                }
16425                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16426                while (it.hasNext()) {
16427                    PersistentPreferredActivity ppa = it.next();
16428                    // Mark entry for removal only if it matches the package name.
16429                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16430                        if (removed == null) {
16431                            removed = new ArrayList<PersistentPreferredActivity>();
16432                        }
16433                        removed.add(ppa);
16434                    }
16435                }
16436                if (removed != null) {
16437                    for (int j=0; j<removed.size(); j++) {
16438                        PersistentPreferredActivity ppa = removed.get(j);
16439                        ppir.removeFilter(ppa);
16440                    }
16441                    changed = true;
16442                }
16443            }
16444
16445            if (changed) {
16446                scheduleWritePackageRestrictionsLocked(userId);
16447            }
16448        }
16449    }
16450
16451    /**
16452     * Common machinery for picking apart a restored XML blob and passing
16453     * it to a caller-supplied functor to be applied to the running system.
16454     */
16455    private void restoreFromXml(XmlPullParser parser, int userId,
16456            String expectedStartTag, BlobXmlRestorer functor)
16457            throws IOException, XmlPullParserException {
16458        int type;
16459        while ((type = parser.next()) != XmlPullParser.START_TAG
16460                && type != XmlPullParser.END_DOCUMENT) {
16461        }
16462        if (type != XmlPullParser.START_TAG) {
16463            // oops didn't find a start tag?!
16464            if (DEBUG_BACKUP) {
16465                Slog.e(TAG, "Didn't find start tag during restore");
16466            }
16467            return;
16468        }
16469Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16470        // this is supposed to be TAG_PREFERRED_BACKUP
16471        if (!expectedStartTag.equals(parser.getName())) {
16472            if (DEBUG_BACKUP) {
16473                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16474            }
16475            return;
16476        }
16477
16478        // skip interfering stuff, then we're aligned with the backing implementation
16479        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16480Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16481        functor.apply(parser, userId);
16482    }
16483
16484    private interface BlobXmlRestorer {
16485        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16486    }
16487
16488    /**
16489     * Non-Binder method, support for the backup/restore mechanism: write the
16490     * full set of preferred activities in its canonical XML format.  Returns the
16491     * XML output as a byte array, or null if there is none.
16492     */
16493    @Override
16494    public byte[] getPreferredActivityBackup(int userId) {
16495        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16496            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16497        }
16498
16499        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16500        try {
16501            final XmlSerializer serializer = new FastXmlSerializer();
16502            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16503            serializer.startDocument(null, true);
16504            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16505
16506            synchronized (mPackages) {
16507                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16508            }
16509
16510            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16511            serializer.endDocument();
16512            serializer.flush();
16513        } catch (Exception e) {
16514            if (DEBUG_BACKUP) {
16515                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16516            }
16517            return null;
16518        }
16519
16520        return dataStream.toByteArray();
16521    }
16522
16523    @Override
16524    public void restorePreferredActivities(byte[] backup, int userId) {
16525        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16526            throw new SecurityException("Only the system may call restorePreferredActivities()");
16527        }
16528
16529        try {
16530            final XmlPullParser parser = Xml.newPullParser();
16531            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16532            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16533                    new BlobXmlRestorer() {
16534                        @Override
16535                        public void apply(XmlPullParser parser, int userId)
16536                                throws XmlPullParserException, IOException {
16537                            synchronized (mPackages) {
16538                                mSettings.readPreferredActivitiesLPw(parser, userId);
16539                            }
16540                        }
16541                    } );
16542        } catch (Exception e) {
16543            if (DEBUG_BACKUP) {
16544                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16545            }
16546        }
16547    }
16548
16549    /**
16550     * Non-Binder method, support for the backup/restore mechanism: write the
16551     * default browser (etc) settings in its canonical XML format.  Returns the default
16552     * browser XML representation as a byte array, or null if there is none.
16553     */
16554    @Override
16555    public byte[] getDefaultAppsBackup(int userId) {
16556        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16557            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16558        }
16559
16560        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16561        try {
16562            final XmlSerializer serializer = new FastXmlSerializer();
16563            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16564            serializer.startDocument(null, true);
16565            serializer.startTag(null, TAG_DEFAULT_APPS);
16566
16567            synchronized (mPackages) {
16568                mSettings.writeDefaultAppsLPr(serializer, userId);
16569            }
16570
16571            serializer.endTag(null, TAG_DEFAULT_APPS);
16572            serializer.endDocument();
16573            serializer.flush();
16574        } catch (Exception e) {
16575            if (DEBUG_BACKUP) {
16576                Slog.e(TAG, "Unable to write default apps for backup", e);
16577            }
16578            return null;
16579        }
16580
16581        return dataStream.toByteArray();
16582    }
16583
16584    @Override
16585    public void restoreDefaultApps(byte[] backup, int userId) {
16586        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16587            throw new SecurityException("Only the system may call restoreDefaultApps()");
16588        }
16589
16590        try {
16591            final XmlPullParser parser = Xml.newPullParser();
16592            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16593            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16594                    new BlobXmlRestorer() {
16595                        @Override
16596                        public void apply(XmlPullParser parser, int userId)
16597                                throws XmlPullParserException, IOException {
16598                            synchronized (mPackages) {
16599                                mSettings.readDefaultAppsLPw(parser, userId);
16600                            }
16601                        }
16602                    } );
16603        } catch (Exception e) {
16604            if (DEBUG_BACKUP) {
16605                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16606            }
16607        }
16608    }
16609
16610    @Override
16611    public byte[] getIntentFilterVerificationBackup(int userId) {
16612        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16613            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16614        }
16615
16616        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16617        try {
16618            final XmlSerializer serializer = new FastXmlSerializer();
16619            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16620            serializer.startDocument(null, true);
16621            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16622
16623            synchronized (mPackages) {
16624                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16625            }
16626
16627            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16628            serializer.endDocument();
16629            serializer.flush();
16630        } catch (Exception e) {
16631            if (DEBUG_BACKUP) {
16632                Slog.e(TAG, "Unable to write default apps for backup", e);
16633            }
16634            return null;
16635        }
16636
16637        return dataStream.toByteArray();
16638    }
16639
16640    @Override
16641    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16642        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16643            throw new SecurityException("Only the system may call restorePreferredActivities()");
16644        }
16645
16646        try {
16647            final XmlPullParser parser = Xml.newPullParser();
16648            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16649            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16650                    new BlobXmlRestorer() {
16651                        @Override
16652                        public void apply(XmlPullParser parser, int userId)
16653                                throws XmlPullParserException, IOException {
16654                            synchronized (mPackages) {
16655                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16656                                mSettings.writeLPr();
16657                            }
16658                        }
16659                    } );
16660        } catch (Exception e) {
16661            if (DEBUG_BACKUP) {
16662                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16663            }
16664        }
16665    }
16666
16667    @Override
16668    public byte[] getPermissionGrantBackup(int userId) {
16669        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16670            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16671        }
16672
16673        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16674        try {
16675            final XmlSerializer serializer = new FastXmlSerializer();
16676            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16677            serializer.startDocument(null, true);
16678            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16679
16680            synchronized (mPackages) {
16681                serializeRuntimePermissionGrantsLPr(serializer, userId);
16682            }
16683
16684            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16685            serializer.endDocument();
16686            serializer.flush();
16687        } catch (Exception e) {
16688            if (DEBUG_BACKUP) {
16689                Slog.e(TAG, "Unable to write default apps for backup", e);
16690            }
16691            return null;
16692        }
16693
16694        return dataStream.toByteArray();
16695    }
16696
16697    @Override
16698    public void restorePermissionGrants(byte[] backup, int userId) {
16699        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16700            throw new SecurityException("Only the system may call restorePermissionGrants()");
16701        }
16702
16703        try {
16704            final XmlPullParser parser = Xml.newPullParser();
16705            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16706            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16707                    new BlobXmlRestorer() {
16708                        @Override
16709                        public void apply(XmlPullParser parser, int userId)
16710                                throws XmlPullParserException, IOException {
16711                            synchronized (mPackages) {
16712                                processRestoredPermissionGrantsLPr(parser, userId);
16713                            }
16714                        }
16715                    } );
16716        } catch (Exception e) {
16717            if (DEBUG_BACKUP) {
16718                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16719            }
16720        }
16721    }
16722
16723    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16724            throws IOException {
16725        serializer.startTag(null, TAG_ALL_GRANTS);
16726
16727        final int N = mSettings.mPackages.size();
16728        for (int i = 0; i < N; i++) {
16729            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16730            boolean pkgGrantsKnown = false;
16731
16732            PermissionsState packagePerms = ps.getPermissionsState();
16733
16734            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16735                final int grantFlags = state.getFlags();
16736                // only look at grants that are not system/policy fixed
16737                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16738                    final boolean isGranted = state.isGranted();
16739                    // And only back up the user-twiddled state bits
16740                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16741                        final String packageName = mSettings.mPackages.keyAt(i);
16742                        if (!pkgGrantsKnown) {
16743                            serializer.startTag(null, TAG_GRANT);
16744                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16745                            pkgGrantsKnown = true;
16746                        }
16747
16748                        final boolean userSet =
16749                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16750                        final boolean userFixed =
16751                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16752                        final boolean revoke =
16753                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16754
16755                        serializer.startTag(null, TAG_PERMISSION);
16756                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16757                        if (isGranted) {
16758                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16759                        }
16760                        if (userSet) {
16761                            serializer.attribute(null, ATTR_USER_SET, "true");
16762                        }
16763                        if (userFixed) {
16764                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16765                        }
16766                        if (revoke) {
16767                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16768                        }
16769                        serializer.endTag(null, TAG_PERMISSION);
16770                    }
16771                }
16772            }
16773
16774            if (pkgGrantsKnown) {
16775                serializer.endTag(null, TAG_GRANT);
16776            }
16777        }
16778
16779        serializer.endTag(null, TAG_ALL_GRANTS);
16780    }
16781
16782    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16783            throws XmlPullParserException, IOException {
16784        String pkgName = null;
16785        int outerDepth = parser.getDepth();
16786        int type;
16787        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16788                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16789            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16790                continue;
16791            }
16792
16793            final String tagName = parser.getName();
16794            if (tagName.equals(TAG_GRANT)) {
16795                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16796                if (DEBUG_BACKUP) {
16797                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16798                }
16799            } else if (tagName.equals(TAG_PERMISSION)) {
16800
16801                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16802                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16803
16804                int newFlagSet = 0;
16805                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16806                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16807                }
16808                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16809                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16810                }
16811                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16812                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16813                }
16814                if (DEBUG_BACKUP) {
16815                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16816                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16817                }
16818                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16819                if (ps != null) {
16820                    // Already installed so we apply the grant immediately
16821                    if (DEBUG_BACKUP) {
16822                        Slog.v(TAG, "        + already installed; applying");
16823                    }
16824                    PermissionsState perms = ps.getPermissionsState();
16825                    BasePermission bp = mSettings.mPermissions.get(permName);
16826                    if (bp != null) {
16827                        if (isGranted) {
16828                            perms.grantRuntimePermission(bp, userId);
16829                        }
16830                        if (newFlagSet != 0) {
16831                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16832                        }
16833                    }
16834                } else {
16835                    // Need to wait for post-restore install to apply the grant
16836                    if (DEBUG_BACKUP) {
16837                        Slog.v(TAG, "        - not yet installed; saving for later");
16838                    }
16839                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16840                            isGranted, newFlagSet, userId);
16841                }
16842            } else {
16843                PackageManagerService.reportSettingsProblem(Log.WARN,
16844                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16845                XmlUtils.skipCurrentTag(parser);
16846            }
16847        }
16848
16849        scheduleWriteSettingsLocked();
16850        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16851    }
16852
16853    @Override
16854    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16855            int sourceUserId, int targetUserId, int flags) {
16856        mContext.enforceCallingOrSelfPermission(
16857                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16858        int callingUid = Binder.getCallingUid();
16859        enforceOwnerRights(ownerPackage, callingUid);
16860        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16861        if (intentFilter.countActions() == 0) {
16862            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16863            return;
16864        }
16865        synchronized (mPackages) {
16866            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16867                    ownerPackage, targetUserId, flags);
16868            CrossProfileIntentResolver resolver =
16869                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16870            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16871            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16872            if (existing != null) {
16873                int size = existing.size();
16874                for (int i = 0; i < size; i++) {
16875                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16876                        return;
16877                    }
16878                }
16879            }
16880            resolver.addFilter(newFilter);
16881            scheduleWritePackageRestrictionsLocked(sourceUserId);
16882        }
16883    }
16884
16885    @Override
16886    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16887        mContext.enforceCallingOrSelfPermission(
16888                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16889        int callingUid = Binder.getCallingUid();
16890        enforceOwnerRights(ownerPackage, callingUid);
16891        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16892        synchronized (mPackages) {
16893            CrossProfileIntentResolver resolver =
16894                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16895            ArraySet<CrossProfileIntentFilter> set =
16896                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16897            for (CrossProfileIntentFilter filter : set) {
16898                if (filter.getOwnerPackage().equals(ownerPackage)) {
16899                    resolver.removeFilter(filter);
16900                }
16901            }
16902            scheduleWritePackageRestrictionsLocked(sourceUserId);
16903        }
16904    }
16905
16906    // Enforcing that callingUid is owning pkg on userId
16907    private void enforceOwnerRights(String pkg, int callingUid) {
16908        // The system owns everything.
16909        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16910            return;
16911        }
16912        int callingUserId = UserHandle.getUserId(callingUid);
16913        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16914        if (pi == null) {
16915            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16916                    + callingUserId);
16917        }
16918        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16919            throw new SecurityException("Calling uid " + callingUid
16920                    + " does not own package " + pkg);
16921        }
16922    }
16923
16924    @Override
16925    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16926        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16927    }
16928
16929    private Intent getHomeIntent() {
16930        Intent intent = new Intent(Intent.ACTION_MAIN);
16931        intent.addCategory(Intent.CATEGORY_HOME);
16932        return intent;
16933    }
16934
16935    private IntentFilter getHomeFilter() {
16936        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16937        filter.addCategory(Intent.CATEGORY_HOME);
16938        filter.addCategory(Intent.CATEGORY_DEFAULT);
16939        return filter;
16940    }
16941
16942    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16943            int userId) {
16944        Intent intent  = getHomeIntent();
16945        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16946                PackageManager.GET_META_DATA, userId);
16947        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16948                true, false, false, userId);
16949
16950        allHomeCandidates.clear();
16951        if (list != null) {
16952            for (ResolveInfo ri : list) {
16953                allHomeCandidates.add(ri);
16954            }
16955        }
16956        return (preferred == null || preferred.activityInfo == null)
16957                ? null
16958                : new ComponentName(preferred.activityInfo.packageName,
16959                        preferred.activityInfo.name);
16960    }
16961
16962    @Override
16963    public void setHomeActivity(ComponentName comp, int userId) {
16964        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16965        getHomeActivitiesAsUser(homeActivities, userId);
16966
16967        boolean found = false;
16968
16969        final int size = homeActivities.size();
16970        final ComponentName[] set = new ComponentName[size];
16971        for (int i = 0; i < size; i++) {
16972            final ResolveInfo candidate = homeActivities.get(i);
16973            final ActivityInfo info = candidate.activityInfo;
16974            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16975            set[i] = activityName;
16976            if (!found && activityName.equals(comp)) {
16977                found = true;
16978            }
16979        }
16980        if (!found) {
16981            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16982                    + userId);
16983        }
16984        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16985                set, comp, userId);
16986    }
16987
16988    private @Nullable String getSetupWizardPackageName() {
16989        final Intent intent = new Intent(Intent.ACTION_MAIN);
16990        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
16991
16992        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
16993                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
16994                        | MATCH_DISABLED_COMPONENTS,
16995                UserHandle.myUserId());
16996        if (matches.size() == 1) {
16997            return matches.get(0).getComponentInfo().packageName;
16998        } else {
16999            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17000                    + ": matches=" + matches);
17001            return null;
17002        }
17003    }
17004
17005    @Override
17006    public void setApplicationEnabledSetting(String appPackageName,
17007            int newState, int flags, int userId, String callingPackage) {
17008        if (!sUserManager.exists(userId)) return;
17009        if (callingPackage == null) {
17010            callingPackage = Integer.toString(Binder.getCallingUid());
17011        }
17012        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17013    }
17014
17015    @Override
17016    public void setComponentEnabledSetting(ComponentName componentName,
17017            int newState, int flags, int userId) {
17018        if (!sUserManager.exists(userId)) return;
17019        setEnabledSetting(componentName.getPackageName(),
17020                componentName.getClassName(), newState, flags, userId, null);
17021    }
17022
17023    private void setEnabledSetting(final String packageName, String className, int newState,
17024            final int flags, int userId, String callingPackage) {
17025        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17026              || newState == COMPONENT_ENABLED_STATE_ENABLED
17027              || newState == COMPONENT_ENABLED_STATE_DISABLED
17028              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17029              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17030            throw new IllegalArgumentException("Invalid new component state: "
17031                    + newState);
17032        }
17033        PackageSetting pkgSetting;
17034        final int uid = Binder.getCallingUid();
17035        final int permission = mContext.checkCallingOrSelfPermission(
17036                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17037        enforceCrossUserPermission(uid, userId,
17038                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17039        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17040        boolean sendNow = false;
17041        boolean isApp = (className == null);
17042        String componentName = isApp ? packageName : className;
17043        int packageUid = -1;
17044        ArrayList<String> components;
17045
17046        // writer
17047        synchronized (mPackages) {
17048            pkgSetting = mSettings.mPackages.get(packageName);
17049            if (pkgSetting == null) {
17050                if (className == null) {
17051                    throw new IllegalArgumentException("Unknown package: " + packageName);
17052                }
17053                throw new IllegalArgumentException(
17054                        "Unknown component: " + packageName + "/" + className);
17055            }
17056            // Allow root and verify that userId is not being specified by a different user
17057            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17058                throw new SecurityException(
17059                        "Permission Denial: attempt to change component state from pid="
17060                        + Binder.getCallingPid()
17061                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17062            }
17063            if (className == null) {
17064                // We're dealing with an application/package level state change
17065                if (pkgSetting.getEnabled(userId) == newState) {
17066                    // Nothing to do
17067                    return;
17068                }
17069                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17070                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17071                    // Don't care about who enables an app.
17072                    callingPackage = null;
17073                }
17074                pkgSetting.setEnabled(newState, userId, callingPackage);
17075                // pkgSetting.pkg.mSetEnabled = newState;
17076            } else {
17077                // We're dealing with a component level state change
17078                // First, verify that this is a valid class name.
17079                PackageParser.Package pkg = pkgSetting.pkg;
17080                if (pkg == null || !pkg.hasComponentClassName(className)) {
17081                    if (pkg != null &&
17082                            pkg.applicationInfo.targetSdkVersion >=
17083                                    Build.VERSION_CODES.JELLY_BEAN) {
17084                        throw new IllegalArgumentException("Component class " + className
17085                                + " does not exist in " + packageName);
17086                    } else {
17087                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17088                                + className + " does not exist in " + packageName);
17089                    }
17090                }
17091                switch (newState) {
17092                case COMPONENT_ENABLED_STATE_ENABLED:
17093                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17094                        return;
17095                    }
17096                    break;
17097                case COMPONENT_ENABLED_STATE_DISABLED:
17098                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17099                        return;
17100                    }
17101                    break;
17102                case COMPONENT_ENABLED_STATE_DEFAULT:
17103                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17104                        return;
17105                    }
17106                    break;
17107                default:
17108                    Slog.e(TAG, "Invalid new component state: " + newState);
17109                    return;
17110                }
17111            }
17112            scheduleWritePackageRestrictionsLocked(userId);
17113            components = mPendingBroadcasts.get(userId, packageName);
17114            final boolean newPackage = components == null;
17115            if (newPackage) {
17116                components = new ArrayList<String>();
17117            }
17118            if (!components.contains(componentName)) {
17119                components.add(componentName);
17120            }
17121            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17122                sendNow = true;
17123                // Purge entry from pending broadcast list if another one exists already
17124                // since we are sending one right away.
17125                mPendingBroadcasts.remove(userId, packageName);
17126            } else {
17127                if (newPackage) {
17128                    mPendingBroadcasts.put(userId, packageName, components);
17129                }
17130                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17131                    // Schedule a message
17132                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17133                }
17134            }
17135        }
17136
17137        long callingId = Binder.clearCallingIdentity();
17138        try {
17139            if (sendNow) {
17140                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17141                sendPackageChangedBroadcast(packageName,
17142                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17143            }
17144        } finally {
17145            Binder.restoreCallingIdentity(callingId);
17146        }
17147    }
17148
17149    @Override
17150    public void flushPackageRestrictionsAsUser(int userId) {
17151        if (!sUserManager.exists(userId)) {
17152            return;
17153        }
17154        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17155                false /* checkShell */, "flushPackageRestrictions");
17156        synchronized (mPackages) {
17157            mSettings.writePackageRestrictionsLPr(userId);
17158            mDirtyUsers.remove(userId);
17159            if (mDirtyUsers.isEmpty()) {
17160                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17161            }
17162        }
17163    }
17164
17165    private void sendPackageChangedBroadcast(String packageName,
17166            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17167        if (DEBUG_INSTALL)
17168            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17169                    + componentNames);
17170        Bundle extras = new Bundle(4);
17171        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17172        String nameList[] = new String[componentNames.size()];
17173        componentNames.toArray(nameList);
17174        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17175        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17176        extras.putInt(Intent.EXTRA_UID, packageUid);
17177        // If this is not reporting a change of the overall package, then only send it
17178        // to registered receivers.  We don't want to launch a swath of apps for every
17179        // little component state change.
17180        final int flags = !componentNames.contains(packageName)
17181                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17182        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17183                new int[] {UserHandle.getUserId(packageUid)});
17184    }
17185
17186    @Override
17187    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17188        if (!sUserManager.exists(userId)) return;
17189        final int uid = Binder.getCallingUid();
17190        final int permission = mContext.checkCallingOrSelfPermission(
17191                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17192        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17193        enforceCrossUserPermission(uid, userId,
17194                true /* requireFullPermission */, true /* checkShell */, "stop package");
17195        // writer
17196        synchronized (mPackages) {
17197            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17198                    allowedByPermission, uid, userId)) {
17199                scheduleWritePackageRestrictionsLocked(userId);
17200            }
17201        }
17202    }
17203
17204    @Override
17205    public String getInstallerPackageName(String packageName) {
17206        // reader
17207        synchronized (mPackages) {
17208            return mSettings.getInstallerPackageNameLPr(packageName);
17209        }
17210    }
17211
17212    @Override
17213    public int getApplicationEnabledSetting(String packageName, int userId) {
17214        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17215        int uid = Binder.getCallingUid();
17216        enforceCrossUserPermission(uid, userId,
17217                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17218        // reader
17219        synchronized (mPackages) {
17220            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17221        }
17222    }
17223
17224    @Override
17225    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17226        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17227        int uid = Binder.getCallingUid();
17228        enforceCrossUserPermission(uid, userId,
17229                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17230        // reader
17231        synchronized (mPackages) {
17232            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17233        }
17234    }
17235
17236    @Override
17237    public void enterSafeMode() {
17238        enforceSystemOrRoot("Only the system can request entering safe mode");
17239
17240        if (!mSystemReady) {
17241            mSafeMode = true;
17242        }
17243    }
17244
17245    @Override
17246    public void systemReady() {
17247        mSystemReady = true;
17248
17249        // Read the compatibilty setting when the system is ready.
17250        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17251                mContext.getContentResolver(),
17252                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17253        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17254        if (DEBUG_SETTINGS) {
17255            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17256        }
17257
17258        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17259
17260        synchronized (mPackages) {
17261            // Verify that all of the preferred activity components actually
17262            // exist.  It is possible for applications to be updated and at
17263            // that point remove a previously declared activity component that
17264            // had been set as a preferred activity.  We try to clean this up
17265            // the next time we encounter that preferred activity, but it is
17266            // possible for the user flow to never be able to return to that
17267            // situation so here we do a sanity check to make sure we haven't
17268            // left any junk around.
17269            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17270            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17271                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17272                removed.clear();
17273                for (PreferredActivity pa : pir.filterSet()) {
17274                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17275                        removed.add(pa);
17276                    }
17277                }
17278                if (removed.size() > 0) {
17279                    for (int r=0; r<removed.size(); r++) {
17280                        PreferredActivity pa = removed.get(r);
17281                        Slog.w(TAG, "Removing dangling preferred activity: "
17282                                + pa.mPref.mComponent);
17283                        pir.removeFilter(pa);
17284                    }
17285                    mSettings.writePackageRestrictionsLPr(
17286                            mSettings.mPreferredActivities.keyAt(i));
17287                }
17288            }
17289
17290            for (int userId : UserManagerService.getInstance().getUserIds()) {
17291                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17292                    grantPermissionsUserIds = ArrayUtils.appendInt(
17293                            grantPermissionsUserIds, userId);
17294                }
17295            }
17296        }
17297        sUserManager.systemReady();
17298
17299        // If we upgraded grant all default permissions before kicking off.
17300        for (int userId : grantPermissionsUserIds) {
17301            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17302        }
17303
17304        // Kick off any messages waiting for system ready
17305        if (mPostSystemReadyMessages != null) {
17306            for (Message msg : mPostSystemReadyMessages) {
17307                msg.sendToTarget();
17308            }
17309            mPostSystemReadyMessages = null;
17310        }
17311
17312        // Watch for external volumes that come and go over time
17313        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17314        storage.registerListener(mStorageListener);
17315
17316        mInstallerService.systemReady();
17317        mPackageDexOptimizer.systemReady();
17318
17319        MountServiceInternal mountServiceInternal = LocalServices.getService(
17320                MountServiceInternal.class);
17321        mountServiceInternal.addExternalStoragePolicy(
17322                new MountServiceInternal.ExternalStorageMountPolicy() {
17323            @Override
17324            public int getMountMode(int uid, String packageName) {
17325                if (Process.isIsolated(uid)) {
17326                    return Zygote.MOUNT_EXTERNAL_NONE;
17327                }
17328                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17329                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17330                }
17331                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17332                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17333                }
17334                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17335                    return Zygote.MOUNT_EXTERNAL_READ;
17336                }
17337                return Zygote.MOUNT_EXTERNAL_WRITE;
17338            }
17339
17340            @Override
17341            public boolean hasExternalStorage(int uid, String packageName) {
17342                return true;
17343            }
17344        });
17345    }
17346
17347    @Override
17348    public boolean isSafeMode() {
17349        return mSafeMode;
17350    }
17351
17352    @Override
17353    public boolean hasSystemUidErrors() {
17354        return mHasSystemUidErrors;
17355    }
17356
17357    static String arrayToString(int[] array) {
17358        StringBuffer buf = new StringBuffer(128);
17359        buf.append('[');
17360        if (array != null) {
17361            for (int i=0; i<array.length; i++) {
17362                if (i > 0) buf.append(", ");
17363                buf.append(array[i]);
17364            }
17365        }
17366        buf.append(']');
17367        return buf.toString();
17368    }
17369
17370    static class DumpState {
17371        public static final int DUMP_LIBS = 1 << 0;
17372        public static final int DUMP_FEATURES = 1 << 1;
17373        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17374        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17375        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17376        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17377        public static final int DUMP_PERMISSIONS = 1 << 6;
17378        public static final int DUMP_PACKAGES = 1 << 7;
17379        public static final int DUMP_SHARED_USERS = 1 << 8;
17380        public static final int DUMP_MESSAGES = 1 << 9;
17381        public static final int DUMP_PROVIDERS = 1 << 10;
17382        public static final int DUMP_VERIFIERS = 1 << 11;
17383        public static final int DUMP_PREFERRED = 1 << 12;
17384        public static final int DUMP_PREFERRED_XML = 1 << 13;
17385        public static final int DUMP_KEYSETS = 1 << 14;
17386        public static final int DUMP_VERSION = 1 << 15;
17387        public static final int DUMP_INSTALLS = 1 << 16;
17388        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17389        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17390        public static final int DUMP_FROZEN = 1 << 19;
17391
17392        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17393
17394        private int mTypes;
17395
17396        private int mOptions;
17397
17398        private boolean mTitlePrinted;
17399
17400        private SharedUserSetting mSharedUser;
17401
17402        public boolean isDumping(int type) {
17403            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17404                return true;
17405            }
17406
17407            return (mTypes & type) != 0;
17408        }
17409
17410        public void setDump(int type) {
17411            mTypes |= type;
17412        }
17413
17414        public boolean isOptionEnabled(int option) {
17415            return (mOptions & option) != 0;
17416        }
17417
17418        public void setOptionEnabled(int option) {
17419            mOptions |= option;
17420        }
17421
17422        public boolean onTitlePrinted() {
17423            final boolean printed = mTitlePrinted;
17424            mTitlePrinted = true;
17425            return printed;
17426        }
17427
17428        public boolean getTitlePrinted() {
17429            return mTitlePrinted;
17430        }
17431
17432        public void setTitlePrinted(boolean enabled) {
17433            mTitlePrinted = enabled;
17434        }
17435
17436        public SharedUserSetting getSharedUser() {
17437            return mSharedUser;
17438        }
17439
17440        public void setSharedUser(SharedUserSetting user) {
17441            mSharedUser = user;
17442        }
17443    }
17444
17445    @Override
17446    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17447            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17448        (new PackageManagerShellCommand(this)).exec(
17449                this, in, out, err, args, resultReceiver);
17450    }
17451
17452    @Override
17453    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17454        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17455                != PackageManager.PERMISSION_GRANTED) {
17456            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17457                    + Binder.getCallingPid()
17458                    + ", uid=" + Binder.getCallingUid()
17459                    + " without permission "
17460                    + android.Manifest.permission.DUMP);
17461            return;
17462        }
17463
17464        DumpState dumpState = new DumpState();
17465        boolean fullPreferred = false;
17466        boolean checkin = false;
17467
17468        String packageName = null;
17469        ArraySet<String> permissionNames = null;
17470
17471        int opti = 0;
17472        while (opti < args.length) {
17473            String opt = args[opti];
17474            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17475                break;
17476            }
17477            opti++;
17478
17479            if ("-a".equals(opt)) {
17480                // Right now we only know how to print all.
17481            } else if ("-h".equals(opt)) {
17482                pw.println("Package manager dump options:");
17483                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17484                pw.println("    --checkin: dump for a checkin");
17485                pw.println("    -f: print details of intent filters");
17486                pw.println("    -h: print this help");
17487                pw.println("  cmd may be one of:");
17488                pw.println("    l[ibraries]: list known shared libraries");
17489                pw.println("    f[eatures]: list device features");
17490                pw.println("    k[eysets]: print known keysets");
17491                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17492                pw.println("    perm[issions]: dump permissions");
17493                pw.println("    permission [name ...]: dump declaration and use of given permission");
17494                pw.println("    pref[erred]: print preferred package settings");
17495                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17496                pw.println("    prov[iders]: dump content providers");
17497                pw.println("    p[ackages]: dump installed packages");
17498                pw.println("    s[hared-users]: dump shared user IDs");
17499                pw.println("    m[essages]: print collected runtime messages");
17500                pw.println("    v[erifiers]: print package verifier info");
17501                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17502                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17503                pw.println("    version: print database version info");
17504                pw.println("    write: write current settings now");
17505                pw.println("    installs: details about install sessions");
17506                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17507                pw.println("    <package.name>: info about given package");
17508                return;
17509            } else if ("--checkin".equals(opt)) {
17510                checkin = true;
17511            } else if ("-f".equals(opt)) {
17512                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17513            } else {
17514                pw.println("Unknown argument: " + opt + "; use -h for help");
17515            }
17516        }
17517
17518        // Is the caller requesting to dump a particular piece of data?
17519        if (opti < args.length) {
17520            String cmd = args[opti];
17521            opti++;
17522            // Is this a package name?
17523            if ("android".equals(cmd) || cmd.contains(".")) {
17524                packageName = cmd;
17525                // When dumping a single package, we always dump all of its
17526                // filter information since the amount of data will be reasonable.
17527                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17528            } else if ("check-permission".equals(cmd)) {
17529                if (opti >= args.length) {
17530                    pw.println("Error: check-permission missing permission argument");
17531                    return;
17532                }
17533                String perm = args[opti];
17534                opti++;
17535                if (opti >= args.length) {
17536                    pw.println("Error: check-permission missing package argument");
17537                    return;
17538                }
17539                String pkg = args[opti];
17540                opti++;
17541                int user = UserHandle.getUserId(Binder.getCallingUid());
17542                if (opti < args.length) {
17543                    try {
17544                        user = Integer.parseInt(args[opti]);
17545                    } catch (NumberFormatException e) {
17546                        pw.println("Error: check-permission user argument is not a number: "
17547                                + args[opti]);
17548                        return;
17549                    }
17550                }
17551                pw.println(checkPermission(perm, pkg, user));
17552                return;
17553            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17554                dumpState.setDump(DumpState.DUMP_LIBS);
17555            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17556                dumpState.setDump(DumpState.DUMP_FEATURES);
17557            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17558                if (opti >= args.length) {
17559                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17560                            | DumpState.DUMP_SERVICE_RESOLVERS
17561                            | DumpState.DUMP_RECEIVER_RESOLVERS
17562                            | DumpState.DUMP_CONTENT_RESOLVERS);
17563                } else {
17564                    while (opti < args.length) {
17565                        String name = args[opti];
17566                        if ("a".equals(name) || "activity".equals(name)) {
17567                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17568                        } else if ("s".equals(name) || "service".equals(name)) {
17569                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17570                        } else if ("r".equals(name) || "receiver".equals(name)) {
17571                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17572                        } else if ("c".equals(name) || "content".equals(name)) {
17573                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17574                        } else {
17575                            pw.println("Error: unknown resolver table type: " + name);
17576                            return;
17577                        }
17578                        opti++;
17579                    }
17580                }
17581            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17582                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17583            } else if ("permission".equals(cmd)) {
17584                if (opti >= args.length) {
17585                    pw.println("Error: permission requires permission name");
17586                    return;
17587                }
17588                permissionNames = new ArraySet<>();
17589                while (opti < args.length) {
17590                    permissionNames.add(args[opti]);
17591                    opti++;
17592                }
17593                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17594                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17595            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17596                dumpState.setDump(DumpState.DUMP_PREFERRED);
17597            } else if ("preferred-xml".equals(cmd)) {
17598                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17599                if (opti < args.length && "--full".equals(args[opti])) {
17600                    fullPreferred = true;
17601                    opti++;
17602                }
17603            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17604                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17605            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17606                dumpState.setDump(DumpState.DUMP_PACKAGES);
17607            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17608                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17609            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17610                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17611            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17612                dumpState.setDump(DumpState.DUMP_MESSAGES);
17613            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17614                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17615            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17616                    || "intent-filter-verifiers".equals(cmd)) {
17617                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17618            } else if ("version".equals(cmd)) {
17619                dumpState.setDump(DumpState.DUMP_VERSION);
17620            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17621                dumpState.setDump(DumpState.DUMP_KEYSETS);
17622            } else if ("installs".equals(cmd)) {
17623                dumpState.setDump(DumpState.DUMP_INSTALLS);
17624            } else if ("frozen".equals(cmd)) {
17625                dumpState.setDump(DumpState.DUMP_FROZEN);
17626            } else if ("write".equals(cmd)) {
17627                synchronized (mPackages) {
17628                    mSettings.writeLPr();
17629                    pw.println("Settings written.");
17630                    return;
17631                }
17632            }
17633        }
17634
17635        if (checkin) {
17636            pw.println("vers,1");
17637        }
17638
17639        // reader
17640        synchronized (mPackages) {
17641            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17642                if (!checkin) {
17643                    if (dumpState.onTitlePrinted())
17644                        pw.println();
17645                    pw.println("Database versions:");
17646                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17647                }
17648            }
17649
17650            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17651                if (!checkin) {
17652                    if (dumpState.onTitlePrinted())
17653                        pw.println();
17654                    pw.println("Verifiers:");
17655                    pw.print("  Required: ");
17656                    pw.print(mRequiredVerifierPackage);
17657                    pw.print(" (uid=");
17658                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17659                            UserHandle.USER_SYSTEM));
17660                    pw.println(")");
17661                } else if (mRequiredVerifierPackage != null) {
17662                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17663                    pw.print(",");
17664                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17665                            UserHandle.USER_SYSTEM));
17666                }
17667            }
17668
17669            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17670                    packageName == null) {
17671                if (mIntentFilterVerifierComponent != null) {
17672                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17673                    if (!checkin) {
17674                        if (dumpState.onTitlePrinted())
17675                            pw.println();
17676                        pw.println("Intent Filter Verifier:");
17677                        pw.print("  Using: ");
17678                        pw.print(verifierPackageName);
17679                        pw.print(" (uid=");
17680                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17681                                UserHandle.USER_SYSTEM));
17682                        pw.println(")");
17683                    } else if (verifierPackageName != null) {
17684                        pw.print("ifv,"); pw.print(verifierPackageName);
17685                        pw.print(",");
17686                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17687                                UserHandle.USER_SYSTEM));
17688                    }
17689                } else {
17690                    pw.println();
17691                    pw.println("No Intent Filter Verifier available!");
17692                }
17693            }
17694
17695            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17696                boolean printedHeader = false;
17697                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17698                while (it.hasNext()) {
17699                    String name = it.next();
17700                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17701                    if (!checkin) {
17702                        if (!printedHeader) {
17703                            if (dumpState.onTitlePrinted())
17704                                pw.println();
17705                            pw.println("Libraries:");
17706                            printedHeader = true;
17707                        }
17708                        pw.print("  ");
17709                    } else {
17710                        pw.print("lib,");
17711                    }
17712                    pw.print(name);
17713                    if (!checkin) {
17714                        pw.print(" -> ");
17715                    }
17716                    if (ent.path != null) {
17717                        if (!checkin) {
17718                            pw.print("(jar) ");
17719                            pw.print(ent.path);
17720                        } else {
17721                            pw.print(",jar,");
17722                            pw.print(ent.path);
17723                        }
17724                    } else {
17725                        if (!checkin) {
17726                            pw.print("(apk) ");
17727                            pw.print(ent.apk);
17728                        } else {
17729                            pw.print(",apk,");
17730                            pw.print(ent.apk);
17731                        }
17732                    }
17733                    pw.println();
17734                }
17735            }
17736
17737            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17738                if (dumpState.onTitlePrinted())
17739                    pw.println();
17740                if (!checkin) {
17741                    pw.println("Features:");
17742                }
17743
17744                for (FeatureInfo feat : mAvailableFeatures.values()) {
17745                    if (checkin) {
17746                        pw.print("feat,");
17747                        pw.print(feat.name);
17748                        pw.print(",");
17749                        pw.println(feat.version);
17750                    } else {
17751                        pw.print("  ");
17752                        pw.print(feat.name);
17753                        if (feat.version > 0) {
17754                            pw.print(" version=");
17755                            pw.print(feat.version);
17756                        }
17757                        pw.println();
17758                    }
17759                }
17760            }
17761
17762            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17763                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17764                        : "Activity Resolver Table:", "  ", packageName,
17765                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17766                    dumpState.setTitlePrinted(true);
17767                }
17768            }
17769            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17770                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17771                        : "Receiver Resolver Table:", "  ", packageName,
17772                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17773                    dumpState.setTitlePrinted(true);
17774                }
17775            }
17776            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17777                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17778                        : "Service Resolver Table:", "  ", packageName,
17779                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17780                    dumpState.setTitlePrinted(true);
17781                }
17782            }
17783            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17784                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17785                        : "Provider Resolver Table:", "  ", packageName,
17786                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17787                    dumpState.setTitlePrinted(true);
17788                }
17789            }
17790
17791            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17792                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17793                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17794                    int user = mSettings.mPreferredActivities.keyAt(i);
17795                    if (pir.dump(pw,
17796                            dumpState.getTitlePrinted()
17797                                ? "\nPreferred Activities User " + user + ":"
17798                                : "Preferred Activities User " + user + ":", "  ",
17799                            packageName, true, false)) {
17800                        dumpState.setTitlePrinted(true);
17801                    }
17802                }
17803            }
17804
17805            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17806                pw.flush();
17807                FileOutputStream fout = new FileOutputStream(fd);
17808                BufferedOutputStream str = new BufferedOutputStream(fout);
17809                XmlSerializer serializer = new FastXmlSerializer();
17810                try {
17811                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17812                    serializer.startDocument(null, true);
17813                    serializer.setFeature(
17814                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17815                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17816                    serializer.endDocument();
17817                    serializer.flush();
17818                } catch (IllegalArgumentException e) {
17819                    pw.println("Failed writing: " + e);
17820                } catch (IllegalStateException e) {
17821                    pw.println("Failed writing: " + e);
17822                } catch (IOException e) {
17823                    pw.println("Failed writing: " + e);
17824                }
17825            }
17826
17827            if (!checkin
17828                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17829                    && packageName == null) {
17830                pw.println();
17831                int count = mSettings.mPackages.size();
17832                if (count == 0) {
17833                    pw.println("No applications!");
17834                    pw.println();
17835                } else {
17836                    final String prefix = "  ";
17837                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17838                    if (allPackageSettings.size() == 0) {
17839                        pw.println("No domain preferred apps!");
17840                        pw.println();
17841                    } else {
17842                        pw.println("App verification status:");
17843                        pw.println();
17844                        count = 0;
17845                        for (PackageSetting ps : allPackageSettings) {
17846                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17847                            if (ivi == null || ivi.getPackageName() == null) continue;
17848                            pw.println(prefix + "Package: " + ivi.getPackageName());
17849                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17850                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17851                            pw.println();
17852                            count++;
17853                        }
17854                        if (count == 0) {
17855                            pw.println(prefix + "No app verification established.");
17856                            pw.println();
17857                        }
17858                        for (int userId : sUserManager.getUserIds()) {
17859                            pw.println("App linkages for user " + userId + ":");
17860                            pw.println();
17861                            count = 0;
17862                            for (PackageSetting ps : allPackageSettings) {
17863                                final long status = ps.getDomainVerificationStatusForUser(userId);
17864                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17865                                    continue;
17866                                }
17867                                pw.println(prefix + "Package: " + ps.name);
17868                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17869                                String statusStr = IntentFilterVerificationInfo.
17870                                        getStatusStringFromValue(status);
17871                                pw.println(prefix + "Status:  " + statusStr);
17872                                pw.println();
17873                                count++;
17874                            }
17875                            if (count == 0) {
17876                                pw.println(prefix + "No configured app linkages.");
17877                                pw.println();
17878                            }
17879                        }
17880                    }
17881                }
17882            }
17883
17884            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17885                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17886                if (packageName == null && permissionNames == null) {
17887                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17888                        if (iperm == 0) {
17889                            if (dumpState.onTitlePrinted())
17890                                pw.println();
17891                            pw.println("AppOp Permissions:");
17892                        }
17893                        pw.print("  AppOp Permission ");
17894                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17895                        pw.println(":");
17896                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17897                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17898                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17899                        }
17900                    }
17901                }
17902            }
17903
17904            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17905                boolean printedSomething = false;
17906                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17907                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17908                        continue;
17909                    }
17910                    if (!printedSomething) {
17911                        if (dumpState.onTitlePrinted())
17912                            pw.println();
17913                        pw.println("Registered ContentProviders:");
17914                        printedSomething = true;
17915                    }
17916                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17917                    pw.print("    "); pw.println(p.toString());
17918                }
17919                printedSomething = false;
17920                for (Map.Entry<String, PackageParser.Provider> entry :
17921                        mProvidersByAuthority.entrySet()) {
17922                    PackageParser.Provider p = entry.getValue();
17923                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17924                        continue;
17925                    }
17926                    if (!printedSomething) {
17927                        if (dumpState.onTitlePrinted())
17928                            pw.println();
17929                        pw.println("ContentProvider Authorities:");
17930                        printedSomething = true;
17931                    }
17932                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17933                    pw.print("    "); pw.println(p.toString());
17934                    if (p.info != null && p.info.applicationInfo != null) {
17935                        final String appInfo = p.info.applicationInfo.toString();
17936                        pw.print("      applicationInfo="); pw.println(appInfo);
17937                    }
17938                }
17939            }
17940
17941            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17942                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17943            }
17944
17945            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17946                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17947            }
17948
17949            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17950                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17951            }
17952
17953            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17954                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17955            }
17956
17957            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17958                // XXX should handle packageName != null by dumping only install data that
17959                // the given package is involved with.
17960                if (dumpState.onTitlePrinted()) pw.println();
17961                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17962            }
17963
17964            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
17965                // XXX should handle packageName != null by dumping only install data that
17966                // the given package is involved with.
17967                if (dumpState.onTitlePrinted()) pw.println();
17968
17969                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
17970                ipw.println();
17971                ipw.println("Frozen packages:");
17972                ipw.increaseIndent();
17973                if (mFrozenPackages.size() == 0) {
17974                    ipw.println("(none)");
17975                } else {
17976                    for (int i = 0; i < mFrozenPackages.size(); i++) {
17977                        ipw.println(mFrozenPackages.valueAt(i));
17978                    }
17979                }
17980                ipw.decreaseIndent();
17981            }
17982
17983            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17984                if (dumpState.onTitlePrinted()) pw.println();
17985                mSettings.dumpReadMessagesLPr(pw, dumpState);
17986
17987                pw.println();
17988                pw.println("Package warning messages:");
17989                BufferedReader in = null;
17990                String line = null;
17991                try {
17992                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17993                    while ((line = in.readLine()) != null) {
17994                        if (line.contains("ignored: updated version")) continue;
17995                        pw.println(line);
17996                    }
17997                } catch (IOException ignored) {
17998                } finally {
17999                    IoUtils.closeQuietly(in);
18000                }
18001            }
18002
18003            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18004                BufferedReader in = null;
18005                String line = null;
18006                try {
18007                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18008                    while ((line = in.readLine()) != null) {
18009                        if (line.contains("ignored: updated version")) continue;
18010                        pw.print("msg,");
18011                        pw.println(line);
18012                    }
18013                } catch (IOException ignored) {
18014                } finally {
18015                    IoUtils.closeQuietly(in);
18016                }
18017            }
18018        }
18019    }
18020
18021    private String dumpDomainString(String packageName) {
18022        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18023                .getList();
18024        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18025
18026        ArraySet<String> result = new ArraySet<>();
18027        if (iviList.size() > 0) {
18028            for (IntentFilterVerificationInfo ivi : iviList) {
18029                for (String host : ivi.getDomains()) {
18030                    result.add(host);
18031                }
18032            }
18033        }
18034        if (filters != null && filters.size() > 0) {
18035            for (IntentFilter filter : filters) {
18036                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18037                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18038                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18039                    result.addAll(filter.getHostsList());
18040                }
18041            }
18042        }
18043
18044        StringBuilder sb = new StringBuilder(result.size() * 16);
18045        for (String domain : result) {
18046            if (sb.length() > 0) sb.append(" ");
18047            sb.append(domain);
18048        }
18049        return sb.toString();
18050    }
18051
18052    // ------- apps on sdcard specific code -------
18053    static final boolean DEBUG_SD_INSTALL = false;
18054
18055    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18056
18057    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18058
18059    private boolean mMediaMounted = false;
18060
18061    static String getEncryptKey() {
18062        try {
18063            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18064                    SD_ENCRYPTION_KEYSTORE_NAME);
18065            if (sdEncKey == null) {
18066                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18067                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18068                if (sdEncKey == null) {
18069                    Slog.e(TAG, "Failed to create encryption keys");
18070                    return null;
18071                }
18072            }
18073            return sdEncKey;
18074        } catch (NoSuchAlgorithmException nsae) {
18075            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18076            return null;
18077        } catch (IOException ioe) {
18078            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18079            return null;
18080        }
18081    }
18082
18083    /*
18084     * Update media status on PackageManager.
18085     */
18086    @Override
18087    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18088        int callingUid = Binder.getCallingUid();
18089        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18090            throw new SecurityException("Media status can only be updated by the system");
18091        }
18092        // reader; this apparently protects mMediaMounted, but should probably
18093        // be a different lock in that case.
18094        synchronized (mPackages) {
18095            Log.i(TAG, "Updating external media status from "
18096                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18097                    + (mediaStatus ? "mounted" : "unmounted"));
18098            if (DEBUG_SD_INSTALL)
18099                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18100                        + ", mMediaMounted=" + mMediaMounted);
18101            if (mediaStatus == mMediaMounted) {
18102                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18103                        : 0, -1);
18104                mHandler.sendMessage(msg);
18105                return;
18106            }
18107            mMediaMounted = mediaStatus;
18108        }
18109        // Queue up an async operation since the package installation may take a
18110        // little while.
18111        mHandler.post(new Runnable() {
18112            public void run() {
18113                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18114            }
18115        });
18116    }
18117
18118    /**
18119     * Called by MountService when the initial ASECs to scan are available.
18120     * Should block until all the ASEC containers are finished being scanned.
18121     */
18122    public void scanAvailableAsecs() {
18123        updateExternalMediaStatusInner(true, false, false);
18124    }
18125
18126    /*
18127     * Collect information of applications on external media, map them against
18128     * existing containers and update information based on current mount status.
18129     * Please note that we always have to report status if reportStatus has been
18130     * set to true especially when unloading packages.
18131     */
18132    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18133            boolean externalStorage) {
18134        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18135        int[] uidArr = EmptyArray.INT;
18136
18137        final String[] list = PackageHelper.getSecureContainerList();
18138        if (ArrayUtils.isEmpty(list)) {
18139            Log.i(TAG, "No secure containers found");
18140        } else {
18141            // Process list of secure containers and categorize them
18142            // as active or stale based on their package internal state.
18143
18144            // reader
18145            synchronized (mPackages) {
18146                for (String cid : list) {
18147                    // Leave stages untouched for now; installer service owns them
18148                    if (PackageInstallerService.isStageName(cid)) continue;
18149
18150                    if (DEBUG_SD_INSTALL)
18151                        Log.i(TAG, "Processing container " + cid);
18152                    String pkgName = getAsecPackageName(cid);
18153                    if (pkgName == null) {
18154                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18155                        continue;
18156                    }
18157                    if (DEBUG_SD_INSTALL)
18158                        Log.i(TAG, "Looking for pkg : " + pkgName);
18159
18160                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18161                    if (ps == null) {
18162                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18163                        continue;
18164                    }
18165
18166                    /*
18167                     * Skip packages that are not external if we're unmounting
18168                     * external storage.
18169                     */
18170                    if (externalStorage && !isMounted && !isExternal(ps)) {
18171                        continue;
18172                    }
18173
18174                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18175                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18176                    // The package status is changed only if the code path
18177                    // matches between settings and the container id.
18178                    if (ps.codePathString != null
18179                            && ps.codePathString.startsWith(args.getCodePath())) {
18180                        if (DEBUG_SD_INSTALL) {
18181                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18182                                    + " at code path: " + ps.codePathString);
18183                        }
18184
18185                        // We do have a valid package installed on sdcard
18186                        processCids.put(args, ps.codePathString);
18187                        final int uid = ps.appId;
18188                        if (uid != -1) {
18189                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18190                        }
18191                    } else {
18192                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18193                                + ps.codePathString);
18194                    }
18195                }
18196            }
18197
18198            Arrays.sort(uidArr);
18199        }
18200
18201        // Process packages with valid entries.
18202        if (isMounted) {
18203            if (DEBUG_SD_INSTALL)
18204                Log.i(TAG, "Loading packages");
18205            loadMediaPackages(processCids, uidArr, externalStorage);
18206            startCleaningPackages();
18207            mInstallerService.onSecureContainersAvailable();
18208        } else {
18209            if (DEBUG_SD_INSTALL)
18210                Log.i(TAG, "Unloading packages");
18211            unloadMediaPackages(processCids, uidArr, reportStatus);
18212        }
18213    }
18214
18215    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18216            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18217        final int size = infos.size();
18218        final String[] packageNames = new String[size];
18219        final int[] packageUids = new int[size];
18220        for (int i = 0; i < size; i++) {
18221            final ApplicationInfo info = infos.get(i);
18222            packageNames[i] = info.packageName;
18223            packageUids[i] = info.uid;
18224        }
18225        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18226                finishedReceiver);
18227    }
18228
18229    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18230            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18231        sendResourcesChangedBroadcast(mediaStatus, replacing,
18232                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18233    }
18234
18235    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18236            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18237        int size = pkgList.length;
18238        if (size > 0) {
18239            // Send broadcasts here
18240            Bundle extras = new Bundle();
18241            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18242            if (uidArr != null) {
18243                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18244            }
18245            if (replacing) {
18246                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18247            }
18248            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18249                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18250            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18251        }
18252    }
18253
18254   /*
18255     * Look at potentially valid container ids from processCids If package
18256     * information doesn't match the one on record or package scanning fails,
18257     * the cid is added to list of removeCids. We currently don't delete stale
18258     * containers.
18259     */
18260    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18261            boolean externalStorage) {
18262        ArrayList<String> pkgList = new ArrayList<String>();
18263        Set<AsecInstallArgs> keys = processCids.keySet();
18264
18265        for (AsecInstallArgs args : keys) {
18266            String codePath = processCids.get(args);
18267            if (DEBUG_SD_INSTALL)
18268                Log.i(TAG, "Loading container : " + args.cid);
18269            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18270            try {
18271                // Make sure there are no container errors first.
18272                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18273                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18274                            + " when installing from sdcard");
18275                    continue;
18276                }
18277                // Check code path here.
18278                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18279                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18280                            + " does not match one in settings " + codePath);
18281                    continue;
18282                }
18283                // Parse package
18284                int parseFlags = mDefParseFlags;
18285                if (args.isExternalAsec()) {
18286                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18287                }
18288                if (args.isFwdLocked()) {
18289                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18290                }
18291
18292                synchronized (mInstallLock) {
18293                    PackageParser.Package pkg = null;
18294                    try {
18295                        // Sadly we don't know the package name yet to freeze it
18296                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18297                                SCAN_IGNORE_FROZEN, 0, null);
18298                    } catch (PackageManagerException e) {
18299                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18300                    }
18301                    // Scan the package
18302                    if (pkg != null) {
18303                        /*
18304                         * TODO why is the lock being held? doPostInstall is
18305                         * called in other places without the lock. This needs
18306                         * to be straightened out.
18307                         */
18308                        // writer
18309                        synchronized (mPackages) {
18310                            retCode = PackageManager.INSTALL_SUCCEEDED;
18311                            pkgList.add(pkg.packageName);
18312                            // Post process args
18313                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18314                                    pkg.applicationInfo.uid);
18315                        }
18316                    } else {
18317                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18318                    }
18319                }
18320
18321            } finally {
18322                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18323                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18324                }
18325            }
18326        }
18327        // writer
18328        synchronized (mPackages) {
18329            // If the platform SDK has changed since the last time we booted,
18330            // we need to re-grant app permission to catch any new ones that
18331            // appear. This is really a hack, and means that apps can in some
18332            // cases get permissions that the user didn't initially explicitly
18333            // allow... it would be nice to have some better way to handle
18334            // this situation.
18335            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18336                    : mSettings.getInternalVersion();
18337            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18338                    : StorageManager.UUID_PRIVATE_INTERNAL;
18339
18340            int updateFlags = UPDATE_PERMISSIONS_ALL;
18341            if (ver.sdkVersion != mSdkVersion) {
18342                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18343                        + mSdkVersion + "; regranting permissions for external");
18344                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18345            }
18346            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18347
18348            // Yay, everything is now upgraded
18349            ver.forceCurrent();
18350
18351            // can downgrade to reader
18352            // Persist settings
18353            mSettings.writeLPr();
18354        }
18355        // Send a broadcast to let everyone know we are done processing
18356        if (pkgList.size() > 0) {
18357            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18358        }
18359    }
18360
18361   /*
18362     * Utility method to unload a list of specified containers
18363     */
18364    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18365        // Just unmount all valid containers.
18366        for (AsecInstallArgs arg : cidArgs) {
18367            synchronized (mInstallLock) {
18368                arg.doPostDeleteLI(false);
18369           }
18370       }
18371   }
18372
18373    /*
18374     * Unload packages mounted on external media. This involves deleting package
18375     * data from internal structures, sending broadcasts about disabled packages,
18376     * gc'ing to free up references, unmounting all secure containers
18377     * corresponding to packages on external media, and posting a
18378     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18379     * that we always have to post this message if status has been requested no
18380     * matter what.
18381     */
18382    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18383            final boolean reportStatus) {
18384        if (DEBUG_SD_INSTALL)
18385            Log.i(TAG, "unloading media packages");
18386        ArrayList<String> pkgList = new ArrayList<String>();
18387        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18388        final Set<AsecInstallArgs> keys = processCids.keySet();
18389        for (AsecInstallArgs args : keys) {
18390            String pkgName = args.getPackageName();
18391            if (DEBUG_SD_INSTALL)
18392                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18393            // Delete package internally
18394            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18395            synchronized (mInstallLock) {
18396                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18397                final boolean res;
18398                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18399                        "unloadMediaPackages")) {
18400                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18401                            null);
18402                }
18403                if (res) {
18404                    pkgList.add(pkgName);
18405                } else {
18406                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18407                    failedList.add(args);
18408                }
18409            }
18410        }
18411
18412        // reader
18413        synchronized (mPackages) {
18414            // We didn't update the settings after removing each package;
18415            // write them now for all packages.
18416            mSettings.writeLPr();
18417        }
18418
18419        // We have to absolutely send UPDATED_MEDIA_STATUS only
18420        // after confirming that all the receivers processed the ordered
18421        // broadcast when packages get disabled, force a gc to clean things up.
18422        // and unload all the containers.
18423        if (pkgList.size() > 0) {
18424            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18425                    new IIntentReceiver.Stub() {
18426                public void performReceive(Intent intent, int resultCode, String data,
18427                        Bundle extras, boolean ordered, boolean sticky,
18428                        int sendingUser) throws RemoteException {
18429                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18430                            reportStatus ? 1 : 0, 1, keys);
18431                    mHandler.sendMessage(msg);
18432                }
18433            });
18434        } else {
18435            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18436                    keys);
18437            mHandler.sendMessage(msg);
18438        }
18439    }
18440
18441    private void loadPrivatePackages(final VolumeInfo vol) {
18442        mHandler.post(new Runnable() {
18443            @Override
18444            public void run() {
18445                loadPrivatePackagesInner(vol);
18446            }
18447        });
18448    }
18449
18450    private void loadPrivatePackagesInner(VolumeInfo vol) {
18451        final String volumeUuid = vol.fsUuid;
18452        if (TextUtils.isEmpty(volumeUuid)) {
18453            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18454            return;
18455        }
18456
18457        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18458        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18459        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18460
18461        final VersionInfo ver;
18462        final List<PackageSetting> packages;
18463        synchronized (mPackages) {
18464            ver = mSettings.findOrCreateVersion(volumeUuid);
18465            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18466        }
18467
18468        for (PackageSetting ps : packages) {
18469            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18470            synchronized (mInstallLock) {
18471                final PackageParser.Package pkg;
18472                try {
18473                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18474                    loaded.add(pkg.applicationInfo);
18475
18476                } catch (PackageManagerException e) {
18477                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18478                }
18479
18480                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18481                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18482                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18483                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18484                }
18485            }
18486        }
18487
18488        // Reconcile app data for all started/unlocked users
18489        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18490        final UserManager um = mContext.getSystemService(UserManager.class);
18491        for (UserInfo user : um.getUsers()) {
18492            final int flags;
18493            if (um.isUserUnlocked(user.id)) {
18494                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18495            } else if (um.isUserRunning(user.id)) {
18496                flags = StorageManager.FLAG_STORAGE_DE;
18497            } else {
18498                continue;
18499            }
18500
18501            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18502            synchronized (mInstallLock) {
18503                reconcileAppsDataLI(volumeUuid, user.id, flags);
18504            }
18505        }
18506
18507        synchronized (mPackages) {
18508            int updateFlags = UPDATE_PERMISSIONS_ALL;
18509            if (ver.sdkVersion != mSdkVersion) {
18510                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18511                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18512                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18513            }
18514            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18515
18516            // Yay, everything is now upgraded
18517            ver.forceCurrent();
18518
18519            mSettings.writeLPr();
18520        }
18521
18522        for (PackageFreezer freezer : freezers) {
18523            freezer.close();
18524        }
18525
18526        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18527        sendResourcesChangedBroadcast(true, false, loaded, null);
18528    }
18529
18530    private void unloadPrivatePackages(final VolumeInfo vol) {
18531        mHandler.post(new Runnable() {
18532            @Override
18533            public void run() {
18534                unloadPrivatePackagesInner(vol);
18535            }
18536        });
18537    }
18538
18539    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18540        final String volumeUuid = vol.fsUuid;
18541        if (TextUtils.isEmpty(volumeUuid)) {
18542            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18543            return;
18544        }
18545
18546        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18547        synchronized (mInstallLock) {
18548        synchronized (mPackages) {
18549            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18550            for (PackageSetting ps : packages) {
18551                if (ps.pkg == null) continue;
18552
18553                final ApplicationInfo info = ps.pkg.applicationInfo;
18554                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18555                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18556
18557                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18558                        "unloadPrivatePackagesInner")) {
18559                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18560                            false, null)) {
18561                        unloaded.add(info);
18562                    } else {
18563                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18564                    }
18565                }
18566            }
18567
18568            mSettings.writeLPr();
18569        }
18570        }
18571
18572        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18573        sendResourcesChangedBroadcast(false, false, unloaded, null);
18574    }
18575
18576    /**
18577     * Examine all users present on given mounted volume, and destroy data
18578     * belonging to users that are no longer valid, or whose user ID has been
18579     * recycled.
18580     */
18581    private void reconcileUsers(String volumeUuid) {
18582        // TODO: also reconcile DE directories
18583        final File[] files = FileUtils
18584                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18585        for (File file : files) {
18586            if (!file.isDirectory()) continue;
18587
18588            final int userId;
18589            final UserInfo info;
18590            try {
18591                userId = Integer.parseInt(file.getName());
18592                info = sUserManager.getUserInfo(userId);
18593            } catch (NumberFormatException e) {
18594                Slog.w(TAG, "Invalid user directory " + file);
18595                continue;
18596            }
18597
18598            boolean destroyUser = false;
18599            if (info == null) {
18600                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18601                        + " because no matching user was found");
18602                destroyUser = true;
18603            } else {
18604                try {
18605                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18606                } catch (IOException e) {
18607                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18608                            + " because we failed to enforce serial number: " + e);
18609                    destroyUser = true;
18610                }
18611            }
18612
18613            if (destroyUser) {
18614                synchronized (mInstallLock) {
18615                    try {
18616                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18617                    } catch (InstallerException e) {
18618                        Slog.w(TAG, "Failed to clean up user dirs", e);
18619                    }
18620                }
18621            }
18622        }
18623    }
18624
18625    private void assertPackageKnown(String volumeUuid, String packageName)
18626            throws PackageManagerException {
18627        synchronized (mPackages) {
18628            final PackageSetting ps = mSettings.mPackages.get(packageName);
18629            if (ps == null) {
18630                throw new PackageManagerException("Package " + packageName + " is unknown");
18631            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18632                throw new PackageManagerException(
18633                        "Package " + packageName + " found on unknown volume " + volumeUuid
18634                                + "; expected volume " + ps.volumeUuid);
18635            }
18636        }
18637    }
18638
18639    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18640            throws PackageManagerException {
18641        synchronized (mPackages) {
18642            final PackageSetting ps = mSettings.mPackages.get(packageName);
18643            if (ps == null) {
18644                throw new PackageManagerException("Package " + packageName + " is unknown");
18645            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18646                throw new PackageManagerException(
18647                        "Package " + packageName + " found on unknown volume " + volumeUuid
18648                                + "; expected volume " + ps.volumeUuid);
18649            } else if (!ps.getInstalled(userId)) {
18650                throw new PackageManagerException(
18651                        "Package " + packageName + " not installed for user " + userId);
18652            }
18653        }
18654    }
18655
18656    /**
18657     * Examine all apps present on given mounted volume, and destroy apps that
18658     * aren't expected, either due to uninstallation or reinstallation on
18659     * another volume.
18660     */
18661    private void reconcileApps(String volumeUuid) {
18662        final File[] files = FileUtils
18663                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18664        for (File file : files) {
18665            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18666                    && !PackageInstallerService.isStageName(file.getName());
18667            if (!isPackage) {
18668                // Ignore entries which are not packages
18669                continue;
18670            }
18671
18672            try {
18673                final PackageLite pkg = PackageParser.parsePackageLite(file,
18674                        PackageParser.PARSE_MUST_BE_APK);
18675                assertPackageKnown(volumeUuid, pkg.packageName);
18676
18677            } catch (PackageParserException | PackageManagerException e) {
18678                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18679                synchronized (mInstallLock) {
18680                    removeCodePathLI(file);
18681                }
18682            }
18683        }
18684    }
18685
18686    /**
18687     * Reconcile all app data for the given user.
18688     * <p>
18689     * Verifies that directories exist and that ownership and labeling is
18690     * correct for all installed apps on all mounted volumes.
18691     */
18692    void reconcileAppsData(int userId, int flags) {
18693        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18694        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18695            final String volumeUuid = vol.getFsUuid();
18696            synchronized (mInstallLock) {
18697                reconcileAppsDataLI(volumeUuid, userId, flags);
18698            }
18699        }
18700    }
18701
18702    /**
18703     * Reconcile all app data on given mounted volume.
18704     * <p>
18705     * Destroys app data that isn't expected, either due to uninstallation or
18706     * reinstallation on another volume.
18707     * <p>
18708     * Verifies that directories exist and that ownership and labeling is
18709     * correct for all installed apps.
18710     */
18711    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
18712        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18713                + Integer.toHexString(flags));
18714
18715        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18716        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18717
18718        boolean restoreconNeeded = false;
18719
18720        // First look for stale data that doesn't belong, and check if things
18721        // have changed since we did our last restorecon
18722        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18723            if (!isUserKeyUnlocked(userId)) {
18724                throw new RuntimeException(
18725                        "Yikes, someone asked us to reconcile CE storage while " + userId
18726                                + " was still locked; this would have caused massive data loss!");
18727            }
18728
18729            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18730
18731            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18732            for (File file : files) {
18733                final String packageName = file.getName();
18734                try {
18735                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18736                } catch (PackageManagerException e) {
18737                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18738                    try {
18739                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18740                                StorageManager.FLAG_STORAGE_CE, 0);
18741                    } catch (InstallerException e2) {
18742                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18743                    }
18744                }
18745            }
18746        }
18747        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18748            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18749
18750            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18751            for (File file : files) {
18752                final String packageName = file.getName();
18753                try {
18754                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18755                } catch (PackageManagerException e) {
18756                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18757                    try {
18758                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18759                                StorageManager.FLAG_STORAGE_DE, 0);
18760                    } catch (InstallerException e2) {
18761                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18762                    }
18763                }
18764            }
18765        }
18766
18767        // Ensure that data directories are ready to roll for all packages
18768        // installed for this volume and user
18769        final List<PackageSetting> packages;
18770        synchronized (mPackages) {
18771            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18772        }
18773        int preparedCount = 0;
18774        for (PackageSetting ps : packages) {
18775            final String packageName = ps.name;
18776            if (ps.pkg == null) {
18777                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18778                // TODO: might be due to legacy ASEC apps; we should circle back
18779                // and reconcile again once they're scanned
18780                continue;
18781            }
18782
18783            if (ps.getInstalled(userId)) {
18784                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
18785
18786                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
18787                    // We may have just shuffled around app data directories, so
18788                    // prepare them one more time
18789                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
18790                }
18791
18792                preparedCount++;
18793            }
18794        }
18795
18796        if (restoreconNeeded) {
18797            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18798                SELinuxMMAC.setRestoreconDone(ceDir);
18799            }
18800            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18801                SELinuxMMAC.setRestoreconDone(deDir);
18802            }
18803        }
18804
18805        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18806                + " packages; restoreconNeeded was " + restoreconNeeded);
18807    }
18808
18809    /**
18810     * Prepare app data for the given app just after it was installed or
18811     * upgraded. This method carefully only touches users that it's installed
18812     * for, and it forces a restorecon to handle any seinfo changes.
18813     * <p>
18814     * Verifies that directories exist and that ownership and labeling is
18815     * correct for all installed apps. If there is an ownership mismatch, it
18816     * will try recovering system apps by wiping data; third-party app data is
18817     * left intact.
18818     * <p>
18819     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18820     */
18821    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
18822        final PackageSetting ps;
18823        synchronized (mPackages) {
18824            ps = mSettings.mPackages.get(pkg.packageName);
18825            mSettings.writeKernelMappingLPr(ps);
18826        }
18827
18828        final UserManager um = mContext.getSystemService(UserManager.class);
18829        for (UserInfo user : um.getUsers()) {
18830            final int flags;
18831            if (um.isUserUnlocked(user.id)) {
18832                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18833            } else if (um.isUserRunning(user.id)) {
18834                flags = StorageManager.FLAG_STORAGE_DE;
18835            } else {
18836                continue;
18837            }
18838
18839            if (ps.getInstalled(user.id)) {
18840                // Whenever an app changes, force a restorecon of its data
18841                // TODO: when user data is locked, mark that we're still dirty
18842                prepareAppDataLIF(pkg, user.id, flags, true);
18843            }
18844        }
18845    }
18846
18847    /**
18848     * Prepare app data for the given app.
18849     * <p>
18850     * Verifies that directories exist and that ownership and labeling is
18851     * correct for all installed apps. If there is an ownership mismatch, this
18852     * will try recovering system apps by wiping data; third-party app data is
18853     * left intact.
18854     */
18855    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
18856            boolean restoreconNeeded) {
18857        if (pkg == null) {
18858            Slog.wtf(TAG, "Package was null!", new Throwable());
18859            return;
18860        }
18861        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
18862        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18863        for (int i = 0; i < childCount; i++) {
18864            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
18865        }
18866    }
18867
18868    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
18869            boolean restoreconNeeded) {
18870        if (DEBUG_APP_DATA) {
18871            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18872                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18873        }
18874
18875        final String volumeUuid = pkg.volumeUuid;
18876        final String packageName = pkg.packageName;
18877        final ApplicationInfo app = pkg.applicationInfo;
18878        final int appId = UserHandle.getAppId(app.uid);
18879
18880        Preconditions.checkNotNull(app.seinfo);
18881
18882        try {
18883            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18884                    appId, app.seinfo, app.targetSdkVersion);
18885        } catch (InstallerException e) {
18886            if (app.isSystemApp()) {
18887                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18888                        + ", but trying to recover: " + e);
18889                destroyAppDataLeafLIF(pkg, userId, flags);
18890                try {
18891                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18892                            appId, app.seinfo, app.targetSdkVersion);
18893                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18894                } catch (InstallerException e2) {
18895                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
18896                }
18897            } else {
18898                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18899            }
18900        }
18901
18902        if (restoreconNeeded) {
18903            try {
18904                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
18905                        app.seinfo);
18906            } catch (InstallerException e) {
18907                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
18908            }
18909        }
18910
18911        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18912            try {
18913                // CE storage is unlocked right now, so read out the inode and
18914                // remember for use later when it's locked
18915                // TODO: mark this structure as dirty so we persist it!
18916                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
18917                        StorageManager.FLAG_STORAGE_CE);
18918                synchronized (mPackages) {
18919                    final PackageSetting ps = mSettings.mPackages.get(packageName);
18920                    if (ps != null) {
18921                        ps.setCeDataInode(ceDataInode, userId);
18922                    }
18923                }
18924            } catch (InstallerException e) {
18925                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
18926            }
18927        }
18928
18929        prepareAppDataContentsLeafLIF(pkg, userId, flags);
18930    }
18931
18932    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
18933        if (pkg == null) {
18934            Slog.wtf(TAG, "Package was null!", new Throwable());
18935            return;
18936        }
18937        prepareAppDataContentsLeafLIF(pkg, userId, flags);
18938        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18939        for (int i = 0; i < childCount; i++) {
18940            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
18941        }
18942    }
18943
18944    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
18945        final String volumeUuid = pkg.volumeUuid;
18946        final String packageName = pkg.packageName;
18947        final ApplicationInfo app = pkg.applicationInfo;
18948
18949        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18950            // Create a native library symlink only if we have native libraries
18951            // and if the native libraries are 32 bit libraries. We do not provide
18952            // this symlink for 64 bit libraries.
18953            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18954                final String nativeLibPath = app.nativeLibraryDir;
18955                try {
18956                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18957                            nativeLibPath, userId);
18958                } catch (InstallerException e) {
18959                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18960                }
18961            }
18962        }
18963    }
18964
18965    /**
18966     * For system apps on non-FBE devices, this method migrates any existing
18967     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18968     * requested by the app.
18969     */
18970    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
18971        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18972                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18973            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18974                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18975            try {
18976                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
18977                        storageTarget);
18978            } catch (InstallerException e) {
18979                logCriticalInfo(Log.WARN,
18980                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18981            }
18982            return true;
18983        } else {
18984            return false;
18985        }
18986    }
18987
18988    public PackageFreezer freezePackage(String packageName, String killReason) {
18989        return new PackageFreezer(packageName, killReason);
18990    }
18991
18992    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
18993            String killReason) {
18994        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18995            return new PackageFreezer();
18996        } else {
18997            return freezePackage(packageName, killReason);
18998        }
18999    }
19000
19001    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19002            String killReason) {
19003        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19004            return new PackageFreezer();
19005        } else {
19006            return freezePackage(packageName, killReason);
19007        }
19008    }
19009
19010    /**
19011     * Class that freezes and kills the given package upon creation, and
19012     * unfreezes it upon closing. This is typically used when doing surgery on
19013     * app code/data to prevent the app from running while you're working.
19014     */
19015    private class PackageFreezer implements AutoCloseable {
19016        private final String mPackageName;
19017        private final PackageFreezer[] mChildren;
19018
19019        private final boolean mWeFroze;
19020
19021        private final AtomicBoolean mClosed = new AtomicBoolean();
19022        private final CloseGuard mCloseGuard = CloseGuard.get();
19023
19024        /**
19025         * Create and return a stub freezer that doesn't actually do anything,
19026         * typically used when someone requested
19027         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19028         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19029         */
19030        public PackageFreezer() {
19031            mPackageName = null;
19032            mChildren = null;
19033            mWeFroze = false;
19034            mCloseGuard.open("close");
19035        }
19036
19037        public PackageFreezer(String packageName, String killReason) {
19038            synchronized (mPackages) {
19039                mPackageName = packageName;
19040                mWeFroze = mFrozenPackages.add(mPackageName);
19041
19042                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19043                if (ps != null) {
19044                    killApplication(ps.name, ps.appId, killReason);
19045                }
19046
19047                final PackageParser.Package p = mPackages.get(packageName);
19048                if (p != null && p.childPackages != null) {
19049                    final int N = p.childPackages.size();
19050                    mChildren = new PackageFreezer[N];
19051                    for (int i = 0; i < N; i++) {
19052                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19053                                killReason);
19054                    }
19055                } else {
19056                    mChildren = null;
19057                }
19058            }
19059            mCloseGuard.open("close");
19060        }
19061
19062        @Override
19063        protected void finalize() throws Throwable {
19064            try {
19065                mCloseGuard.warnIfOpen();
19066                close();
19067            } finally {
19068                super.finalize();
19069            }
19070        }
19071
19072        @Override
19073        public void close() {
19074            mCloseGuard.close();
19075            if (mClosed.compareAndSet(false, true)) {
19076                synchronized (mPackages) {
19077                    if (mWeFroze) {
19078                        mFrozenPackages.remove(mPackageName);
19079                    }
19080
19081                    if (mChildren != null) {
19082                        for (PackageFreezer freezer : mChildren) {
19083                            freezer.close();
19084                        }
19085                    }
19086                }
19087            }
19088        }
19089    }
19090
19091    /**
19092     * Verify that given package is currently frozen.
19093     */
19094    private void checkPackageFrozen(String packageName) {
19095        synchronized (mPackages) {
19096            if (!mFrozenPackages.contains(packageName)) {
19097                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19098            }
19099        }
19100    }
19101
19102    @Override
19103    public int movePackage(final String packageName, final String volumeUuid) {
19104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19105
19106        final int moveId = mNextMoveId.getAndIncrement();
19107        mHandler.post(new Runnable() {
19108            @Override
19109            public void run() {
19110                try {
19111                    movePackageInternal(packageName, volumeUuid, moveId);
19112                } catch (PackageManagerException e) {
19113                    Slog.w(TAG, "Failed to move " + packageName, e);
19114                    mMoveCallbacks.notifyStatusChanged(moveId,
19115                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19116                }
19117            }
19118        });
19119        return moveId;
19120    }
19121
19122    private void movePackageInternal(final String packageName, final String volumeUuid,
19123            final int moveId) throws PackageManagerException {
19124        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19125        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19126        final PackageManager pm = mContext.getPackageManager();
19127
19128        final boolean currentAsec;
19129        final String currentVolumeUuid;
19130        final File codeFile;
19131        final String installerPackageName;
19132        final String packageAbiOverride;
19133        final int appId;
19134        final String seinfo;
19135        final String label;
19136        final int targetSdkVersion;
19137        final PackageFreezer freezer;
19138
19139        // reader
19140        synchronized (mPackages) {
19141            final PackageParser.Package pkg = mPackages.get(packageName);
19142            final PackageSetting ps = mSettings.mPackages.get(packageName);
19143            if (pkg == null || ps == null) {
19144                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19145            }
19146
19147            if (pkg.applicationInfo.isSystemApp()) {
19148                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19149                        "Cannot move system application");
19150            }
19151
19152            if (pkg.applicationInfo.isExternalAsec()) {
19153                currentAsec = true;
19154                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19155            } else if (pkg.applicationInfo.isForwardLocked()) {
19156                currentAsec = true;
19157                currentVolumeUuid = "forward_locked";
19158            } else {
19159                currentAsec = false;
19160                currentVolumeUuid = ps.volumeUuid;
19161
19162                final File probe = new File(pkg.codePath);
19163                final File probeOat = new File(probe, "oat");
19164                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19165                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19166                            "Move only supported for modern cluster style installs");
19167                }
19168            }
19169
19170            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19171                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19172                        "Package already moved to " + volumeUuid);
19173            }
19174            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19175                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19176                        "Device admin cannot be moved");
19177            }
19178
19179            if (mFrozenPackages.contains(packageName)) {
19180                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19181                        "Failed to move already frozen package");
19182            }
19183
19184            codeFile = new File(pkg.codePath);
19185            installerPackageName = ps.installerPackageName;
19186            packageAbiOverride = ps.cpuAbiOverrideString;
19187            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19188            seinfo = pkg.applicationInfo.seinfo;
19189            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19190            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19191            freezer = new PackageFreezer(packageName, "movePackageInternal");
19192        }
19193
19194        final Bundle extras = new Bundle();
19195        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19196        extras.putString(Intent.EXTRA_TITLE, label);
19197        mMoveCallbacks.notifyCreated(moveId, extras);
19198
19199        int installFlags;
19200        final boolean moveCompleteApp;
19201        final File measurePath;
19202
19203        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19204            installFlags = INSTALL_INTERNAL;
19205            moveCompleteApp = !currentAsec;
19206            measurePath = Environment.getDataAppDirectory(volumeUuid);
19207        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19208            installFlags = INSTALL_EXTERNAL;
19209            moveCompleteApp = false;
19210            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19211        } else {
19212            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19213            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19214                    || !volume.isMountedWritable()) {
19215                freezer.close();
19216                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19217                        "Move location not mounted private volume");
19218            }
19219
19220            Preconditions.checkState(!currentAsec);
19221
19222            installFlags = INSTALL_INTERNAL;
19223            moveCompleteApp = true;
19224            measurePath = Environment.getDataAppDirectory(volumeUuid);
19225        }
19226
19227        final PackageStats stats = new PackageStats(null, -1);
19228        synchronized (mInstaller) {
19229            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19230                freezer.close();
19231                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19232                        "Failed to measure package size");
19233            }
19234        }
19235
19236        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19237                + stats.dataSize);
19238
19239        final long startFreeBytes = measurePath.getFreeSpace();
19240        final long sizeBytes;
19241        if (moveCompleteApp) {
19242            sizeBytes = stats.codeSize + stats.dataSize;
19243        } else {
19244            sizeBytes = stats.codeSize;
19245        }
19246
19247        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19248            freezer.close();
19249            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19250                    "Not enough free space to move");
19251        }
19252
19253        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19254
19255        final CountDownLatch installedLatch = new CountDownLatch(1);
19256        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19257            @Override
19258            public void onUserActionRequired(Intent intent) throws RemoteException {
19259                throw new IllegalStateException();
19260            }
19261
19262            @Override
19263            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19264                    Bundle extras) throws RemoteException {
19265                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19266                        + PackageManager.installStatusToString(returnCode, msg));
19267
19268                installedLatch.countDown();
19269                freezer.close();
19270
19271                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19272                switch (status) {
19273                    case PackageInstaller.STATUS_SUCCESS:
19274                        mMoveCallbacks.notifyStatusChanged(moveId,
19275                                PackageManager.MOVE_SUCCEEDED);
19276                        break;
19277                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19278                        mMoveCallbacks.notifyStatusChanged(moveId,
19279                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19280                        break;
19281                    default:
19282                        mMoveCallbacks.notifyStatusChanged(moveId,
19283                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19284                        break;
19285                }
19286            }
19287        };
19288
19289        final MoveInfo move;
19290        if (moveCompleteApp) {
19291            // Kick off a thread to report progress estimates
19292            new Thread() {
19293                @Override
19294                public void run() {
19295                    while (true) {
19296                        try {
19297                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19298                                break;
19299                            }
19300                        } catch (InterruptedException ignored) {
19301                        }
19302
19303                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19304                        final int progress = 10 + (int) MathUtils.constrain(
19305                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19306                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19307                    }
19308                }
19309            }.start();
19310
19311            final String dataAppName = codeFile.getName();
19312            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19313                    dataAppName, appId, seinfo, targetSdkVersion);
19314        } else {
19315            move = null;
19316        }
19317
19318        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19319
19320        final Message msg = mHandler.obtainMessage(INIT_COPY);
19321        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19322        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19323                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19324                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19325        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19326        msg.obj = params;
19327
19328        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19329                System.identityHashCode(msg.obj));
19330        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19331                System.identityHashCode(msg.obj));
19332
19333        mHandler.sendMessage(msg);
19334    }
19335
19336    @Override
19337    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19338        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19339
19340        final int realMoveId = mNextMoveId.getAndIncrement();
19341        final Bundle extras = new Bundle();
19342        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19343        mMoveCallbacks.notifyCreated(realMoveId, extras);
19344
19345        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19346            @Override
19347            public void onCreated(int moveId, Bundle extras) {
19348                // Ignored
19349            }
19350
19351            @Override
19352            public void onStatusChanged(int moveId, int status, long estMillis) {
19353                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19354            }
19355        };
19356
19357        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19358        storage.setPrimaryStorageUuid(volumeUuid, callback);
19359        return realMoveId;
19360    }
19361
19362    @Override
19363    public int getMoveStatus(int moveId) {
19364        mContext.enforceCallingOrSelfPermission(
19365                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19366        return mMoveCallbacks.mLastStatus.get(moveId);
19367    }
19368
19369    @Override
19370    public void registerMoveCallback(IPackageMoveObserver callback) {
19371        mContext.enforceCallingOrSelfPermission(
19372                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19373        mMoveCallbacks.register(callback);
19374    }
19375
19376    @Override
19377    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19378        mContext.enforceCallingOrSelfPermission(
19379                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19380        mMoveCallbacks.unregister(callback);
19381    }
19382
19383    @Override
19384    public boolean setInstallLocation(int loc) {
19385        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19386                null);
19387        if (getInstallLocation() == loc) {
19388            return true;
19389        }
19390        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19391                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19392            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19393                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19394            return true;
19395        }
19396        return false;
19397   }
19398
19399    @Override
19400    public int getInstallLocation() {
19401        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19402                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19403                PackageHelper.APP_INSTALL_AUTO);
19404    }
19405
19406    /** Called by UserManagerService */
19407    void cleanUpUser(UserManagerService userManager, int userHandle) {
19408        synchronized (mPackages) {
19409            mDirtyUsers.remove(userHandle);
19410            mUserNeedsBadging.delete(userHandle);
19411            mSettings.removeUserLPw(userHandle);
19412            mPendingBroadcasts.remove(userHandle);
19413            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19414        }
19415        synchronized (mInstallLock) {
19416            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19417            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19418                final String volumeUuid = vol.getFsUuid();
19419                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
19420                try {
19421                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
19422                } catch (InstallerException e) {
19423                    Slog.w(TAG, "Failed to remove user data", e);
19424                }
19425            }
19426            synchronized (mPackages) {
19427                removeUnusedPackagesLILPw(userManager, userHandle);
19428            }
19429        }
19430    }
19431
19432    /**
19433     * We're removing userHandle and would like to remove any downloaded packages
19434     * that are no longer in use by any other user.
19435     * @param userHandle the user being removed
19436     */
19437    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
19438        final boolean DEBUG_CLEAN_APKS = false;
19439        int [] users = userManager.getUserIds();
19440        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19441        while (psit.hasNext()) {
19442            PackageSetting ps = psit.next();
19443            if (ps.pkg == null) {
19444                continue;
19445            }
19446            final String packageName = ps.pkg.packageName;
19447            // Skip over if system app
19448            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19449                continue;
19450            }
19451            if (DEBUG_CLEAN_APKS) {
19452                Slog.i(TAG, "Checking package " + packageName);
19453            }
19454            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19455            if (keep) {
19456                if (DEBUG_CLEAN_APKS) {
19457                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19458                }
19459            } else {
19460                for (int i = 0; i < users.length; i++) {
19461                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19462                        keep = true;
19463                        if (DEBUG_CLEAN_APKS) {
19464                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19465                                    + users[i]);
19466                        }
19467                        break;
19468                    }
19469                }
19470            }
19471            if (!keep) {
19472                if (DEBUG_CLEAN_APKS) {
19473                    Slog.i(TAG, "  Removing package " + packageName);
19474                }
19475                mHandler.post(new Runnable() {
19476                    public void run() {
19477                        deletePackageX(packageName, userHandle, 0);
19478                    } //end run
19479                });
19480            }
19481        }
19482    }
19483
19484    /** Called by UserManagerService */
19485    void createNewUser(int userHandle) {
19486        synchronized (mInstallLock) {
19487            try {
19488                mInstaller.createUserConfig(userHandle);
19489            } catch (InstallerException e) {
19490                Slog.w(TAG, "Failed to create user config", e);
19491            }
19492            mSettings.createNewUserLI(this, mInstaller, userHandle);
19493        }
19494        synchronized (mPackages) {
19495            applyFactoryDefaultBrowserLPw(userHandle);
19496            primeDomainVerificationsLPw(userHandle);
19497        }
19498    }
19499
19500    void newUserCreated(final int userHandle) {
19501        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19502        // If permission review for legacy apps is required, we represent
19503        // dagerous permissions for such apps as always granted runtime
19504        // permissions to keep per user flag state whether review is needed.
19505        // Hence, if a new user is added we have to propagate dangerous
19506        // permission grants for these legacy apps.
19507        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19508            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19509                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19510        }
19511    }
19512
19513    @Override
19514    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19515        mContext.enforceCallingOrSelfPermission(
19516                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19517                "Only package verification agents can read the verifier device identity");
19518
19519        synchronized (mPackages) {
19520            return mSettings.getVerifierDeviceIdentityLPw();
19521        }
19522    }
19523
19524    @Override
19525    public void setPermissionEnforced(String permission, boolean enforced) {
19526        // TODO: Now that we no longer change GID for storage, this should to away.
19527        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19528                "setPermissionEnforced");
19529        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19530            synchronized (mPackages) {
19531                if (mSettings.mReadExternalStorageEnforced == null
19532                        || mSettings.mReadExternalStorageEnforced != enforced) {
19533                    mSettings.mReadExternalStorageEnforced = enforced;
19534                    mSettings.writeLPr();
19535                }
19536            }
19537            // kill any non-foreground processes so we restart them and
19538            // grant/revoke the GID.
19539            final IActivityManager am = ActivityManagerNative.getDefault();
19540            if (am != null) {
19541                final long token = Binder.clearCallingIdentity();
19542                try {
19543                    am.killProcessesBelowForeground("setPermissionEnforcement");
19544                } catch (RemoteException e) {
19545                } finally {
19546                    Binder.restoreCallingIdentity(token);
19547                }
19548            }
19549        } else {
19550            throw new IllegalArgumentException("No selective enforcement for " + permission);
19551        }
19552    }
19553
19554    @Override
19555    @Deprecated
19556    public boolean isPermissionEnforced(String permission) {
19557        return true;
19558    }
19559
19560    @Override
19561    public boolean isStorageLow() {
19562        final long token = Binder.clearCallingIdentity();
19563        try {
19564            final DeviceStorageMonitorInternal
19565                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19566            if (dsm != null) {
19567                return dsm.isMemoryLow();
19568            } else {
19569                return false;
19570            }
19571        } finally {
19572            Binder.restoreCallingIdentity(token);
19573        }
19574    }
19575
19576    @Override
19577    public IPackageInstaller getPackageInstaller() {
19578        return mInstallerService;
19579    }
19580
19581    private boolean userNeedsBadging(int userId) {
19582        int index = mUserNeedsBadging.indexOfKey(userId);
19583        if (index < 0) {
19584            final UserInfo userInfo;
19585            final long token = Binder.clearCallingIdentity();
19586            try {
19587                userInfo = sUserManager.getUserInfo(userId);
19588            } finally {
19589                Binder.restoreCallingIdentity(token);
19590            }
19591            final boolean b;
19592            if (userInfo != null && userInfo.isManagedProfile()) {
19593                b = true;
19594            } else {
19595                b = false;
19596            }
19597            mUserNeedsBadging.put(userId, b);
19598            return b;
19599        }
19600        return mUserNeedsBadging.valueAt(index);
19601    }
19602
19603    @Override
19604    public KeySet getKeySetByAlias(String packageName, String alias) {
19605        if (packageName == null || alias == null) {
19606            return null;
19607        }
19608        synchronized(mPackages) {
19609            final PackageParser.Package pkg = mPackages.get(packageName);
19610            if (pkg == null) {
19611                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19612                throw new IllegalArgumentException("Unknown package: " + packageName);
19613            }
19614            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19615            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19616        }
19617    }
19618
19619    @Override
19620    public KeySet getSigningKeySet(String packageName) {
19621        if (packageName == null) {
19622            return null;
19623        }
19624        synchronized(mPackages) {
19625            final PackageParser.Package pkg = mPackages.get(packageName);
19626            if (pkg == null) {
19627                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19628                throw new IllegalArgumentException("Unknown package: " + packageName);
19629            }
19630            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19631                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19632                throw new SecurityException("May not access signing KeySet of other apps.");
19633            }
19634            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19635            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19636        }
19637    }
19638
19639    @Override
19640    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19641        if (packageName == null || ks == null) {
19642            return false;
19643        }
19644        synchronized(mPackages) {
19645            final PackageParser.Package pkg = mPackages.get(packageName);
19646            if (pkg == null) {
19647                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19648                throw new IllegalArgumentException("Unknown package: " + packageName);
19649            }
19650            IBinder ksh = ks.getToken();
19651            if (ksh instanceof KeySetHandle) {
19652                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19653                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19654            }
19655            return false;
19656        }
19657    }
19658
19659    @Override
19660    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19661        if (packageName == null || ks == null) {
19662            return false;
19663        }
19664        synchronized(mPackages) {
19665            final PackageParser.Package pkg = mPackages.get(packageName);
19666            if (pkg == null) {
19667                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19668                throw new IllegalArgumentException("Unknown package: " + packageName);
19669            }
19670            IBinder ksh = ks.getToken();
19671            if (ksh instanceof KeySetHandle) {
19672                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19673                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19674            }
19675            return false;
19676        }
19677    }
19678
19679    private void deletePackageIfUnusedLPr(final String packageName) {
19680        PackageSetting ps = mSettings.mPackages.get(packageName);
19681        if (ps == null) {
19682            return;
19683        }
19684        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19685            // TODO Implement atomic delete if package is unused
19686            // It is currently possible that the package will be deleted even if it is installed
19687            // after this method returns.
19688            mHandler.post(new Runnable() {
19689                public void run() {
19690                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19691                }
19692            });
19693        }
19694    }
19695
19696    /**
19697     * Check and throw if the given before/after packages would be considered a
19698     * downgrade.
19699     */
19700    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19701            throws PackageManagerException {
19702        if (after.versionCode < before.mVersionCode) {
19703            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19704                    "Update version code " + after.versionCode + " is older than current "
19705                    + before.mVersionCode);
19706        } else if (after.versionCode == before.mVersionCode) {
19707            if (after.baseRevisionCode < before.baseRevisionCode) {
19708                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19709                        "Update base revision code " + after.baseRevisionCode
19710                        + " is older than current " + before.baseRevisionCode);
19711            }
19712
19713            if (!ArrayUtils.isEmpty(after.splitNames)) {
19714                for (int i = 0; i < after.splitNames.length; i++) {
19715                    final String splitName = after.splitNames[i];
19716                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19717                    if (j != -1) {
19718                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19719                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19720                                    "Update split " + splitName + " revision code "
19721                                    + after.splitRevisionCodes[i] + " is older than current "
19722                                    + before.splitRevisionCodes[j]);
19723                        }
19724                    }
19725                }
19726            }
19727        }
19728    }
19729
19730    private static class MoveCallbacks extends Handler {
19731        private static final int MSG_CREATED = 1;
19732        private static final int MSG_STATUS_CHANGED = 2;
19733
19734        private final RemoteCallbackList<IPackageMoveObserver>
19735                mCallbacks = new RemoteCallbackList<>();
19736
19737        private final SparseIntArray mLastStatus = new SparseIntArray();
19738
19739        public MoveCallbacks(Looper looper) {
19740            super(looper);
19741        }
19742
19743        public void register(IPackageMoveObserver callback) {
19744            mCallbacks.register(callback);
19745        }
19746
19747        public void unregister(IPackageMoveObserver callback) {
19748            mCallbacks.unregister(callback);
19749        }
19750
19751        @Override
19752        public void handleMessage(Message msg) {
19753            final SomeArgs args = (SomeArgs) msg.obj;
19754            final int n = mCallbacks.beginBroadcast();
19755            for (int i = 0; i < n; i++) {
19756                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19757                try {
19758                    invokeCallback(callback, msg.what, args);
19759                } catch (RemoteException ignored) {
19760                }
19761            }
19762            mCallbacks.finishBroadcast();
19763            args.recycle();
19764        }
19765
19766        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19767                throws RemoteException {
19768            switch (what) {
19769                case MSG_CREATED: {
19770                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19771                    break;
19772                }
19773                case MSG_STATUS_CHANGED: {
19774                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19775                    break;
19776                }
19777            }
19778        }
19779
19780        private void notifyCreated(int moveId, Bundle extras) {
19781            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19782
19783            final SomeArgs args = SomeArgs.obtain();
19784            args.argi1 = moveId;
19785            args.arg2 = extras;
19786            obtainMessage(MSG_CREATED, args).sendToTarget();
19787        }
19788
19789        private void notifyStatusChanged(int moveId, int status) {
19790            notifyStatusChanged(moveId, status, -1);
19791        }
19792
19793        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19794            Slog.v(TAG, "Move " + moveId + " status " + status);
19795
19796            final SomeArgs args = SomeArgs.obtain();
19797            args.argi1 = moveId;
19798            args.argi2 = status;
19799            args.arg3 = estMillis;
19800            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19801
19802            synchronized (mLastStatus) {
19803                mLastStatus.put(moveId, status);
19804            }
19805        }
19806    }
19807
19808    private final static class OnPermissionChangeListeners extends Handler {
19809        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19810
19811        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19812                new RemoteCallbackList<>();
19813
19814        public OnPermissionChangeListeners(Looper looper) {
19815            super(looper);
19816        }
19817
19818        @Override
19819        public void handleMessage(Message msg) {
19820            switch (msg.what) {
19821                case MSG_ON_PERMISSIONS_CHANGED: {
19822                    final int uid = msg.arg1;
19823                    handleOnPermissionsChanged(uid);
19824                } break;
19825            }
19826        }
19827
19828        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19829            mPermissionListeners.register(listener);
19830
19831        }
19832
19833        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19834            mPermissionListeners.unregister(listener);
19835        }
19836
19837        public void onPermissionsChanged(int uid) {
19838            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19839                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19840            }
19841        }
19842
19843        private void handleOnPermissionsChanged(int uid) {
19844            final int count = mPermissionListeners.beginBroadcast();
19845            try {
19846                for (int i = 0; i < count; i++) {
19847                    IOnPermissionsChangeListener callback = mPermissionListeners
19848                            .getBroadcastItem(i);
19849                    try {
19850                        callback.onPermissionsChanged(uid);
19851                    } catch (RemoteException e) {
19852                        Log.e(TAG, "Permission listener is dead", e);
19853                    }
19854                }
19855            } finally {
19856                mPermissionListeners.finishBroadcast();
19857            }
19858        }
19859    }
19860
19861    private class PackageManagerInternalImpl extends PackageManagerInternal {
19862        @Override
19863        public void setLocationPackagesProvider(PackagesProvider provider) {
19864            synchronized (mPackages) {
19865                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19866            }
19867        }
19868
19869        @Override
19870        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19871            synchronized (mPackages) {
19872                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19873            }
19874        }
19875
19876        @Override
19877        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19878            synchronized (mPackages) {
19879                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19880            }
19881        }
19882
19883        @Override
19884        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19885            synchronized (mPackages) {
19886                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19887            }
19888        }
19889
19890        @Override
19891        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19892            synchronized (mPackages) {
19893                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19894            }
19895        }
19896
19897        @Override
19898        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19899            synchronized (mPackages) {
19900                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19901            }
19902        }
19903
19904        @Override
19905        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19906            synchronized (mPackages) {
19907                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19908                        packageName, userId);
19909            }
19910        }
19911
19912        @Override
19913        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19914            synchronized (mPackages) {
19915                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19916                        packageName, userId);
19917            }
19918        }
19919
19920        @Override
19921        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19922            synchronized (mPackages) {
19923                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19924                        packageName, userId);
19925            }
19926        }
19927
19928        @Override
19929        public void setKeepUninstalledPackages(final List<String> packageList) {
19930            Preconditions.checkNotNull(packageList);
19931            List<String> removedFromList = null;
19932            synchronized (mPackages) {
19933                if (mKeepUninstalledPackages != null) {
19934                    final int packagesCount = mKeepUninstalledPackages.size();
19935                    for (int i = 0; i < packagesCount; i++) {
19936                        String oldPackage = mKeepUninstalledPackages.get(i);
19937                        if (packageList != null && packageList.contains(oldPackage)) {
19938                            continue;
19939                        }
19940                        if (removedFromList == null) {
19941                            removedFromList = new ArrayList<>();
19942                        }
19943                        removedFromList.add(oldPackage);
19944                    }
19945                }
19946                mKeepUninstalledPackages = new ArrayList<>(packageList);
19947                if (removedFromList != null) {
19948                    final int removedCount = removedFromList.size();
19949                    for (int i = 0; i < removedCount; i++) {
19950                        deletePackageIfUnusedLPr(removedFromList.get(i));
19951                    }
19952                }
19953            }
19954        }
19955
19956        @Override
19957        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19958            synchronized (mPackages) {
19959                // If we do not support permission review, done.
19960                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19961                    return false;
19962                }
19963
19964                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19965                if (packageSetting == null) {
19966                    return false;
19967                }
19968
19969                // Permission review applies only to apps not supporting the new permission model.
19970                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19971                    return false;
19972                }
19973
19974                // Legacy apps have the permission and get user consent on launch.
19975                PermissionsState permissionsState = packageSetting.getPermissionsState();
19976                return permissionsState.isPermissionReviewRequired(userId);
19977            }
19978        }
19979
19980        @Override
19981        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19982            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19983        }
19984
19985        @Override
19986        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19987                int userId) {
19988            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19989        }
19990    }
19991
19992    @Override
19993    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19994        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19995        synchronized (mPackages) {
19996            final long identity = Binder.clearCallingIdentity();
19997            try {
19998                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19999                        packageNames, userId);
20000            } finally {
20001                Binder.restoreCallingIdentity(identity);
20002            }
20003        }
20004    }
20005
20006    private static void enforceSystemOrPhoneCaller(String tag) {
20007        int callingUid = Binder.getCallingUid();
20008        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20009            throw new SecurityException(
20010                    "Cannot call " + tag + " from UID " + callingUid);
20011        }
20012    }
20013
20014    boolean isHistoricalPackageUsageAvailable() {
20015        return mPackageUsage.isHistoricalPackageUsageAvailable();
20016    }
20017
20018    /**
20019     * Return a <b>copy</b> of the collection of packages known to the package manager.
20020     * @return A copy of the values of mPackages.
20021     */
20022    Collection<PackageParser.Package> getPackages() {
20023        synchronized (mPackages) {
20024            return new ArrayList<>(mPackages.values());
20025        }
20026    }
20027
20028    /**
20029     * Logs process start information (including base APK hash) to the security log.
20030     * @hide
20031     */
20032    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20033            String apkFile, int pid) {
20034        if (!SecurityLog.isLoggingEnabled()) {
20035            return;
20036        }
20037        Bundle data = new Bundle();
20038        data.putLong("startTimestamp", System.currentTimeMillis());
20039        data.putString("processName", processName);
20040        data.putInt("uid", uid);
20041        data.putString("seinfo", seinfo);
20042        data.putString("apkFile", apkFile);
20043        data.putInt("pid", pid);
20044        Message msg = mProcessLoggingHandler.obtainMessage(
20045                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20046        msg.setData(data);
20047        mProcessLoggingHandler.sendMessage(msg);
20048    }
20049}
20050