PackageManagerService.java revision 0e9e5ea58600a7b6aed1b307affdc400bfa9b33b
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.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.security.KeyStore;
199import android.security.SystemKeyStore;
200import android.system.ErrnoException;
201import android.system.Os;
202import android.text.TextUtils;
203import android.text.format.DateUtils;
204import android.util.ArrayMap;
205import android.util.ArraySet;
206import android.util.AtomicFile;
207import android.util.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.util.jar.StrictJarFile;
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.telephony.CarrierAppUtils;
233import com.android.internal.util.ArrayUtils;
234import com.android.internal.util.FastPrintWriter;
235import com.android.internal.util.FastXmlSerializer;
236import com.android.internal.util.IndentingPrintWriter;
237import com.android.internal.util.Preconditions;
238import com.android.internal.util.XmlUtils;
239import com.android.server.EventLogTags;
240import com.android.server.FgThread;
241import com.android.server.IntentResolver;
242import com.android.server.LocalServices;
243import com.android.server.ServiceThread;
244import com.android.server.SystemConfig;
245import com.android.server.Watchdog;
246import com.android.server.pm.PermissionsState.PermissionState;
247import com.android.server.pm.Settings.DatabaseVersion;
248import com.android.server.pm.Settings.VersionInfo;
249import com.android.server.storage.DeviceStorageMonitorInternal;
250
251import dalvik.system.CloseGuard;
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those APKs everywhere.
304 * <p>
305 * Internally there are two important locks:
306 * <ul>
307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308 * and other related state. It is a fine-grained lock that should only be held
309 * momentarily, as it's one of the most contended locks in the system.
310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311 * operations typically involve heavy lifting of application data on disk. Since
312 * {@code installd} is single-threaded, and it's operations can often be slow,
313 * this lock should never be acquired while already holding {@link #mPackages}.
314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315 * holding {@link #mInstallLock}.
316 * </ul>
317 * Many internal methods rely on the caller to hold the appropriate locks, and
318 * this contract is expressed through method name suffixes:
319 * <ul>
320 * <li>fooLI(): the caller must hold {@link #mInstallLock}
321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322 * being modified must be frozen
323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325 * </ul>
326 * <p>
327 * Because this class is very central to the platform's security; please run all
328 * CTS and unit tests whenever making modifications:
329 *
330 * <pre>
331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333 * </pre>
334 */
335public class PackageManagerService extends IPackageManager.Stub {
336    static final String TAG = "PackageManager";
337    static final boolean DEBUG_SETTINGS = false;
338    static final boolean DEBUG_PREFERRED = false;
339    static final boolean DEBUG_UPGRADE = false;
340    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341    private static final boolean DEBUG_BACKUP = false;
342    private static final boolean DEBUG_INSTALL = false;
343    private static final boolean DEBUG_REMOVE = false;
344    private static final boolean DEBUG_BROADCASTS = false;
345    private static final boolean DEBUG_SHOW_INFO = false;
346    private static final boolean DEBUG_PACKAGE_INFO = false;
347    private static final boolean DEBUG_INTENT_MATCHING = false;
348    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349    private static final boolean DEBUG_VERIFY = false;
350    private static final boolean DEBUG_FILTERS = false;
351
352    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354    // user, but by default initialize to this.
355    static final boolean DEBUG_DEXOPT = false;
356
357    private static final boolean DEBUG_ABI_SELECTION = false;
358    private static final boolean DEBUG_EPHEMERAL = false;
359    private static final boolean DEBUG_TRIAGED_MISSING = false;
360    private static final boolean DEBUG_APP_DATA = false;
361
362    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363
364    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365
366    private static final int RADIO_UID = Process.PHONE_UID;
367    private static final int LOG_UID = Process.LOG_UID;
368    private static final int NFC_UID = Process.NFC_UID;
369    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370    private static final int SHELL_UID = Process.SHELL_UID;
371
372    // Cap the size of permission trees that 3rd party apps can define
373    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374
375    // Suffix used during package installation when copying/moving
376    // package apks to install directory.
377    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378
379    static final int SCAN_NO_DEX = 1<<1;
380    static final int SCAN_FORCE_DEX = 1<<2;
381    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382    static final int SCAN_NEW_INSTALL = 1<<4;
383    static final int SCAN_NO_PATHS = 1<<5;
384    static final int SCAN_UPDATE_TIME = 1<<6;
385    static final int SCAN_DEFER_DEX = 1<<7;
386    static final int SCAN_BOOTING = 1<<8;
387    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String PLATFORM_PACKAGE_NAME = "android";
441
442    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
443
444    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
445            DEFAULT_CONTAINER_PACKAGE,
446            "com.android.defcontainer.DefaultContainerService");
447
448    private static final String KILL_APP_REASON_GIDS_CHANGED =
449            "permission grant or revoke changed gids";
450
451    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
452            "permissions revoked";
453
454    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
455
456    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
457
458    /** Permission grant: not grant the permission. */
459    private static final int GRANT_DENIED = 1;
460
461    /** Permission grant: grant the permission as an install permission. */
462    private static final int GRANT_INSTALL = 2;
463
464    /** Permission grant: grant the permission as a runtime one. */
465    private static final int GRANT_RUNTIME = 3;
466
467    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
468    private static final int GRANT_UPGRADE = 4;
469
470    /** Canonical intent used to identify what counts as a "web browser" app */
471    private static final Intent sBrowserIntent;
472    static {
473        sBrowserIntent = new Intent();
474        sBrowserIntent.setAction(Intent.ACTION_VIEW);
475        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
476        sBrowserIntent.setData(Uri.parse("http:"));
477    }
478
479    /**
480     * The set of all protected actions [i.e. those actions for which a high priority
481     * intent filter is disallowed].
482     */
483    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
484    static {
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
486        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
487        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
488        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
489    }
490
491    // Compilation reasons.
492    public static final int REASON_FIRST_BOOT = 0;
493    public static final int REASON_BOOT = 1;
494    public static final int REASON_INSTALL = 2;
495    public static final int REASON_BACKGROUND_DEXOPT = 3;
496    public static final int REASON_AB_OTA = 4;
497    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
498    public static final int REASON_SHARED_APK = 6;
499    public static final int REASON_FORCED_DEXOPT = 7;
500
501    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
502
503    /** Special library name that skips shared libraries check during compilation. */
504    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
505
506    final ServiceThread mHandlerThread;
507
508    final PackageHandler mHandler;
509
510    private final ProcessLoggingHandler mProcessLoggingHandler;
511
512    /**
513     * Messages for {@link #mHandler} that need to wait for system ready before
514     * being dispatched.
515     */
516    private ArrayList<Message> mPostSystemReadyMessages;
517
518    final int mSdkVersion = Build.VERSION.SDK_INT;
519
520    final Context mContext;
521    final boolean mFactoryTest;
522    final boolean mOnlyCore;
523    final DisplayMetrics mMetrics;
524    final int mDefParseFlags;
525    final String[] mSeparateProcesses;
526    final boolean mIsUpgrade;
527    final boolean mIsPreNUpgrade;
528
529    /** The location for ASEC container files on internal storage. */
530    final String mAsecInternalPath;
531
532    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
533    // LOCK HELD.  Can be called with mInstallLock held.
534    @GuardedBy("mInstallLock")
535    final Installer mInstaller;
536
537    /** Directory where installed third-party apps stored */
538    final File mAppInstallDir;
539    final File mEphemeralInstallDir;
540
541    /**
542     * Directory to which applications installed internally have their
543     * 32 bit native libraries copied.
544     */
545    private File mAppLib32InstallDir;
546
547    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
548    // apps.
549    final File mDrmAppPrivateInstallDir;
550
551    // ----------------------------------------------------------------
552
553    // Lock for state used when installing and doing other long running
554    // operations.  Methods that must be called with this lock held have
555    // the suffix "LI".
556    final Object mInstallLock = new Object();
557
558    // ----------------------------------------------------------------
559
560    // Keys are String (package name), values are Package.  This also serves
561    // as the lock for the global state.  Methods that must be called with
562    // this lock held have the prefix "LP".
563    @GuardedBy("mPackages")
564    final ArrayMap<String, PackageParser.Package> mPackages =
565            new ArrayMap<String, PackageParser.Package>();
566
567    final ArrayMap<String, Set<String>> mKnownCodebase =
568            new ArrayMap<String, Set<String>>();
569
570    // Tracks available target package names -> overlay package paths.
571    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
572        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
573
574    /**
575     * Tracks new system packages [received in an OTA] that we expect to
576     * find updated user-installed versions. Keys are package name, values
577     * are package location.
578     */
579    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
580    /**
581     * Tracks high priority intent filters for protected actions. During boot, certain
582     * filter actions are protected and should never be allowed to have a high priority
583     * intent filter for them. However, there is one, and only one exception -- the
584     * setup wizard. It must be able to define a high priority intent filter for these
585     * actions to ensure there are no escapes from the wizard. We need to delay processing
586     * of these during boot as we need to look at all of the system packages in order
587     * to know which component is the setup wizard.
588     */
589    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
590    /**
591     * Whether or not processing protected filters should be deferred.
592     */
593    private boolean mDeferProtectedFilters = true;
594
595    /**
596     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
597     */
598    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
599    /**
600     * Whether or not system app permissions should be promoted from install to runtime.
601     */
602    boolean mPromoteSystemApps;
603
604    @GuardedBy("mPackages")
605    final Settings mSettings;
606
607    /**
608     * Set of package names that are currently "frozen", which means active
609     * surgery is being done on the code/data for that package. The platform
610     * will refuse to launch frozen packages to avoid race conditions.
611     *
612     * @see PackageFreezer
613     */
614    @GuardedBy("mPackages")
615    final ArraySet<String> mFrozenPackages = new ArraySet<>();
616
617    boolean mRestoredSettings;
618
619    // System configuration read by SystemConfig.
620    final int[] mGlobalGids;
621    final SparseArray<ArraySet<String>> mSystemPermissions;
622    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
623
624    // If mac_permissions.xml was found for seinfo labeling.
625    boolean mFoundPolicyFile;
626
627    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
628
629    public static final class SharedLibraryEntry {
630        public final String path;
631        public final String apk;
632
633        SharedLibraryEntry(String _path, String _apk) {
634            path = _path;
635            apk = _apk;
636        }
637    }
638
639    // Currently known shared libraries.
640    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
641            new ArrayMap<String, SharedLibraryEntry>();
642
643    // All available activities, for your resolving pleasure.
644    final ActivityIntentResolver mActivities =
645            new ActivityIntentResolver();
646
647    // All available receivers, for your resolving pleasure.
648    final ActivityIntentResolver mReceivers =
649            new ActivityIntentResolver();
650
651    // All available services, for your resolving pleasure.
652    final ServiceIntentResolver mServices = new ServiceIntentResolver();
653
654    // All available providers, for your resolving pleasure.
655    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
656
657    // Mapping from provider base names (first directory in content URI codePath)
658    // to the provider information.
659    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
660            new ArrayMap<String, PackageParser.Provider>();
661
662    // Mapping from instrumentation class names to info about them.
663    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
664            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
665
666    // Mapping from permission names to info about them.
667    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
668            new ArrayMap<String, PackageParser.PermissionGroup>();
669
670    // Packages whose data we have transfered into another package, thus
671    // should no longer exist.
672    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
673
674    // Broadcast actions that are only available to the system.
675    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
676
677    /** List of packages waiting for verification. */
678    final SparseArray<PackageVerificationState> mPendingVerification
679            = new SparseArray<PackageVerificationState>();
680
681    /** Set of packages associated with each app op permission. */
682    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
683
684    final PackageInstallerService mInstallerService;
685
686    private final PackageDexOptimizer mPackageDexOptimizer;
687
688    private AtomicInteger mNextMoveId = new AtomicInteger();
689    private final MoveCallbacks mMoveCallbacks;
690
691    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
692
693    // Cache of users who need badging.
694    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
695
696    /** Token for keys in mPendingVerification. */
697    private int mPendingVerificationToken = 0;
698
699    volatile boolean mSystemReady;
700    volatile boolean mSafeMode;
701    volatile boolean mHasSystemUidErrors;
702
703    ApplicationInfo mAndroidApplication;
704    final ActivityInfo mResolveActivity = new ActivityInfo();
705    final ResolveInfo mResolveInfo = new ResolveInfo();
706    ComponentName mResolveComponentName;
707    PackageParser.Package mPlatformPackage;
708    ComponentName mCustomResolverComponentName;
709
710    boolean mResolverReplaced = false;
711
712    private final @Nullable ComponentName mIntentFilterVerifierComponent;
713    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
714
715    private int mIntentFilterVerificationToken = 0;
716
717    /** Component that knows whether or not an ephemeral application exists */
718    final ComponentName mEphemeralResolverComponent;
719    /** The service connection to the ephemeral resolver */
720    final EphemeralResolverConnection mEphemeralResolverConnection;
721
722    /** Component used to install ephemeral applications */
723    final ComponentName mEphemeralInstallerComponent;
724    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
725    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
726
727    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
728            = new SparseArray<IntentFilterVerificationState>();
729
730    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
731            new DefaultPermissionGrantPolicy(this);
732
733    // List of packages names to keep cached, even if they are uninstalled for all users
734    private List<String> mKeepUninstalledPackages;
735
736    private static class IFVerificationParams {
737        PackageParser.Package pkg;
738        boolean replacing;
739        int userId;
740        int verifierUid;
741
742        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
743                int _userId, int _verifierUid) {
744            pkg = _pkg;
745            replacing = _replacing;
746            userId = _userId;
747            replacing = _replacing;
748            verifierUid = _verifierUid;
749        }
750    }
751
752    private interface IntentFilterVerifier<T extends IntentFilter> {
753        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
754                                               T filter, String packageName);
755        void startVerifications(int userId);
756        void receiveVerificationResponse(int verificationId);
757    }
758
759    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
760        private Context mContext;
761        private ComponentName mIntentFilterVerifierComponent;
762        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
763
764        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
765            mContext = context;
766            mIntentFilterVerifierComponent = verifierComponent;
767        }
768
769        private String getDefaultScheme() {
770            return IntentFilter.SCHEME_HTTPS;
771        }
772
773        @Override
774        public void startVerifications(int userId) {
775            // Launch verifications requests
776            int count = mCurrentIntentFilterVerifications.size();
777            for (int n=0; n<count; n++) {
778                int verificationId = mCurrentIntentFilterVerifications.get(n);
779                final IntentFilterVerificationState ivs =
780                        mIntentFilterVerificationStates.get(verificationId);
781
782                String packageName = ivs.getPackageName();
783
784                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
785                final int filterCount = filters.size();
786                ArraySet<String> domainsSet = new ArraySet<>();
787                for (int m=0; m<filterCount; m++) {
788                    PackageParser.ActivityIntentInfo filter = filters.get(m);
789                    domainsSet.addAll(filter.getHostsList());
790                }
791                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
792                synchronized (mPackages) {
793                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
794                            packageName, domainsList) != null) {
795                        scheduleWriteSettingsLocked();
796                    }
797                }
798                sendVerificationRequest(userId, verificationId, ivs);
799            }
800            mCurrentIntentFilterVerifications.clear();
801        }
802
803        private void sendVerificationRequest(int userId, int verificationId,
804                IntentFilterVerificationState ivs) {
805
806            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
807            verificationIntent.putExtra(
808                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
809                    verificationId);
810            verificationIntent.putExtra(
811                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
812                    getDefaultScheme());
813            verificationIntent.putExtra(
814                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
815                    ivs.getHostsString());
816            verificationIntent.putExtra(
817                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
818                    ivs.getPackageName());
819            verificationIntent.setComponent(mIntentFilterVerifierComponent);
820            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
821
822            UserHandle user = new UserHandle(userId);
823            mContext.sendBroadcastAsUser(verificationIntent, user);
824            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
825                    "Sending IntentFilter verification broadcast");
826        }
827
828        public void receiveVerificationResponse(int verificationId) {
829            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
830
831            final boolean verified = ivs.isVerified();
832
833            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
834            final int count = filters.size();
835            if (DEBUG_DOMAIN_VERIFICATION) {
836                Slog.i(TAG, "Received verification response " + verificationId
837                        + " for " + count + " filters, verified=" + verified);
838            }
839            for (int n=0; n<count; n++) {
840                PackageParser.ActivityIntentInfo filter = filters.get(n);
841                filter.setVerified(verified);
842
843                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
844                        + " verified with result:" + verified + " and hosts:"
845                        + ivs.getHostsString());
846            }
847
848            mIntentFilterVerificationStates.remove(verificationId);
849
850            final String packageName = ivs.getPackageName();
851            IntentFilterVerificationInfo ivi = null;
852
853            synchronized (mPackages) {
854                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
855            }
856            if (ivi == null) {
857                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
858                        + verificationId + " packageName:" + packageName);
859                return;
860            }
861            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
862                    "Updating IntentFilterVerificationInfo for package " + packageName
863                            +" verificationId:" + verificationId);
864
865            synchronized (mPackages) {
866                if (verified) {
867                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
868                } else {
869                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
870                }
871                scheduleWriteSettingsLocked();
872
873                final int userId = ivs.getUserId();
874                if (userId != UserHandle.USER_ALL) {
875                    final int userStatus =
876                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
877
878                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
879                    boolean needUpdate = false;
880
881                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
882                    // already been set by the User thru the Disambiguation dialog
883                    switch (userStatus) {
884                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
885                            if (verified) {
886                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
887                            } else {
888                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
889                            }
890                            needUpdate = true;
891                            break;
892
893                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
894                            if (verified) {
895                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
896                                needUpdate = true;
897                            }
898                            break;
899
900                        default:
901                            // Nothing to do
902                    }
903
904                    if (needUpdate) {
905                        mSettings.updateIntentFilterVerificationStatusLPw(
906                                packageName, updatedStatus, userId);
907                        scheduleWritePackageRestrictionsLocked(userId);
908                    }
909                }
910            }
911        }
912
913        @Override
914        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
915                    ActivityIntentInfo filter, String packageName) {
916            if (!hasValidDomains(filter)) {
917                return false;
918            }
919            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
920            if (ivs == null) {
921                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
922                        packageName);
923            }
924            if (DEBUG_DOMAIN_VERIFICATION) {
925                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
926            }
927            ivs.addFilter(filter);
928            return true;
929        }
930
931        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
932                int userId, int verificationId, String packageName) {
933            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
934                    verifierUid, userId, packageName);
935            ivs.setPendingState();
936            synchronized (mPackages) {
937                mIntentFilterVerificationStates.append(verificationId, ivs);
938                mCurrentIntentFilterVerifications.add(verificationId);
939            }
940            return ivs;
941        }
942    }
943
944    private static boolean hasValidDomains(ActivityIntentInfo filter) {
945        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
946                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
947                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
948    }
949
950    // Set of pending broadcasts for aggregating enable/disable of components.
951    static class PendingPackageBroadcasts {
952        // for each user id, a map of <package name -> components within that package>
953        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
954
955        public PendingPackageBroadcasts() {
956            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
957        }
958
959        public ArrayList<String> get(int userId, String packageName) {
960            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
961            return packages.get(packageName);
962        }
963
964        public void put(int userId, String packageName, ArrayList<String> components) {
965            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
966            packages.put(packageName, components);
967        }
968
969        public void remove(int userId, String packageName) {
970            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
971            if (packages != null) {
972                packages.remove(packageName);
973            }
974        }
975
976        public void remove(int userId) {
977            mUidMap.remove(userId);
978        }
979
980        public int userIdCount() {
981            return mUidMap.size();
982        }
983
984        public int userIdAt(int n) {
985            return mUidMap.keyAt(n);
986        }
987
988        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
989            return mUidMap.get(userId);
990        }
991
992        public int size() {
993            // total number of pending broadcast entries across all userIds
994            int num = 0;
995            for (int i = 0; i< mUidMap.size(); i++) {
996                num += mUidMap.valueAt(i).size();
997            }
998            return num;
999        }
1000
1001        public void clear() {
1002            mUidMap.clear();
1003        }
1004
1005        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1006            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1007            if (map == null) {
1008                map = new ArrayMap<String, ArrayList<String>>();
1009                mUidMap.put(userId, map);
1010            }
1011            return map;
1012        }
1013    }
1014    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1015
1016    // Service Connection to remote media container service to copy
1017    // package uri's from external media onto secure containers
1018    // or internal storage.
1019    private IMediaContainerService mContainerService = null;
1020
1021    static final int SEND_PENDING_BROADCAST = 1;
1022    static final int MCS_BOUND = 3;
1023    static final int END_COPY = 4;
1024    static final int INIT_COPY = 5;
1025    static final int MCS_UNBIND = 6;
1026    static final int START_CLEANING_PACKAGE = 7;
1027    static final int FIND_INSTALL_LOC = 8;
1028    static final int POST_INSTALL = 9;
1029    static final int MCS_RECONNECT = 10;
1030    static final int MCS_GIVE_UP = 11;
1031    static final int UPDATED_MEDIA_STATUS = 12;
1032    static final int WRITE_SETTINGS = 13;
1033    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1034    static final int PACKAGE_VERIFIED = 15;
1035    static final int CHECK_PENDING_VERIFICATION = 16;
1036    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1037    static final int INTENT_FILTER_VERIFIED = 18;
1038
1039    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1040
1041    // Delay time in millisecs
1042    static final int BROADCAST_DELAY = 10 * 1000;
1043
1044    static UserManagerService sUserManager;
1045
1046    // Stores a list of users whose package restrictions file needs to be updated
1047    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1048
1049    final private DefaultContainerConnection mDefContainerConn =
1050            new DefaultContainerConnection();
1051    class DefaultContainerConnection implements ServiceConnection {
1052        public void onServiceConnected(ComponentName name, IBinder service) {
1053            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1054            IMediaContainerService imcs =
1055                IMediaContainerService.Stub.asInterface(service);
1056            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1057        }
1058
1059        public void onServiceDisconnected(ComponentName name) {
1060            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1061        }
1062    }
1063
1064    // Recordkeeping of restore-after-install operations that are currently in flight
1065    // between the Package Manager and the Backup Manager
1066    static class PostInstallData {
1067        public InstallArgs args;
1068        public PackageInstalledInfo res;
1069
1070        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1071            args = _a;
1072            res = _r;
1073        }
1074    }
1075
1076    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1077    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1078
1079    // XML tags for backup/restore of various bits of state
1080    private static final String TAG_PREFERRED_BACKUP = "pa";
1081    private static final String TAG_DEFAULT_APPS = "da";
1082    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1083
1084    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1085    private static final String TAG_ALL_GRANTS = "rt-grants";
1086    private static final String TAG_GRANT = "grant";
1087    private static final String ATTR_PACKAGE_NAME = "pkg";
1088
1089    private static final String TAG_PERMISSION = "perm";
1090    private static final String ATTR_PERMISSION_NAME = "name";
1091    private static final String ATTR_IS_GRANTED = "g";
1092    private static final String ATTR_USER_SET = "set";
1093    private static final String ATTR_USER_FIXED = "fixed";
1094    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1095
1096    // System/policy permission grants are not backed up
1097    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1098            FLAG_PERMISSION_POLICY_FIXED
1099            | FLAG_PERMISSION_SYSTEM_FIXED
1100            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1101
1102    // And we back up these user-adjusted states
1103    private static final int USER_RUNTIME_GRANT_MASK =
1104            FLAG_PERMISSION_USER_SET
1105            | FLAG_PERMISSION_USER_FIXED
1106            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1107
1108    final @Nullable String mRequiredVerifierPackage;
1109    final @NonNull String mRequiredInstallerPackage;
1110    final @Nullable String mSetupWizardPackage;
1111    final @NonNull String mServicesSystemSharedLibraryPackageName;
1112    final @NonNull String mSharedSystemSharedLibraryPackageName;
1113
1114    private final PackageUsage mPackageUsage = new PackageUsage();
1115
1116    private class PackageUsage {
1117        private static final int WRITE_INTERVAL
1118            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1119
1120        private final Object mFileLock = new Object();
1121        private final AtomicLong mLastWritten = new AtomicLong(0);
1122        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1123
1124        private boolean mIsHistoricalPackageUsageAvailable = true;
1125
1126        boolean isHistoricalPackageUsageAvailable() {
1127            return mIsHistoricalPackageUsageAvailable;
1128        }
1129
1130        void write(boolean force) {
1131            if (force) {
1132                writeInternal();
1133                return;
1134            }
1135            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1136                && !DEBUG_DEXOPT) {
1137                return;
1138            }
1139            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1140                new Thread("PackageUsage_DiskWriter") {
1141                    @Override
1142                    public void run() {
1143                        try {
1144                            writeInternal();
1145                        } finally {
1146                            mBackgroundWriteRunning.set(false);
1147                        }
1148                    }
1149                }.start();
1150            }
1151        }
1152
1153        private void writeInternal() {
1154            synchronized (mPackages) {
1155                synchronized (mFileLock) {
1156                    AtomicFile file = getFile();
1157                    FileOutputStream f = null;
1158                    try {
1159                        f = file.startWrite();
1160                        BufferedOutputStream out = new BufferedOutputStream(f);
1161                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1162                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1163                        StringBuilder sb = new StringBuilder();
1164
1165                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1166                        sb.append('\n');
1167                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1168
1169                        for (PackageParser.Package pkg : mPackages.values()) {
1170                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1171                                continue;
1172                            }
1173                            sb.setLength(0);
1174                            sb.append(pkg.packageName);
1175                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1176                                sb.append(' ');
1177                                sb.append(usageTimeInMillis);
1178                            }
1179                            sb.append('\n');
1180                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1181                        }
1182                        out.flush();
1183                        file.finishWrite(f);
1184                    } catch (IOException e) {
1185                        if (f != null) {
1186                            file.failWrite(f);
1187                        }
1188                        Log.e(TAG, "Failed to write package usage times", e);
1189                    }
1190                }
1191            }
1192            mLastWritten.set(SystemClock.elapsedRealtime());
1193        }
1194
1195        void readLP() {
1196            synchronized (mFileLock) {
1197                AtomicFile file = getFile();
1198                BufferedInputStream in = null;
1199                try {
1200                    in = new BufferedInputStream(file.openRead());
1201                    StringBuffer sb = new StringBuffer();
1202
1203                    String firstLine = readLine(in, sb);
1204                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1205                        readVersion1LP(in, sb);
1206                    } else {
1207                        readVersion0LP(in, sb, firstLine);
1208                    }
1209                } catch (FileNotFoundException expected) {
1210                    mIsHistoricalPackageUsageAvailable = false;
1211                } catch (IOException e) {
1212                    Log.w(TAG, "Failed to read package usage times", e);
1213                } finally {
1214                    IoUtils.closeQuietly(in);
1215                }
1216            }
1217            mLastWritten.set(SystemClock.elapsedRealtime());
1218        }
1219
1220        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1221                throws IOException {
1222            // Initial version of the file had no version number and stored one
1223            // package-timestamp pair per line.
1224            // Note that the first line has already been read from the InputStream.
1225            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1226                String[] tokens = line.split(" ");
1227                if (tokens.length != 2) {
1228                    throw new IOException("Failed to parse " + line +
1229                            " as package-timestamp pair.");
1230                }
1231
1232                String packageName = tokens[0];
1233                PackageParser.Package pkg = mPackages.get(packageName);
1234                if (pkg == null) {
1235                    continue;
1236                }
1237
1238                long timestamp = parseAsLong(tokens[1]);
1239                for (int reason = 0;
1240                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1241                        reason++) {
1242                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1243                }
1244            }
1245        }
1246
1247        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1248            // Version 1 of the file started with the corresponding version
1249            // number and then stored a package name and eight timestamps per line.
1250            String line;
1251            while ((line = readLine(in, sb)) != null) {
1252                String[] tokens = line.split(" ");
1253                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1254                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1255                }
1256
1257                String packageName = tokens[0];
1258                PackageParser.Package pkg = mPackages.get(packageName);
1259                if (pkg == null) {
1260                    continue;
1261                }
1262
1263                for (int reason = 0;
1264                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1265                        reason++) {
1266                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1267                }
1268            }
1269        }
1270
1271        private long parseAsLong(String token) throws IOException {
1272            try {
1273                return Long.parseLong(token);
1274            } catch (NumberFormatException e) {
1275                throw new IOException("Failed to parse " + token + " as a long.", e);
1276            }
1277        }
1278
1279        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1280            return readToken(in, sb, '\n');
1281        }
1282
1283        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1284                throws IOException {
1285            sb.setLength(0);
1286            while (true) {
1287                int ch = in.read();
1288                if (ch == -1) {
1289                    if (sb.length() == 0) {
1290                        return null;
1291                    }
1292                    throw new IOException("Unexpected EOF");
1293                }
1294                if (ch == endOfToken) {
1295                    return sb.toString();
1296                }
1297                sb.append((char)ch);
1298            }
1299        }
1300
1301        private AtomicFile getFile() {
1302            File dataDir = Environment.getDataDirectory();
1303            File systemDir = new File(dataDir, "system");
1304            File fname = new File(systemDir, "package-usage.list");
1305            return new AtomicFile(fname);
1306        }
1307
1308        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1309        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1310    }
1311
1312    class PackageHandler extends Handler {
1313        private boolean mBound = false;
1314        final ArrayList<HandlerParams> mPendingInstalls =
1315            new ArrayList<HandlerParams>();
1316
1317        private boolean connectToService() {
1318            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1319                    " DefaultContainerService");
1320            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1321            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1322            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1323                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1324                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1325                mBound = true;
1326                return true;
1327            }
1328            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1329            return false;
1330        }
1331
1332        private void disconnectService() {
1333            mContainerService = null;
1334            mBound = false;
1335            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1336            mContext.unbindService(mDefContainerConn);
1337            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1338        }
1339
1340        PackageHandler(Looper looper) {
1341            super(looper);
1342        }
1343
1344        public void handleMessage(Message msg) {
1345            try {
1346                doHandleMessage(msg);
1347            } finally {
1348                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349            }
1350        }
1351
1352        void doHandleMessage(Message msg) {
1353            switch (msg.what) {
1354                case INIT_COPY: {
1355                    HandlerParams params = (HandlerParams) msg.obj;
1356                    int idx = mPendingInstalls.size();
1357                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1358                    // If a bind was already initiated we dont really
1359                    // need to do anything. The pending install
1360                    // will be processed later on.
1361                    if (!mBound) {
1362                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1363                                System.identityHashCode(mHandler));
1364                        // If this is the only one pending we might
1365                        // have to bind to the service again.
1366                        if (!connectToService()) {
1367                            Slog.e(TAG, "Failed to bind to media container service");
1368                            params.serviceError();
1369                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1370                                    System.identityHashCode(mHandler));
1371                            if (params.traceMethod != null) {
1372                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1373                                        params.traceCookie);
1374                            }
1375                            return;
1376                        } else {
1377                            // Once we bind to the service, the first
1378                            // pending request will be processed.
1379                            mPendingInstalls.add(idx, params);
1380                        }
1381                    } else {
1382                        mPendingInstalls.add(idx, params);
1383                        // Already bound to the service. Just make
1384                        // sure we trigger off processing the first request.
1385                        if (idx == 0) {
1386                            mHandler.sendEmptyMessage(MCS_BOUND);
1387                        }
1388                    }
1389                    break;
1390                }
1391                case MCS_BOUND: {
1392                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1393                    if (msg.obj != null) {
1394                        mContainerService = (IMediaContainerService) msg.obj;
1395                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1396                                System.identityHashCode(mHandler));
1397                    }
1398                    if (mContainerService == null) {
1399                        if (!mBound) {
1400                            // Something seriously wrong since we are not bound and we are not
1401                            // waiting for connection. Bail out.
1402                            Slog.e(TAG, "Cannot 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                                if (params.traceMethod != null) {
1409                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1410                                            params.traceMethod, params.traceCookie);
1411                                }
1412                                return;
1413                            }
1414                            mPendingInstalls.clear();
1415                        } else {
1416                            Slog.w(TAG, "Waiting to connect to media container service");
1417                        }
1418                    } else if (mPendingInstalls.size() > 0) {
1419                        HandlerParams params = mPendingInstalls.get(0);
1420                        if (params != null) {
1421                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1422                                    System.identityHashCode(params));
1423                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1424                            if (params.startCopy()) {
1425                                // We are done...  look for more work or to
1426                                // go idle.
1427                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1428                                        "Checking for more work or unbind...");
1429                                // Delete pending install
1430                                if (mPendingInstalls.size() > 0) {
1431                                    mPendingInstalls.remove(0);
1432                                }
1433                                if (mPendingInstalls.size() == 0) {
1434                                    if (mBound) {
1435                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1436                                                "Posting delayed MCS_UNBIND");
1437                                        removeMessages(MCS_UNBIND);
1438                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1439                                        // Unbind after a little delay, to avoid
1440                                        // continual thrashing.
1441                                        sendMessageDelayed(ubmsg, 10000);
1442                                    }
1443                                } else {
1444                                    // There are more pending requests in queue.
1445                                    // Just post MCS_BOUND message to trigger processing
1446                                    // of next pending install.
1447                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1448                                            "Posting MCS_BOUND for next work");
1449                                    mHandler.sendEmptyMessage(MCS_BOUND);
1450                                }
1451                            }
1452                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1453                        }
1454                    } else {
1455                        // Should never happen ideally.
1456                        Slog.w(TAG, "Empty queue");
1457                    }
1458                    break;
1459                }
1460                case MCS_RECONNECT: {
1461                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1462                    if (mPendingInstalls.size() > 0) {
1463                        if (mBound) {
1464                            disconnectService();
1465                        }
1466                        if (!connectToService()) {
1467                            Slog.e(TAG, "Failed to bind to media container service");
1468                            for (HandlerParams params : mPendingInstalls) {
1469                                // Indicate service bind error
1470                                params.serviceError();
1471                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1472                                        System.identityHashCode(params));
1473                            }
1474                            mPendingInstalls.clear();
1475                        }
1476                    }
1477                    break;
1478                }
1479                case MCS_UNBIND: {
1480                    // If there is no actual work left, then time to unbind.
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1482
1483                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1484                        if (mBound) {
1485                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1486
1487                            disconnectService();
1488                        }
1489                    } else if (mPendingInstalls.size() > 0) {
1490                        // There are more pending requests in queue.
1491                        // Just post MCS_BOUND message to trigger processing
1492                        // of next pending install.
1493                        mHandler.sendEmptyMessage(MCS_BOUND);
1494                    }
1495
1496                    break;
1497                }
1498                case MCS_GIVE_UP: {
1499                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1500                    HandlerParams params = mPendingInstalls.remove(0);
1501                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1502                            System.identityHashCode(params));
1503                    break;
1504                }
1505                case SEND_PENDING_BROADCAST: {
1506                    String packages[];
1507                    ArrayList<String> components[];
1508                    int size = 0;
1509                    int uids[];
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1511                    synchronized (mPackages) {
1512                        if (mPendingBroadcasts == null) {
1513                            return;
1514                        }
1515                        size = mPendingBroadcasts.size();
1516                        if (size <= 0) {
1517                            // Nothing to be done. Just return
1518                            return;
1519                        }
1520                        packages = new String[size];
1521                        components = new ArrayList[size];
1522                        uids = new int[size];
1523                        int i = 0;  // filling out the above arrays
1524
1525                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1526                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1527                            Iterator<Map.Entry<String, ArrayList<String>>> it
1528                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1529                                            .entrySet().iterator();
1530                            while (it.hasNext() && i < size) {
1531                                Map.Entry<String, ArrayList<String>> ent = it.next();
1532                                packages[i] = ent.getKey();
1533                                components[i] = ent.getValue();
1534                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1535                                uids[i] = (ps != null)
1536                                        ? UserHandle.getUid(packageUserId, ps.appId)
1537                                        : -1;
1538                                i++;
1539                            }
1540                        }
1541                        size = i;
1542                        mPendingBroadcasts.clear();
1543                    }
1544                    // Send broadcasts
1545                    for (int i = 0; i < size; i++) {
1546                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1547                    }
1548                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1549                    break;
1550                }
1551                case START_CLEANING_PACKAGE: {
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1553                    final String packageName = (String)msg.obj;
1554                    final int userId = msg.arg1;
1555                    final boolean andCode = msg.arg2 != 0;
1556                    synchronized (mPackages) {
1557                        if (userId == UserHandle.USER_ALL) {
1558                            int[] users = sUserManager.getUserIds();
1559                            for (int user : users) {
1560                                mSettings.addPackageToCleanLPw(
1561                                        new PackageCleanItem(user, packageName, andCode));
1562                            }
1563                        } else {
1564                            mSettings.addPackageToCleanLPw(
1565                                    new PackageCleanItem(userId, packageName, andCode));
1566                        }
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                    startCleaningPackages();
1570                } break;
1571                case POST_INSTALL: {
1572                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1573
1574                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1575                    final boolean didRestore = (msg.arg2 != 0);
1576                    mRunningInstalls.delete(msg.arg1);
1577
1578                    if (data != null) {
1579                        InstallArgs args = data.args;
1580                        PackageInstalledInfo parentRes = data.res;
1581
1582                        final boolean grantPermissions = (args.installFlags
1583                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1584                        final boolean killApp = (args.installFlags
1585                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1586                        final String[] grantedPermissions = args.installGrantPermissions;
1587
1588                        // Handle the parent package
1589                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1590                                grantedPermissions, didRestore, args.installerPackageName,
1591                                args.observer);
1592
1593                        // Handle the child packages
1594                        final int childCount = (parentRes.addedChildPackages != null)
1595                                ? parentRes.addedChildPackages.size() : 0;
1596                        for (int i = 0; i < childCount; i++) {
1597                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1598                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1599                                    grantedPermissions, false, args.installerPackageName,
1600                                    args.observer);
1601                        }
1602
1603                        // Log tracing if needed
1604                        if (args.traceMethod != null) {
1605                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1606                                    args.traceCookie);
1607                        }
1608                    } else {
1609                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1610                    }
1611
1612                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1613                } break;
1614                case UPDATED_MEDIA_STATUS: {
1615                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1616                    boolean reportStatus = msg.arg1 == 1;
1617                    boolean doGc = msg.arg2 == 1;
1618                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1619                    if (doGc) {
1620                        // Force a gc to clear up stale containers.
1621                        Runtime.getRuntime().gc();
1622                    }
1623                    if (msg.obj != null) {
1624                        @SuppressWarnings("unchecked")
1625                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1626                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1627                        // Unload containers
1628                        unloadAllContainers(args);
1629                    }
1630                    if (reportStatus) {
1631                        try {
1632                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1633                            PackageHelper.getMountService().finishMediaUpdate();
1634                        } catch (RemoteException e) {
1635                            Log.e(TAG, "MountService not running?");
1636                        }
1637                    }
1638                } break;
1639                case WRITE_SETTINGS: {
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1641                    synchronized (mPackages) {
1642                        removeMessages(WRITE_SETTINGS);
1643                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1644                        mSettings.writeLPr();
1645                        mDirtyUsers.clear();
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                } break;
1649                case WRITE_PACKAGE_RESTRICTIONS: {
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1651                    synchronized (mPackages) {
1652                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1653                        for (int userId : mDirtyUsers) {
1654                            mSettings.writePackageRestrictionsLPr(userId);
1655                        }
1656                        mDirtyUsers.clear();
1657                    }
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1659                } break;
1660                case CHECK_PENDING_VERIFICATION: {
1661                    final int verificationId = msg.arg1;
1662                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1663
1664                    if ((state != null) && !state.timeoutExtended()) {
1665                        final InstallArgs args = state.getInstallArgs();
1666                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1667
1668                        Slog.i(TAG, "Verification timed out for " + originUri);
1669                        mPendingVerification.remove(verificationId);
1670
1671                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1672
1673                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1674                            Slog.i(TAG, "Continuing with installation of " + originUri);
1675                            state.setVerifierResponse(Binder.getCallingUid(),
1676                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1677                            broadcastPackageVerified(verificationId, originUri,
1678                                    PackageManager.VERIFICATION_ALLOW,
1679                                    state.getInstallArgs().getUser());
1680                            try {
1681                                ret = args.copyApk(mContainerService, true);
1682                            } catch (RemoteException e) {
1683                                Slog.e(TAG, "Could not contact the ContainerService");
1684                            }
1685                        } else {
1686                            broadcastPackageVerified(verificationId, originUri,
1687                                    PackageManager.VERIFICATION_REJECT,
1688                                    state.getInstallArgs().getUser());
1689                        }
1690
1691                        Trace.asyncTraceEnd(
1692                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1693
1694                        processPendingInstall(args, ret);
1695                        mHandler.sendEmptyMessage(MCS_UNBIND);
1696                    }
1697                    break;
1698                }
1699                case PACKAGE_VERIFIED: {
1700                    final int verificationId = msg.arg1;
1701
1702                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1703                    if (state == null) {
1704                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1705                        break;
1706                    }
1707
1708                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1709
1710                    state.setVerifierResponse(response.callerUid, response.code);
1711
1712                    if (state.isVerificationComplete()) {
1713                        mPendingVerification.remove(verificationId);
1714
1715                        final InstallArgs args = state.getInstallArgs();
1716                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1717
1718                        int ret;
1719                        if (state.isInstallAllowed()) {
1720                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1721                            broadcastPackageVerified(verificationId, originUri,
1722                                    response.code, state.getInstallArgs().getUser());
1723                            try {
1724                                ret = args.copyApk(mContainerService, true);
1725                            } catch (RemoteException e) {
1726                                Slog.e(TAG, "Could not contact the ContainerService");
1727                            }
1728                        } else {
1729                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1730                        }
1731
1732                        Trace.asyncTraceEnd(
1733                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1734
1735                        processPendingInstall(args, ret);
1736                        mHandler.sendEmptyMessage(MCS_UNBIND);
1737                    }
1738
1739                    break;
1740                }
1741                case START_INTENT_FILTER_VERIFICATIONS: {
1742                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1743                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1744                            params.replacing, params.pkg);
1745                    break;
1746                }
1747                case INTENT_FILTER_VERIFIED: {
1748                    final int verificationId = msg.arg1;
1749
1750                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1751                            verificationId);
1752                    if (state == null) {
1753                        Slog.w(TAG, "Invalid IntentFilter verification token "
1754                                + verificationId + " received");
1755                        break;
1756                    }
1757
1758                    final int userId = state.getUserId();
1759
1760                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1761                            "Processing IntentFilter verification with token:"
1762                            + verificationId + " and userId:" + userId);
1763
1764                    final IntentFilterVerificationResponse response =
1765                            (IntentFilterVerificationResponse) msg.obj;
1766
1767                    state.setVerifierResponse(response.callerUid, response.code);
1768
1769                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1770                            "IntentFilter verification with token:" + verificationId
1771                            + " and userId:" + userId
1772                            + " is settings verifier response with response code:"
1773                            + response.code);
1774
1775                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1776                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1777                                + response.getFailedDomainsString());
1778                    }
1779
1780                    if (state.isVerificationComplete()) {
1781                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1782                    } else {
1783                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1784                                "IntentFilter verification with token:" + verificationId
1785                                + " was not said to be complete");
1786                    }
1787
1788                    break;
1789                }
1790            }
1791        }
1792    }
1793
1794    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1795            boolean killApp, String[] grantedPermissions,
1796            boolean launchedForRestore, String installerPackage,
1797            IPackageInstallObserver2 installObserver) {
1798        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1799            // Send the removed broadcasts
1800            if (res.removedInfo != null) {
1801                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1802            }
1803
1804            // Now that we successfully installed the package, grant runtime
1805            // permissions if requested before broadcasting the install.
1806            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1807                    >= Build.VERSION_CODES.M) {
1808                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1809            }
1810
1811            final boolean update = res.removedInfo != null
1812                    && res.removedInfo.removedPackage != null;
1813
1814            // If this is the first time we have child packages for a disabled privileged
1815            // app that had no children, we grant requested runtime permissions to the new
1816            // children if the parent on the system image had them already granted.
1817            if (res.pkg.parentPackage != null) {
1818                synchronized (mPackages) {
1819                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1820                }
1821            }
1822
1823            synchronized (mPackages) {
1824                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1825            }
1826
1827            final String packageName = res.pkg.applicationInfo.packageName;
1828            Bundle extras = new Bundle(1);
1829            extras.putInt(Intent.EXTRA_UID, res.uid);
1830
1831            // Determine the set of users who are adding this package for
1832            // the first time vs. those who are seeing an update.
1833            int[] firstUsers = EMPTY_INT_ARRAY;
1834            int[] updateUsers = EMPTY_INT_ARRAY;
1835            if (res.origUsers == null || res.origUsers.length == 0) {
1836                firstUsers = res.newUsers;
1837            } else {
1838                for (int newUser : res.newUsers) {
1839                    boolean isNew = true;
1840                    for (int origUser : res.origUsers) {
1841                        if (origUser == newUser) {
1842                            isNew = false;
1843                            break;
1844                        }
1845                    }
1846                    if (isNew) {
1847                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1848                    } else {
1849                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1850                    }
1851                }
1852            }
1853
1854            // Send installed broadcasts if the install/update is not ephemeral
1855            if (!isEphemeral(res.pkg)) {
1856                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1857
1858                // Send added for users that see the package for the first time
1859                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1860                        extras, 0 /*flags*/, null /*targetPackage*/,
1861                        null /*finishedReceiver*/, firstUsers);
1862
1863                // Send added for users that don't see the package for the first time
1864                if (update) {
1865                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1866                }
1867                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1868                        extras, 0 /*flags*/, null /*targetPackage*/,
1869                        null /*finishedReceiver*/, updateUsers);
1870
1871                // Send replaced for users that don't see the package for the first time
1872                if (update) {
1873                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1874                            packageName, extras, 0 /*flags*/,
1875                            null /*targetPackage*/, null /*finishedReceiver*/,
1876                            updateUsers);
1877                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1878                            null /*package*/, null /*extras*/, 0 /*flags*/,
1879                            packageName /*targetPackage*/,
1880                            null /*finishedReceiver*/, updateUsers);
1881                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1882                    // First-install and we did a restore, so we're responsible for the
1883                    // first-launch broadcast.
1884                    if (DEBUG_BACKUP) {
1885                        Slog.i(TAG, "Post-restore of " + packageName
1886                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1887                    }
1888                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1889                }
1890
1891                // Send broadcast package appeared if forward locked/external for all users
1892                // treat asec-hosted packages like removable media on upgrade
1893                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1894                    if (DEBUG_INSTALL) {
1895                        Slog.i(TAG, "upgrading pkg " + res.pkg
1896                                + " is ASEC-hosted -> AVAILABLE");
1897                    }
1898                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1899                    ArrayList<String> pkgList = new ArrayList<>(1);
1900                    pkgList.add(packageName);
1901                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1902                }
1903            }
1904
1905            // Work that needs to happen on first install within each user
1906            if (firstUsers != null && firstUsers.length > 0) {
1907                synchronized (mPackages) {
1908                    for (int userId : firstUsers) {
1909                        // If this app is a browser and it's newly-installed for some
1910                        // users, clear any default-browser state in those users. The
1911                        // app's nature doesn't depend on the user, so we can just check
1912                        // its browser nature in any user and generalize.
1913                        if (packageIsBrowser(packageName, userId)) {
1914                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1915                        }
1916
1917                        // We may also need to apply pending (restored) runtime
1918                        // permission grants within these users.
1919                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1920                    }
1921                }
1922            }
1923
1924            // Log current value of "unknown sources" setting
1925            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1926                    getUnknownSourcesSettings());
1927
1928            // Force a gc to clear up things
1929            Runtime.getRuntime().gc();
1930
1931            // Remove the replaced package's older resources safely now
1932            // We delete after a gc for applications  on sdcard.
1933            if (res.removedInfo != null && res.removedInfo.args != null) {
1934                synchronized (mInstallLock) {
1935                    res.removedInfo.args.doPostDeleteLI(true);
1936                }
1937            }
1938        }
1939
1940        // If someone is watching installs - notify them
1941        if (installObserver != null) {
1942            try {
1943                Bundle extras = extrasForInstallResult(res);
1944                installObserver.onPackageInstalled(res.name, res.returnCode,
1945                        res.returnMsg, extras);
1946            } catch (RemoteException e) {
1947                Slog.i(TAG, "Observer no longer exists.");
1948            }
1949        }
1950    }
1951
1952    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1953            PackageParser.Package pkg) {
1954        if (pkg.parentPackage == null) {
1955            return;
1956        }
1957        if (pkg.requestedPermissions == null) {
1958            return;
1959        }
1960        final PackageSetting disabledSysParentPs = mSettings
1961                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1962        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1963                || !disabledSysParentPs.isPrivileged()
1964                || (disabledSysParentPs.childPackageNames != null
1965                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1966            return;
1967        }
1968        final int[] allUserIds = sUserManager.getUserIds();
1969        final int permCount = pkg.requestedPermissions.size();
1970        for (int i = 0; i < permCount; i++) {
1971            String permission = pkg.requestedPermissions.get(i);
1972            BasePermission bp = mSettings.mPermissions.get(permission);
1973            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1974                continue;
1975            }
1976            for (int userId : allUserIds) {
1977                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1978                        permission, userId)) {
1979                    grantRuntimePermission(pkg.packageName, permission, userId);
1980                }
1981            }
1982        }
1983    }
1984
1985    private StorageEventListener mStorageListener = new StorageEventListener() {
1986        @Override
1987        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1988            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1989                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1990                    final String volumeUuid = vol.getFsUuid();
1991
1992                    // Clean up any users or apps that were removed or recreated
1993                    // while this volume was missing
1994                    reconcileUsers(volumeUuid);
1995                    reconcileApps(volumeUuid);
1996
1997                    // Clean up any install sessions that expired or were
1998                    // cancelled while this volume was missing
1999                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2000
2001                    loadPrivatePackages(vol);
2002
2003                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2004                    unloadPrivatePackages(vol);
2005                }
2006            }
2007
2008            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2009                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2010                    updateExternalMediaStatus(true, false);
2011                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2012                    updateExternalMediaStatus(false, false);
2013                }
2014            }
2015        }
2016
2017        @Override
2018        public void onVolumeForgotten(String fsUuid) {
2019            if (TextUtils.isEmpty(fsUuid)) {
2020                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2021                return;
2022            }
2023
2024            // Remove any apps installed on the forgotten volume
2025            synchronized (mPackages) {
2026                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2027                for (PackageSetting ps : packages) {
2028                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2029                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2030                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2031                }
2032
2033                mSettings.onVolumeForgotten(fsUuid);
2034                mSettings.writeLPr();
2035            }
2036        }
2037    };
2038
2039    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2040            String[] grantedPermissions) {
2041        for (int userId : userIds) {
2042            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2043        }
2044
2045        // We could have touched GID membership, so flush out packages.list
2046        synchronized (mPackages) {
2047            mSettings.writePackageListLPr();
2048        }
2049    }
2050
2051    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2052            String[] grantedPermissions) {
2053        SettingBase sb = (SettingBase) pkg.mExtras;
2054        if (sb == null) {
2055            return;
2056        }
2057
2058        PermissionsState permissionsState = sb.getPermissionsState();
2059
2060        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2061                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2062
2063        for (String permission : pkg.requestedPermissions) {
2064            final BasePermission bp;
2065            synchronized (mPackages) {
2066                bp = mSettings.mPermissions.get(permission);
2067            }
2068            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2069                    && (grantedPermissions == null
2070                           || ArrayUtils.contains(grantedPermissions, permission))) {
2071                final int flags = permissionsState.getPermissionFlags(permission, userId);
2072                // Installer cannot change immutable permissions.
2073                if ((flags & immutableFlags) == 0) {
2074                    grantRuntimePermission(pkg.packageName, permission, userId);
2075                }
2076            }
2077        }
2078    }
2079
2080    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2081        Bundle extras = null;
2082        switch (res.returnCode) {
2083            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2084                extras = new Bundle();
2085                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2086                        res.origPermission);
2087                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2088                        res.origPackage);
2089                break;
2090            }
2091            case PackageManager.INSTALL_SUCCEEDED: {
2092                extras = new Bundle();
2093                extras.putBoolean(Intent.EXTRA_REPLACING,
2094                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2095                break;
2096            }
2097        }
2098        return extras;
2099    }
2100
2101    void scheduleWriteSettingsLocked() {
2102        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2103            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2104        }
2105    }
2106
2107    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2108        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2109        scheduleWritePackageRestrictionsLocked(userId);
2110    }
2111
2112    void scheduleWritePackageRestrictionsLocked(int userId) {
2113        final int[] userIds = (userId == UserHandle.USER_ALL)
2114                ? sUserManager.getUserIds() : new int[]{userId};
2115        for (int nextUserId : userIds) {
2116            if (!sUserManager.exists(nextUserId)) return;
2117            mDirtyUsers.add(nextUserId);
2118            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2119                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2120            }
2121        }
2122    }
2123
2124    public static PackageManagerService main(Context context, Installer installer,
2125            boolean factoryTest, boolean onlyCore) {
2126        // Self-check for initial settings.
2127        PackageManagerServiceCompilerMapping.checkProperties();
2128
2129        PackageManagerService m = new PackageManagerService(context, installer,
2130                factoryTest, onlyCore);
2131        m.enableSystemUserPackages();
2132        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2133        // disabled after already being started.
2134        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2135                UserHandle.USER_SYSTEM);
2136        ServiceManager.addService("package", m);
2137        return m;
2138    }
2139
2140    private void enableSystemUserPackages() {
2141        if (!UserManager.isSplitSystemUser()) {
2142            return;
2143        }
2144        // For system user, enable apps based on the following conditions:
2145        // - app is whitelisted or belong to one of these groups:
2146        //   -- system app which has no launcher icons
2147        //   -- system app which has INTERACT_ACROSS_USERS permission
2148        //   -- system IME app
2149        // - app is not in the blacklist
2150        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2151        Set<String> enableApps = new ArraySet<>();
2152        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2153                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2154                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2155        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2156        enableApps.addAll(wlApps);
2157        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2158                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2159        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2160        enableApps.removeAll(blApps);
2161        Log.i(TAG, "Applications installed for system user: " + enableApps);
2162        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2163                UserHandle.SYSTEM);
2164        final int allAppsSize = allAps.size();
2165        synchronized (mPackages) {
2166            for (int i = 0; i < allAppsSize; i++) {
2167                String pName = allAps.get(i);
2168                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2169                // Should not happen, but we shouldn't be failing if it does
2170                if (pkgSetting == null) {
2171                    continue;
2172                }
2173                boolean install = enableApps.contains(pName);
2174                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2175                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2176                            + " for system user");
2177                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2178                }
2179            }
2180        }
2181    }
2182
2183    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2184        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2185                Context.DISPLAY_SERVICE);
2186        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2187    }
2188
2189    public PackageManagerService(Context context, Installer installer,
2190            boolean factoryTest, boolean onlyCore) {
2191        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2192                SystemClock.uptimeMillis());
2193
2194        if (mSdkVersion <= 0) {
2195            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2196        }
2197
2198        mContext = context;
2199        mFactoryTest = factoryTest;
2200        mOnlyCore = onlyCore;
2201        mMetrics = new DisplayMetrics();
2202        mSettings = new Settings(mPackages);
2203        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2204                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2205        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215
2216        String separateProcesses = SystemProperties.get("debug.separate_processes");
2217        if (separateProcesses != null && separateProcesses.length() > 0) {
2218            if ("*".equals(separateProcesses)) {
2219                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2220                mSeparateProcesses = null;
2221                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2222            } else {
2223                mDefParseFlags = 0;
2224                mSeparateProcesses = separateProcesses.split(",");
2225                Slog.w(TAG, "Running with debug.separate_processes: "
2226                        + separateProcesses);
2227            }
2228        } else {
2229            mDefParseFlags = 0;
2230            mSeparateProcesses = null;
2231        }
2232
2233        mInstaller = installer;
2234        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2235                "*dexopt*");
2236        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2237
2238        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2239                FgThread.get().getLooper());
2240
2241        getDefaultDisplayMetrics(context, mMetrics);
2242
2243        SystemConfig systemConfig = SystemConfig.getInstance();
2244        mGlobalGids = systemConfig.getGlobalGids();
2245        mSystemPermissions = systemConfig.getSystemPermissions();
2246        mAvailableFeatures = systemConfig.getAvailableFeatures();
2247
2248        synchronized (mInstallLock) {
2249        // writer
2250        synchronized (mPackages) {
2251            mHandlerThread = new ServiceThread(TAG,
2252                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2253            mHandlerThread.start();
2254            mHandler = new PackageHandler(mHandlerThread.getLooper());
2255            mProcessLoggingHandler = new ProcessLoggingHandler();
2256            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2257
2258            File dataDir = Environment.getDataDirectory();
2259            mAppInstallDir = new File(dataDir, "app");
2260            mAppLib32InstallDir = new File(dataDir, "app-lib");
2261            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2262            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2263            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2264
2265            sUserManager = new UserManagerService(context, this, mPackages);
2266
2267            // Propagate permission configuration in to package manager.
2268            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2269                    = systemConfig.getPermissions();
2270            for (int i=0; i<permConfig.size(); i++) {
2271                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2272                BasePermission bp = mSettings.mPermissions.get(perm.name);
2273                if (bp == null) {
2274                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2275                    mSettings.mPermissions.put(perm.name, bp);
2276                }
2277                if (perm.gids != null) {
2278                    bp.setGids(perm.gids, perm.perUser);
2279                }
2280            }
2281
2282            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2283            for (int i=0; i<libConfig.size(); i++) {
2284                mSharedLibraries.put(libConfig.keyAt(i),
2285                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2286            }
2287
2288            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2289
2290            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2291
2292            String customResolverActivity = Resources.getSystem().getString(
2293                    R.string.config_customResolverActivity);
2294            if (TextUtils.isEmpty(customResolverActivity)) {
2295                customResolverActivity = null;
2296            } else {
2297                mCustomResolverComponentName = ComponentName.unflattenFromString(
2298                        customResolverActivity);
2299            }
2300
2301            long startTime = SystemClock.uptimeMillis();
2302
2303            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2304                    startTime);
2305
2306            // Set flag to monitor and not change apk file paths when
2307            // scanning install directories.
2308            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2309
2310            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2311            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2312
2313            if (bootClassPath == null) {
2314                Slog.w(TAG, "No BOOTCLASSPATH found!");
2315            }
2316
2317            if (systemServerClassPath == null) {
2318                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2319            }
2320
2321            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2322            final String[] dexCodeInstructionSets =
2323                    getDexCodeInstructionSets(
2324                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2325
2326            /**
2327             * Ensure all external libraries have had dexopt run on them.
2328             */
2329            if (mSharedLibraries.size() > 0) {
2330                // NOTE: For now, we're compiling these system "shared libraries"
2331                // (and framework jars) into all available architectures. It's possible
2332                // to compile them only when we come across an app that uses them (there's
2333                // already logic for that in scanPackageLI) but that adds some complexity.
2334                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2335                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2336                        final String lib = libEntry.path;
2337                        if (lib == null) {
2338                            continue;
2339                        }
2340
2341                        try {
2342                            // Shared libraries do not have profiles so we perform a full
2343                            // AOT compilation (if needed).
2344                            int dexoptNeeded = DexFile.getDexOptNeeded(
2345                                    lib, dexCodeInstructionSet,
2346                                    getCompilerFilterForReason(REASON_SHARED_APK),
2347                                    false /* newProfile */);
2348                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2349                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2350                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2351                                        getCompilerFilterForReason(REASON_SHARED_APK),
2352                                        StorageManager.UUID_PRIVATE_INTERNAL,
2353                                        SKIP_SHARED_LIBRARY_CHECK);
2354                            }
2355                        } catch (FileNotFoundException e) {
2356                            Slog.w(TAG, "Library not found: " + lib);
2357                        } catch (IOException | InstallerException e) {
2358                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2359                                    + e.getMessage());
2360                        }
2361                    }
2362                }
2363            }
2364
2365            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2366
2367            final VersionInfo ver = mSettings.getInternalVersion();
2368            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2369
2370            // when upgrading from pre-M, promote system app permissions from install to runtime
2371            mPromoteSystemApps =
2372                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2373
2374            // save off the names of pre-existing system packages prior to scanning; we don't
2375            // want to automatically grant runtime permissions for new system apps
2376            if (mPromoteSystemApps) {
2377                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2378                while (pkgSettingIter.hasNext()) {
2379                    PackageSetting ps = pkgSettingIter.next();
2380                    if (isSystemApp(ps)) {
2381                        mExistingSystemPackages.add(ps.name);
2382                    }
2383                }
2384            }
2385
2386            // When upgrading from pre-N, we need to handle package extraction like first boot,
2387            // as there is no profiling data available.
2388            mIsPreNUpgrade = !mSettings.isNWorkDone();
2389            mSettings.setNWorkDone();
2390
2391            // Collect vendor overlay packages.
2392            // (Do this before scanning any apps.)
2393            // For security and version matching reason, only consider
2394            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2395            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2396            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2397                    | PackageParser.PARSE_IS_SYSTEM
2398                    | PackageParser.PARSE_IS_SYSTEM_DIR
2399                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2400
2401            // Find base frameworks (resource packages without code).
2402            scanDirTracedLI(frameworkDir, mDefParseFlags
2403                    | PackageParser.PARSE_IS_SYSTEM
2404                    | PackageParser.PARSE_IS_SYSTEM_DIR
2405                    | PackageParser.PARSE_IS_PRIVILEGED,
2406                    scanFlags | SCAN_NO_DEX, 0);
2407
2408            // Collected privileged system packages.
2409            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2410            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2411                    | PackageParser.PARSE_IS_SYSTEM
2412                    | PackageParser.PARSE_IS_SYSTEM_DIR
2413                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2414
2415            // Collect ordinary system packages.
2416            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2417            scanDirTracedLI(systemAppDir, mDefParseFlags
2418                    | PackageParser.PARSE_IS_SYSTEM
2419                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2420
2421            // Collect all vendor packages.
2422            File vendorAppDir = new File("/vendor/app");
2423            try {
2424                vendorAppDir = vendorAppDir.getCanonicalFile();
2425            } catch (IOException e) {
2426                // failed to look up canonical path, continue with original one
2427            }
2428            scanDirTracedLI(vendorAppDir, mDefParseFlags
2429                    | PackageParser.PARSE_IS_SYSTEM
2430                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2431
2432            // Collect all OEM packages.
2433            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2434            scanDirTracedLI(oemAppDir, mDefParseFlags
2435                    | PackageParser.PARSE_IS_SYSTEM
2436                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2437
2438            // Prune any system packages that no longer exist.
2439            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2440            if (!mOnlyCore) {
2441                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2442                while (psit.hasNext()) {
2443                    PackageSetting ps = psit.next();
2444
2445                    /*
2446                     * If this is not a system app, it can't be a
2447                     * disable system app.
2448                     */
2449                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2450                        continue;
2451                    }
2452
2453                    /*
2454                     * If the package is scanned, it's not erased.
2455                     */
2456                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2457                    if (scannedPkg != null) {
2458                        /*
2459                         * If the system app is both scanned and in the
2460                         * disabled packages list, then it must have been
2461                         * added via OTA. Remove it from the currently
2462                         * scanned package so the previously user-installed
2463                         * application can be scanned.
2464                         */
2465                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2466                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2467                                    + ps.name + "; removing system app.  Last known codePath="
2468                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2469                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2470                                    + scannedPkg.mVersionCode);
2471                            removePackageLI(scannedPkg, true);
2472                            mExpectingBetter.put(ps.name, ps.codePath);
2473                        }
2474
2475                        continue;
2476                    }
2477
2478                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2479                        psit.remove();
2480                        logCriticalInfo(Log.WARN, "System package " + ps.name
2481                                + " no longer exists; it's data will be wiped");
2482                        // Actual deletion of code and data will be handled by later
2483                        // reconciliation step
2484                    } else {
2485                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2486                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2487                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2488                        }
2489                    }
2490                }
2491            }
2492
2493            //look for any incomplete package installations
2494            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2495            for (int i = 0; i < deletePkgsList.size(); i++) {
2496                // Actual deletion of code and data will be handled by later
2497                // reconciliation step
2498                final String packageName = deletePkgsList.get(i).name;
2499                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2500                synchronized (mPackages) {
2501                    mSettings.removePackageLPw(packageName);
2502                }
2503            }
2504
2505            //delete tmp files
2506            deleteTempPackageFiles();
2507
2508            // Remove any shared userIDs that have no associated packages
2509            mSettings.pruneSharedUsersLPw();
2510
2511            if (!mOnlyCore) {
2512                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2513                        SystemClock.uptimeMillis());
2514                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2515
2516                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2517                        | PackageParser.PARSE_FORWARD_LOCK,
2518                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2519
2520                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2521                        | PackageParser.PARSE_IS_EPHEMERAL,
2522                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2523
2524                /**
2525                 * Remove disable package settings for any updated system
2526                 * apps that were removed via an OTA. If they're not a
2527                 * previously-updated app, remove them completely.
2528                 * Otherwise, just revoke their system-level permissions.
2529                 */
2530                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2531                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2532                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2533
2534                    String msg;
2535                    if (deletedPkg == null) {
2536                        msg = "Updated system package " + deletedAppName
2537                                + " no longer exists; it's data will be wiped";
2538                        // Actual deletion of code and data will be handled by later
2539                        // reconciliation step
2540                    } else {
2541                        msg = "Updated system app + " + deletedAppName
2542                                + " no longer present; removing system privileges for "
2543                                + deletedAppName;
2544
2545                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2546
2547                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2548                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2549                    }
2550                    logCriticalInfo(Log.WARN, msg);
2551                }
2552
2553                /**
2554                 * Make sure all system apps that we expected to appear on
2555                 * the userdata partition actually showed up. If they never
2556                 * appeared, crawl back and revive the system version.
2557                 */
2558                for (int i = 0; i < mExpectingBetter.size(); i++) {
2559                    final String packageName = mExpectingBetter.keyAt(i);
2560                    if (!mPackages.containsKey(packageName)) {
2561                        final File scanFile = mExpectingBetter.valueAt(i);
2562
2563                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2564                                + " but never showed up; reverting to system");
2565
2566                        int reparseFlags = mDefParseFlags;
2567                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2568                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2569                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2570                                    | PackageParser.PARSE_IS_PRIVILEGED;
2571                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2572                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2573                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2574                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2575                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2576                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2577                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2578                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2579                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2580                        } else {
2581                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2582                            continue;
2583                        }
2584
2585                        mSettings.enableSystemPackageLPw(packageName);
2586
2587                        try {
2588                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2589                        } catch (PackageManagerException e) {
2590                            Slog.e(TAG, "Failed to parse original system package: "
2591                                    + e.getMessage());
2592                        }
2593                    }
2594                }
2595            }
2596            mExpectingBetter.clear();
2597
2598            // Resolve protected action filters. Only the setup wizard is allowed to
2599            // have a high priority filter for these actions.
2600            mSetupWizardPackage = getSetupWizardPackageName();
2601            if (mProtectedFilters.size() > 0) {
2602                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2603                    Slog.i(TAG, "No setup wizard;"
2604                        + " All protected intents capped to priority 0");
2605                }
2606                for (ActivityIntentInfo filter : mProtectedFilters) {
2607                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2608                        if (DEBUG_FILTERS) {
2609                            Slog.i(TAG, "Found setup wizard;"
2610                                + " allow priority " + filter.getPriority() + ";"
2611                                + " package: " + filter.activity.info.packageName
2612                                + " activity: " + filter.activity.className
2613                                + " priority: " + filter.getPriority());
2614                        }
2615                        // skip setup wizard; allow it to keep the high priority filter
2616                        continue;
2617                    }
2618                    Slog.w(TAG, "Protected action; cap priority to 0;"
2619                            + " package: " + filter.activity.info.packageName
2620                            + " activity: " + filter.activity.className
2621                            + " origPrio: " + filter.getPriority());
2622                    filter.setPriority(0);
2623                }
2624            }
2625            mDeferProtectedFilters = false;
2626            mProtectedFilters.clear();
2627
2628            // Now that we know all of the shared libraries, update all clients to have
2629            // the correct library paths.
2630            updateAllSharedLibrariesLPw();
2631
2632            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2633                // NOTE: We ignore potential failures here during a system scan (like
2634                // the rest of the commands above) because there's precious little we
2635                // can do about it. A settings error is reported, though.
2636                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2637                        false /* boot complete */);
2638            }
2639
2640            // Now that we know all the packages we are keeping,
2641            // read and update their last usage times.
2642            mPackageUsage.readLP();
2643
2644            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2645                    SystemClock.uptimeMillis());
2646            Slog.i(TAG, "Time to scan packages: "
2647                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2648                    + " seconds");
2649
2650            // If the platform SDK has changed since the last time we booted,
2651            // we need to re-grant app permission to catch any new ones that
2652            // appear.  This is really a hack, and means that apps can in some
2653            // cases get permissions that the user didn't initially explicitly
2654            // allow...  it would be nice to have some better way to handle
2655            // this situation.
2656            int updateFlags = UPDATE_PERMISSIONS_ALL;
2657            if (ver.sdkVersion != mSdkVersion) {
2658                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2659                        + mSdkVersion + "; regranting permissions for internal storage");
2660                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2661            }
2662            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2663            ver.sdkVersion = mSdkVersion;
2664
2665            // If this is the first boot or an update from pre-M, and it is a normal
2666            // boot, then we need to initialize the default preferred apps across
2667            // all defined users.
2668            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2669                for (UserInfo user : sUserManager.getUsers(true)) {
2670                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2671                    applyFactoryDefaultBrowserLPw(user.id);
2672                    primeDomainVerificationsLPw(user.id);
2673                }
2674            }
2675
2676            // Prepare storage for system user really early during boot,
2677            // since core system apps like SettingsProvider and SystemUI
2678            // can't wait for user to start
2679            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2680                    StorageManager.FLAG_STORAGE_DE);
2681
2682            // If this is first boot after an OTA, and a normal boot, then
2683            // we need to clear code cache directories.
2684            if (mIsUpgrade && !onlyCore) {
2685                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2686                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2687                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2688                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2689                        // No apps are running this early, so no need to freeze
2690                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2691                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2692                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2693                    }
2694                    clearAppProfilesLIF(ps.pkg);
2695                }
2696                ver.fingerprint = Build.FINGERPRINT;
2697            }
2698
2699            checkDefaultBrowser();
2700
2701            // clear only after permissions and other defaults have been updated
2702            mExistingSystemPackages.clear();
2703            mPromoteSystemApps = false;
2704
2705            // All the changes are done during package scanning.
2706            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2707
2708            // can downgrade to reader
2709            mSettings.writeLPr();
2710
2711            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2712                    SystemClock.uptimeMillis());
2713
2714            if (!mOnlyCore) {
2715                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2716                mRequiredInstallerPackage = getRequiredInstallerLPr();
2717                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2718                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2719                        mIntentFilterVerifierComponent);
2720                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2721                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2722                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2723                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2724            } else {
2725                mRequiredVerifierPackage = null;
2726                mRequiredInstallerPackage = null;
2727                mIntentFilterVerifierComponent = null;
2728                mIntentFilterVerifier = null;
2729                mServicesSystemSharedLibraryPackageName = null;
2730                mSharedSystemSharedLibraryPackageName = null;
2731            }
2732
2733            mInstallerService = new PackageInstallerService(context, this);
2734
2735            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2736            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2737            // both the installer and resolver must be present to enable ephemeral
2738            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2739                if (DEBUG_EPHEMERAL) {
2740                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2741                            + " installer:" + ephemeralInstallerComponent);
2742                }
2743                mEphemeralResolverComponent = ephemeralResolverComponent;
2744                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2745                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2746                mEphemeralResolverConnection =
2747                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2748            } else {
2749                if (DEBUG_EPHEMERAL) {
2750                    final String missingComponent =
2751                            (ephemeralResolverComponent == null)
2752                            ? (ephemeralInstallerComponent == null)
2753                                    ? "resolver and installer"
2754                                    : "resolver"
2755                            : "installer";
2756                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2757                }
2758                mEphemeralResolverComponent = null;
2759                mEphemeralInstallerComponent = null;
2760                mEphemeralResolverConnection = null;
2761            }
2762
2763            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2764        } // synchronized (mPackages)
2765        } // synchronized (mInstallLock)
2766
2767        // Now after opening every single application zip, make sure they
2768        // are all flushed.  Not really needed, but keeps things nice and
2769        // tidy.
2770        Runtime.getRuntime().gc();
2771
2772        // The initial scanning above does many calls into installd while
2773        // holding the mPackages lock, but we're mostly interested in yelling
2774        // once we have a booted system.
2775        mInstaller.setWarnIfHeld(mPackages);
2776
2777        // Expose private service for system components to use.
2778        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2779    }
2780
2781    @Override
2782    public boolean isFirstBoot() {
2783        return !mRestoredSettings;
2784    }
2785
2786    @Override
2787    public boolean isOnlyCoreApps() {
2788        return mOnlyCore;
2789    }
2790
2791    @Override
2792    public boolean isUpgrade() {
2793        return mIsUpgrade;
2794    }
2795
2796    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2797        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2798
2799        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2800                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2801                UserHandle.USER_SYSTEM);
2802        if (matches.size() == 1) {
2803            return matches.get(0).getComponentInfo().packageName;
2804        } else {
2805            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2806            return null;
2807        }
2808    }
2809
2810    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2811        synchronized (mPackages) {
2812            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2813            if (libraryEntry == null) {
2814                throw new IllegalStateException("Missing required shared library:" + libraryName);
2815            }
2816            return libraryEntry.apk;
2817        }
2818    }
2819
2820    private @NonNull String getRequiredInstallerLPr() {
2821        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2822        intent.addCategory(Intent.CATEGORY_DEFAULT);
2823        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2824
2825        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2826                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2827                UserHandle.USER_SYSTEM);
2828        if (matches.size() == 1) {
2829            ResolveInfo resolveInfo = matches.get(0);
2830            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2831                throw new RuntimeException("The installer must be a privileged app");
2832            }
2833            return matches.get(0).getComponentInfo().packageName;
2834        } else {
2835            throw new RuntimeException("There must be exactly one installer; found " + matches);
2836        }
2837    }
2838
2839    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2840        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2841
2842        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2843                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2844                UserHandle.USER_SYSTEM);
2845        ResolveInfo best = null;
2846        final int N = matches.size();
2847        for (int i = 0; i < N; i++) {
2848            final ResolveInfo cur = matches.get(i);
2849            final String packageName = cur.getComponentInfo().packageName;
2850            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2851                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2852                continue;
2853            }
2854
2855            if (best == null || cur.priority > best.priority) {
2856                best = cur;
2857            }
2858        }
2859
2860        if (best != null) {
2861            return best.getComponentInfo().getComponentName();
2862        } else {
2863            throw new RuntimeException("There must be at least one intent filter verifier");
2864        }
2865    }
2866
2867    private @Nullable ComponentName getEphemeralResolverLPr() {
2868        final String[] packageArray =
2869                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2870        if (packageArray.length == 0) {
2871            if (DEBUG_EPHEMERAL) {
2872                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2873            }
2874            return null;
2875        }
2876
2877        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2878        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2879                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2880                UserHandle.USER_SYSTEM);
2881
2882        final int N = resolvers.size();
2883        if (N == 0) {
2884            if (DEBUG_EPHEMERAL) {
2885                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2886            }
2887            return null;
2888        }
2889
2890        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2891        for (int i = 0; i < N; i++) {
2892            final ResolveInfo info = resolvers.get(i);
2893
2894            if (info.serviceInfo == null) {
2895                continue;
2896            }
2897
2898            final String packageName = info.serviceInfo.packageName;
2899            if (!possiblePackages.contains(packageName)) {
2900                if (DEBUG_EPHEMERAL) {
2901                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2902                            + " pkg: " + packageName + ", info:" + info);
2903                }
2904                continue;
2905            }
2906
2907            if (DEBUG_EPHEMERAL) {
2908                Slog.v(TAG, "Ephemeral resolver found;"
2909                        + " pkg: " + packageName + ", info:" + info);
2910            }
2911            return new ComponentName(packageName, info.serviceInfo.name);
2912        }
2913        if (DEBUG_EPHEMERAL) {
2914            Slog.v(TAG, "Ephemeral resolver NOT found");
2915        }
2916        return null;
2917    }
2918
2919    private @Nullable ComponentName getEphemeralInstallerLPr() {
2920        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2921        intent.addCategory(Intent.CATEGORY_DEFAULT);
2922        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2923
2924        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2925                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2926                UserHandle.USER_SYSTEM);
2927        if (matches.size() == 0) {
2928            return null;
2929        } else if (matches.size() == 1) {
2930            return matches.get(0).getComponentInfo().getComponentName();
2931        } else {
2932            throw new RuntimeException(
2933                    "There must be at most one ephemeral installer; found " + matches);
2934        }
2935    }
2936
2937    private void primeDomainVerificationsLPw(int userId) {
2938        if (DEBUG_DOMAIN_VERIFICATION) {
2939            Slog.d(TAG, "Priming domain verifications in user " + userId);
2940        }
2941
2942        SystemConfig systemConfig = SystemConfig.getInstance();
2943        ArraySet<String> packages = systemConfig.getLinkedApps();
2944        ArraySet<String> domains = new ArraySet<String>();
2945
2946        for (String packageName : packages) {
2947            PackageParser.Package pkg = mPackages.get(packageName);
2948            if (pkg != null) {
2949                if (!pkg.isSystemApp()) {
2950                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2951                    continue;
2952                }
2953
2954                domains.clear();
2955                for (PackageParser.Activity a : pkg.activities) {
2956                    for (ActivityIntentInfo filter : a.intents) {
2957                        if (hasValidDomains(filter)) {
2958                            domains.addAll(filter.getHostsList());
2959                        }
2960                    }
2961                }
2962
2963                if (domains.size() > 0) {
2964                    if (DEBUG_DOMAIN_VERIFICATION) {
2965                        Slog.v(TAG, "      + " + packageName);
2966                    }
2967                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2968                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2969                    // and then 'always' in the per-user state actually used for intent resolution.
2970                    final IntentFilterVerificationInfo ivi;
2971                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2972                            new ArrayList<String>(domains));
2973                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2974                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2975                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2976                } else {
2977                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2978                            + "' does not handle web links");
2979                }
2980            } else {
2981                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2982            }
2983        }
2984
2985        scheduleWritePackageRestrictionsLocked(userId);
2986        scheduleWriteSettingsLocked();
2987    }
2988
2989    private void applyFactoryDefaultBrowserLPw(int userId) {
2990        // The default browser app's package name is stored in a string resource,
2991        // with a product-specific overlay used for vendor customization.
2992        String browserPkg = mContext.getResources().getString(
2993                com.android.internal.R.string.default_browser);
2994        if (!TextUtils.isEmpty(browserPkg)) {
2995            // non-empty string => required to be a known package
2996            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2997            if (ps == null) {
2998                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2999                browserPkg = null;
3000            } else {
3001                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3002            }
3003        }
3004
3005        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3006        // default.  If there's more than one, just leave everything alone.
3007        if (browserPkg == null) {
3008            calculateDefaultBrowserLPw(userId);
3009        }
3010    }
3011
3012    private void calculateDefaultBrowserLPw(int userId) {
3013        List<String> allBrowsers = resolveAllBrowserApps(userId);
3014        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3015        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3016    }
3017
3018    private List<String> resolveAllBrowserApps(int userId) {
3019        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3020        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3021                PackageManager.MATCH_ALL, userId);
3022
3023        final int count = list.size();
3024        List<String> result = new ArrayList<String>(count);
3025        for (int i=0; i<count; i++) {
3026            ResolveInfo info = list.get(i);
3027            if (info.activityInfo == null
3028                    || !info.handleAllWebDataURI
3029                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3030                    || result.contains(info.activityInfo.packageName)) {
3031                continue;
3032            }
3033            result.add(info.activityInfo.packageName);
3034        }
3035
3036        return result;
3037    }
3038
3039    private boolean packageIsBrowser(String packageName, int userId) {
3040        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3041                PackageManager.MATCH_ALL, userId);
3042        final int N = list.size();
3043        for (int i = 0; i < N; i++) {
3044            ResolveInfo info = list.get(i);
3045            if (packageName.equals(info.activityInfo.packageName)) {
3046                return true;
3047            }
3048        }
3049        return false;
3050    }
3051
3052    private void checkDefaultBrowser() {
3053        final int myUserId = UserHandle.myUserId();
3054        final String packageName = getDefaultBrowserPackageName(myUserId);
3055        if (packageName != null) {
3056            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3057            if (info == null) {
3058                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3059                synchronized (mPackages) {
3060                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3061                }
3062            }
3063        }
3064    }
3065
3066    @Override
3067    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3068            throws RemoteException {
3069        try {
3070            return super.onTransact(code, data, reply, flags);
3071        } catch (RuntimeException e) {
3072            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3073                Slog.wtf(TAG, "Package Manager Crash", e);
3074            }
3075            throw e;
3076        }
3077    }
3078
3079    static int[] appendInts(int[] cur, int[] add) {
3080        if (add == null) return cur;
3081        if (cur == null) return add;
3082        final int N = add.length;
3083        for (int i=0; i<N; i++) {
3084            cur = appendInt(cur, add[i]);
3085        }
3086        return cur;
3087    }
3088
3089    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3090        if (!sUserManager.exists(userId)) return null;
3091        if (ps == null) {
3092            return null;
3093        }
3094        final PackageParser.Package p = ps.pkg;
3095        if (p == null) {
3096            return null;
3097        }
3098
3099        final PermissionsState permissionsState = ps.getPermissionsState();
3100
3101        final int[] gids = permissionsState.computeGids(userId);
3102        final Set<String> permissions = permissionsState.getPermissions(userId);
3103        final PackageUserState state = ps.readUserState(userId);
3104
3105        return PackageParser.generatePackageInfo(p, gids, flags,
3106                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3107    }
3108
3109    @Override
3110    public void checkPackageStartable(String packageName, int userId) {
3111        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3112
3113        synchronized (mPackages) {
3114            final PackageSetting ps = mSettings.mPackages.get(packageName);
3115            if (ps == null) {
3116                throw new SecurityException("Package " + packageName + " was not found!");
3117            }
3118
3119            if (!ps.getInstalled(userId)) {
3120                throw new SecurityException(
3121                        "Package " + packageName + " was not installed for user " + userId + "!");
3122            }
3123
3124            if (mSafeMode && !ps.isSystem()) {
3125                throw new SecurityException("Package " + packageName + " not a system app!");
3126            }
3127
3128            if (mFrozenPackages.contains(packageName)) {
3129                throw new SecurityException("Package " + packageName + " is currently frozen!");
3130            }
3131
3132            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3133                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3134                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3135            }
3136        }
3137    }
3138
3139    @Override
3140    public boolean isPackageAvailable(String packageName, int userId) {
3141        if (!sUserManager.exists(userId)) return false;
3142        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3143                false /* requireFullPermission */, false /* checkShell */, "is package available");
3144        synchronized (mPackages) {
3145            PackageParser.Package p = mPackages.get(packageName);
3146            if (p != null) {
3147                final PackageSetting ps = (PackageSetting) p.mExtras;
3148                if (ps != null) {
3149                    final PackageUserState state = ps.readUserState(userId);
3150                    if (state != null) {
3151                        return PackageParser.isAvailable(state);
3152                    }
3153                }
3154            }
3155        }
3156        return false;
3157    }
3158
3159    @Override
3160    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3161        if (!sUserManager.exists(userId)) return null;
3162        flags = updateFlagsForPackage(flags, userId, packageName);
3163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3164                false /* requireFullPermission */, false /* checkShell */, "get package info");
3165        // reader
3166        synchronized (mPackages) {
3167            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3168            PackageParser.Package p = null;
3169            if (matchFactoryOnly) {
3170                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3171                if (ps != null) {
3172                    return generatePackageInfo(ps, flags, userId);
3173                }
3174            }
3175            if (p == null) {
3176                p = mPackages.get(packageName);
3177                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3178                    return null;
3179                }
3180            }
3181            if (DEBUG_PACKAGE_INFO)
3182                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3183            if (p != null) {
3184                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3185            }
3186            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3187                final PackageSetting ps = mSettings.mPackages.get(packageName);
3188                return generatePackageInfo(ps, flags, userId);
3189            }
3190        }
3191        return null;
3192    }
3193
3194    @Override
3195    public String[] currentToCanonicalPackageNames(String[] names) {
3196        String[] out = new String[names.length];
3197        // reader
3198        synchronized (mPackages) {
3199            for (int i=names.length-1; i>=0; i--) {
3200                PackageSetting ps = mSettings.mPackages.get(names[i]);
3201                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3202            }
3203        }
3204        return out;
3205    }
3206
3207    @Override
3208    public String[] canonicalToCurrentPackageNames(String[] names) {
3209        String[] out = new String[names.length];
3210        // reader
3211        synchronized (mPackages) {
3212            for (int i=names.length-1; i>=0; i--) {
3213                String cur = mSettings.mRenamedPackages.get(names[i]);
3214                out[i] = cur != null ? cur : names[i];
3215            }
3216        }
3217        return out;
3218    }
3219
3220    @Override
3221    public int getPackageUid(String packageName, int flags, int userId) {
3222        if (!sUserManager.exists(userId)) return -1;
3223        flags = updateFlagsForPackage(flags, userId, packageName);
3224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3225                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3226
3227        // reader
3228        synchronized (mPackages) {
3229            final PackageParser.Package p = mPackages.get(packageName);
3230            if (p != null && p.isMatch(flags)) {
3231                return UserHandle.getUid(userId, p.applicationInfo.uid);
3232            }
3233            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3234                final PackageSetting ps = mSettings.mPackages.get(packageName);
3235                if (ps != null && ps.isMatch(flags)) {
3236                    return UserHandle.getUid(userId, ps.appId);
3237                }
3238            }
3239        }
3240
3241        return -1;
3242    }
3243
3244    @Override
3245    public int[] getPackageGids(String packageName, int flags, int userId) {
3246        if (!sUserManager.exists(userId)) return null;
3247        flags = updateFlagsForPackage(flags, userId, packageName);
3248        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3249                false /* requireFullPermission */, false /* checkShell */,
3250                "getPackageGids");
3251
3252        // reader
3253        synchronized (mPackages) {
3254            final PackageParser.Package p = mPackages.get(packageName);
3255            if (p != null && p.isMatch(flags)) {
3256                PackageSetting ps = (PackageSetting) p.mExtras;
3257                return ps.getPermissionsState().computeGids(userId);
3258            }
3259            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3260                final PackageSetting ps = mSettings.mPackages.get(packageName);
3261                if (ps != null && ps.isMatch(flags)) {
3262                    return ps.getPermissionsState().computeGids(userId);
3263                }
3264            }
3265        }
3266
3267        return null;
3268    }
3269
3270    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3271        if (bp.perm != null) {
3272            return PackageParser.generatePermissionInfo(bp.perm, flags);
3273        }
3274        PermissionInfo pi = new PermissionInfo();
3275        pi.name = bp.name;
3276        pi.packageName = bp.sourcePackage;
3277        pi.nonLocalizedLabel = bp.name;
3278        pi.protectionLevel = bp.protectionLevel;
3279        return pi;
3280    }
3281
3282    @Override
3283    public PermissionInfo getPermissionInfo(String name, int flags) {
3284        // reader
3285        synchronized (mPackages) {
3286            final BasePermission p = mSettings.mPermissions.get(name);
3287            if (p != null) {
3288                return generatePermissionInfo(p, flags);
3289            }
3290            return null;
3291        }
3292    }
3293
3294    @Override
3295    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3296            int flags) {
3297        // reader
3298        synchronized (mPackages) {
3299            if (group != null && !mPermissionGroups.containsKey(group)) {
3300                // This is thrown as NameNotFoundException
3301                return null;
3302            }
3303
3304            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3305            for (BasePermission p : mSettings.mPermissions.values()) {
3306                if (group == null) {
3307                    if (p.perm == null || p.perm.info.group == null) {
3308                        out.add(generatePermissionInfo(p, flags));
3309                    }
3310                } else {
3311                    if (p.perm != null && group.equals(p.perm.info.group)) {
3312                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3313                    }
3314                }
3315            }
3316            return new ParceledListSlice<>(out);
3317        }
3318    }
3319
3320    @Override
3321    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3322        // reader
3323        synchronized (mPackages) {
3324            return PackageParser.generatePermissionGroupInfo(
3325                    mPermissionGroups.get(name), flags);
3326        }
3327    }
3328
3329    @Override
3330    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3331        // reader
3332        synchronized (mPackages) {
3333            final int N = mPermissionGroups.size();
3334            ArrayList<PermissionGroupInfo> out
3335                    = new ArrayList<PermissionGroupInfo>(N);
3336            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3337                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3338            }
3339            return new ParceledListSlice<>(out);
3340        }
3341    }
3342
3343    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3344            int userId) {
3345        if (!sUserManager.exists(userId)) return null;
3346        PackageSetting ps = mSettings.mPackages.get(packageName);
3347        if (ps != null) {
3348            if (ps.pkg == null) {
3349                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3350                if (pInfo != null) {
3351                    return pInfo.applicationInfo;
3352                }
3353                return null;
3354            }
3355            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3356                    ps.readUserState(userId), userId);
3357        }
3358        return null;
3359    }
3360
3361    @Override
3362    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3363        if (!sUserManager.exists(userId)) return null;
3364        flags = updateFlagsForApplication(flags, userId, packageName);
3365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3366                false /* requireFullPermission */, false /* checkShell */, "get application info");
3367        // writer
3368        synchronized (mPackages) {
3369            PackageParser.Package p = mPackages.get(packageName);
3370            if (DEBUG_PACKAGE_INFO) Log.v(
3371                    TAG, "getApplicationInfo " + packageName
3372                    + ": " + p);
3373            if (p != null) {
3374                PackageSetting ps = mSettings.mPackages.get(packageName);
3375                if (ps == null) return null;
3376                // Note: isEnabledLP() does not apply here - always return info
3377                return PackageParser.generateApplicationInfo(
3378                        p, flags, ps.readUserState(userId), userId);
3379            }
3380            if ("android".equals(packageName)||"system".equals(packageName)) {
3381                return mAndroidApplication;
3382            }
3383            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3384                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3385            }
3386        }
3387        return null;
3388    }
3389
3390    @Override
3391    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3392            final IPackageDataObserver observer) {
3393        mContext.enforceCallingOrSelfPermission(
3394                android.Manifest.permission.CLEAR_APP_CACHE, null);
3395        // Queue up an async operation since clearing cache may take a little while.
3396        mHandler.post(new Runnable() {
3397            public void run() {
3398                mHandler.removeCallbacks(this);
3399                boolean success = true;
3400                synchronized (mInstallLock) {
3401                    try {
3402                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3403                    } catch (InstallerException e) {
3404                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3405                        success = false;
3406                    }
3407                }
3408                if (observer != null) {
3409                    try {
3410                        observer.onRemoveCompleted(null, success);
3411                    } catch (RemoteException e) {
3412                        Slog.w(TAG, "RemoveException when invoking call back");
3413                    }
3414                }
3415            }
3416        });
3417    }
3418
3419    @Override
3420    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3421            final IntentSender pi) {
3422        mContext.enforceCallingOrSelfPermission(
3423                android.Manifest.permission.CLEAR_APP_CACHE, null);
3424        // Queue up an async operation since clearing cache may take a little while.
3425        mHandler.post(new Runnable() {
3426            public void run() {
3427                mHandler.removeCallbacks(this);
3428                boolean success = true;
3429                synchronized (mInstallLock) {
3430                    try {
3431                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3432                    } catch (InstallerException e) {
3433                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3434                        success = false;
3435                    }
3436                }
3437                if(pi != null) {
3438                    try {
3439                        // Callback via pending intent
3440                        int code = success ? 1 : 0;
3441                        pi.sendIntent(null, code, null,
3442                                null, null);
3443                    } catch (SendIntentException e1) {
3444                        Slog.i(TAG, "Failed to send pending intent");
3445                    }
3446                }
3447            }
3448        });
3449    }
3450
3451    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3452        synchronized (mInstallLock) {
3453            try {
3454                mInstaller.freeCache(volumeUuid, freeStorageSize);
3455            } catch (InstallerException e) {
3456                throw new IOException("Failed to free enough space", e);
3457            }
3458        }
3459    }
3460
3461    /**
3462     * Update given flags based on encryption status of current user.
3463     */
3464    private int updateFlags(int flags, int userId) {
3465        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3466                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3467            // Caller expressed an explicit opinion about what encryption
3468            // aware/unaware components they want to see, so fall through and
3469            // give them what they want
3470        } else {
3471            // Caller expressed no opinion, so match based on user state
3472            if (StorageManager.isUserKeyUnlocked(userId)) {
3473                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3474            } else {
3475                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3476            }
3477        }
3478        return flags;
3479    }
3480
3481    /**
3482     * Update given flags when being used to request {@link PackageInfo}.
3483     */
3484    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3485        boolean triaged = true;
3486        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3487                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3488            // Caller is asking for component details, so they'd better be
3489            // asking for specific encryption matching behavior, or be triaged
3490            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3491                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3492                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3493                triaged = false;
3494            }
3495        }
3496        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3497                | PackageManager.MATCH_SYSTEM_ONLY
3498                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3499            triaged = false;
3500        }
3501        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3502            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3503                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3504        }
3505        return updateFlags(flags, userId);
3506    }
3507
3508    /**
3509     * Update given flags when being used to request {@link ApplicationInfo}.
3510     */
3511    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3512        return updateFlagsForPackage(flags, userId, cookie);
3513    }
3514
3515    /**
3516     * Update given flags when being used to request {@link ComponentInfo}.
3517     */
3518    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3519        if (cookie instanceof Intent) {
3520            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3521                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3522            }
3523        }
3524
3525        boolean triaged = true;
3526        // Caller is asking for component details, so they'd better be
3527        // asking for specific encryption matching behavior, or be triaged
3528        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3529                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3530                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3531            triaged = false;
3532        }
3533        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3534            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3535                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3536        }
3537
3538        return updateFlags(flags, userId);
3539    }
3540
3541    /**
3542     * Update given flags when being used to request {@link ResolveInfo}.
3543     */
3544    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3545        // Safe mode means we shouldn't match any third-party components
3546        if (mSafeMode) {
3547            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3548        }
3549
3550        return updateFlagsForComponent(flags, userId, cookie);
3551    }
3552
3553    @Override
3554    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3555        if (!sUserManager.exists(userId)) return null;
3556        flags = updateFlagsForComponent(flags, userId, component);
3557        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3558                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3559        synchronized (mPackages) {
3560            PackageParser.Activity a = mActivities.mActivities.get(component);
3561
3562            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3563            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3564                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3565                if (ps == null) return null;
3566                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3567                        userId);
3568            }
3569            if (mResolveComponentName.equals(component)) {
3570                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3571                        new PackageUserState(), userId);
3572            }
3573        }
3574        return null;
3575    }
3576
3577    @Override
3578    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3579            String resolvedType) {
3580        synchronized (mPackages) {
3581            if (component.equals(mResolveComponentName)) {
3582                // The resolver supports EVERYTHING!
3583                return true;
3584            }
3585            PackageParser.Activity a = mActivities.mActivities.get(component);
3586            if (a == null) {
3587                return false;
3588            }
3589            for (int i=0; i<a.intents.size(); i++) {
3590                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3591                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3592                    return true;
3593                }
3594            }
3595            return false;
3596        }
3597    }
3598
3599    @Override
3600    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3601        if (!sUserManager.exists(userId)) return null;
3602        flags = updateFlagsForComponent(flags, userId, component);
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3604                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3605        synchronized (mPackages) {
3606            PackageParser.Activity a = mReceivers.mActivities.get(component);
3607            if (DEBUG_PACKAGE_INFO) Log.v(
3608                TAG, "getReceiverInfo " + component + ": " + a);
3609            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3610                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3611                if (ps == null) return null;
3612                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3613                        userId);
3614            }
3615        }
3616        return null;
3617    }
3618
3619    @Override
3620    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3621        if (!sUserManager.exists(userId)) return null;
3622        flags = updateFlagsForComponent(flags, userId, component);
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3624                false /* requireFullPermission */, false /* checkShell */, "get service info");
3625        synchronized (mPackages) {
3626            PackageParser.Service s = mServices.mServices.get(component);
3627            if (DEBUG_PACKAGE_INFO) Log.v(
3628                TAG, "getServiceInfo " + component + ": " + s);
3629            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3630                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3631                if (ps == null) return null;
3632                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3633                        userId);
3634            }
3635        }
3636        return null;
3637    }
3638
3639    @Override
3640    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3641        if (!sUserManager.exists(userId)) return null;
3642        flags = updateFlagsForComponent(flags, userId, component);
3643        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3644                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3645        synchronized (mPackages) {
3646            PackageParser.Provider p = mProviders.mProviders.get(component);
3647            if (DEBUG_PACKAGE_INFO) Log.v(
3648                TAG, "getProviderInfo " + component + ": " + p);
3649            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3650                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3651                if (ps == null) return null;
3652                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3653                        userId);
3654            }
3655        }
3656        return null;
3657    }
3658
3659    @Override
3660    public String[] getSystemSharedLibraryNames() {
3661        Set<String> libSet;
3662        synchronized (mPackages) {
3663            libSet = mSharedLibraries.keySet();
3664            int size = libSet.size();
3665            if (size > 0) {
3666                String[] libs = new String[size];
3667                libSet.toArray(libs);
3668                return libs;
3669            }
3670        }
3671        return null;
3672    }
3673
3674    @Override
3675    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3676        synchronized (mPackages) {
3677            return mServicesSystemSharedLibraryPackageName;
3678        }
3679    }
3680
3681    @Override
3682    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3683        synchronized (mPackages) {
3684            return mSharedSystemSharedLibraryPackageName;
3685        }
3686    }
3687
3688    @Override
3689    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3690        synchronized (mPackages) {
3691            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3692
3693            final FeatureInfo fi = new FeatureInfo();
3694            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3695                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3696            res.add(fi);
3697
3698            return new ParceledListSlice<>(res);
3699        }
3700    }
3701
3702    @Override
3703    public boolean hasSystemFeature(String name, int version) {
3704        synchronized (mPackages) {
3705            final FeatureInfo feat = mAvailableFeatures.get(name);
3706            if (feat == null) {
3707                return false;
3708            } else {
3709                return feat.version >= version;
3710            }
3711        }
3712    }
3713
3714    @Override
3715    public int checkPermission(String permName, String pkgName, int userId) {
3716        if (!sUserManager.exists(userId)) {
3717            return PackageManager.PERMISSION_DENIED;
3718        }
3719
3720        synchronized (mPackages) {
3721            final PackageParser.Package p = mPackages.get(pkgName);
3722            if (p != null && p.mExtras != null) {
3723                final PackageSetting ps = (PackageSetting) p.mExtras;
3724                final PermissionsState permissionsState = ps.getPermissionsState();
3725                if (permissionsState.hasPermission(permName, userId)) {
3726                    return PackageManager.PERMISSION_GRANTED;
3727                }
3728                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3729                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3730                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3731                    return PackageManager.PERMISSION_GRANTED;
3732                }
3733            }
3734        }
3735
3736        return PackageManager.PERMISSION_DENIED;
3737    }
3738
3739    @Override
3740    public int checkUidPermission(String permName, int uid) {
3741        final int userId = UserHandle.getUserId(uid);
3742
3743        if (!sUserManager.exists(userId)) {
3744            return PackageManager.PERMISSION_DENIED;
3745        }
3746
3747        synchronized (mPackages) {
3748            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3749            if (obj != null) {
3750                final SettingBase ps = (SettingBase) obj;
3751                final PermissionsState permissionsState = ps.getPermissionsState();
3752                if (permissionsState.hasPermission(permName, userId)) {
3753                    return PackageManager.PERMISSION_GRANTED;
3754                }
3755                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3756                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3757                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3758                    return PackageManager.PERMISSION_GRANTED;
3759                }
3760            } else {
3761                ArraySet<String> perms = mSystemPermissions.get(uid);
3762                if (perms != null) {
3763                    if (perms.contains(permName)) {
3764                        return PackageManager.PERMISSION_GRANTED;
3765                    }
3766                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3767                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3768                        return PackageManager.PERMISSION_GRANTED;
3769                    }
3770                }
3771            }
3772        }
3773
3774        return PackageManager.PERMISSION_DENIED;
3775    }
3776
3777    @Override
3778    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3779        if (UserHandle.getCallingUserId() != userId) {
3780            mContext.enforceCallingPermission(
3781                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3782                    "isPermissionRevokedByPolicy for user " + userId);
3783        }
3784
3785        if (checkPermission(permission, packageName, userId)
3786                == PackageManager.PERMISSION_GRANTED) {
3787            return false;
3788        }
3789
3790        final long identity = Binder.clearCallingIdentity();
3791        try {
3792            final int flags = getPermissionFlags(permission, packageName, userId);
3793            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3794        } finally {
3795            Binder.restoreCallingIdentity(identity);
3796        }
3797    }
3798
3799    @Override
3800    public String getPermissionControllerPackageName() {
3801        synchronized (mPackages) {
3802            return mRequiredInstallerPackage;
3803        }
3804    }
3805
3806    /**
3807     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3808     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3809     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3810     * @param message the message to log on security exception
3811     */
3812    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3813            boolean checkShell, String message) {
3814        if (userId < 0) {
3815            throw new IllegalArgumentException("Invalid userId " + userId);
3816        }
3817        if (checkShell) {
3818            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3819        }
3820        if (userId == UserHandle.getUserId(callingUid)) return;
3821        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3822            if (requireFullPermission) {
3823                mContext.enforceCallingOrSelfPermission(
3824                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3825            } else {
3826                try {
3827                    mContext.enforceCallingOrSelfPermission(
3828                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3829                } catch (SecurityException se) {
3830                    mContext.enforceCallingOrSelfPermission(
3831                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3832                }
3833            }
3834        }
3835    }
3836
3837    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3838        if (callingUid == Process.SHELL_UID) {
3839            if (userHandle >= 0
3840                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3841                throw new SecurityException("Shell does not have permission to access user "
3842                        + userHandle);
3843            } else if (userHandle < 0) {
3844                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3845                        + Debug.getCallers(3));
3846            }
3847        }
3848    }
3849
3850    private BasePermission findPermissionTreeLP(String permName) {
3851        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3852            if (permName.startsWith(bp.name) &&
3853                    permName.length() > bp.name.length() &&
3854                    permName.charAt(bp.name.length()) == '.') {
3855                return bp;
3856            }
3857        }
3858        return null;
3859    }
3860
3861    private BasePermission checkPermissionTreeLP(String permName) {
3862        if (permName != null) {
3863            BasePermission bp = findPermissionTreeLP(permName);
3864            if (bp != null) {
3865                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3866                    return bp;
3867                }
3868                throw new SecurityException("Calling uid "
3869                        + Binder.getCallingUid()
3870                        + " is not allowed to add to permission tree "
3871                        + bp.name + " owned by uid " + bp.uid);
3872            }
3873        }
3874        throw new SecurityException("No permission tree found for " + permName);
3875    }
3876
3877    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3878        if (s1 == null) {
3879            return s2 == null;
3880        }
3881        if (s2 == null) {
3882            return false;
3883        }
3884        if (s1.getClass() != s2.getClass()) {
3885            return false;
3886        }
3887        return s1.equals(s2);
3888    }
3889
3890    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3891        if (pi1.icon != pi2.icon) return false;
3892        if (pi1.logo != pi2.logo) return false;
3893        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3894        if (!compareStrings(pi1.name, pi2.name)) return false;
3895        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3896        // We'll take care of setting this one.
3897        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3898        // These are not currently stored in settings.
3899        //if (!compareStrings(pi1.group, pi2.group)) return false;
3900        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3901        //if (pi1.labelRes != pi2.labelRes) return false;
3902        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3903        return true;
3904    }
3905
3906    int permissionInfoFootprint(PermissionInfo info) {
3907        int size = info.name.length();
3908        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3909        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3910        return size;
3911    }
3912
3913    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3914        int size = 0;
3915        for (BasePermission perm : mSettings.mPermissions.values()) {
3916            if (perm.uid == tree.uid) {
3917                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3918            }
3919        }
3920        return size;
3921    }
3922
3923    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3924        // We calculate the max size of permissions defined by this uid and throw
3925        // if that plus the size of 'info' would exceed our stated maximum.
3926        if (tree.uid != Process.SYSTEM_UID) {
3927            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3928            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3929                throw new SecurityException("Permission tree size cap exceeded");
3930            }
3931        }
3932    }
3933
3934    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3935        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3936            throw new SecurityException("Label must be specified in permission");
3937        }
3938        BasePermission tree = checkPermissionTreeLP(info.name);
3939        BasePermission bp = mSettings.mPermissions.get(info.name);
3940        boolean added = bp == null;
3941        boolean changed = true;
3942        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3943        if (added) {
3944            enforcePermissionCapLocked(info, tree);
3945            bp = new BasePermission(info.name, tree.sourcePackage,
3946                    BasePermission.TYPE_DYNAMIC);
3947        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3948            throw new SecurityException(
3949                    "Not allowed to modify non-dynamic permission "
3950                    + info.name);
3951        } else {
3952            if (bp.protectionLevel == fixedLevel
3953                    && bp.perm.owner.equals(tree.perm.owner)
3954                    && bp.uid == tree.uid
3955                    && comparePermissionInfos(bp.perm.info, info)) {
3956                changed = false;
3957            }
3958        }
3959        bp.protectionLevel = fixedLevel;
3960        info = new PermissionInfo(info);
3961        info.protectionLevel = fixedLevel;
3962        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3963        bp.perm.info.packageName = tree.perm.info.packageName;
3964        bp.uid = tree.uid;
3965        if (added) {
3966            mSettings.mPermissions.put(info.name, bp);
3967        }
3968        if (changed) {
3969            if (!async) {
3970                mSettings.writeLPr();
3971            } else {
3972                scheduleWriteSettingsLocked();
3973            }
3974        }
3975        return added;
3976    }
3977
3978    @Override
3979    public boolean addPermission(PermissionInfo info) {
3980        synchronized (mPackages) {
3981            return addPermissionLocked(info, false);
3982        }
3983    }
3984
3985    @Override
3986    public boolean addPermissionAsync(PermissionInfo info) {
3987        synchronized (mPackages) {
3988            return addPermissionLocked(info, true);
3989        }
3990    }
3991
3992    @Override
3993    public void removePermission(String name) {
3994        synchronized (mPackages) {
3995            checkPermissionTreeLP(name);
3996            BasePermission bp = mSettings.mPermissions.get(name);
3997            if (bp != null) {
3998                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3999                    throw new SecurityException(
4000                            "Not allowed to modify non-dynamic permission "
4001                            + name);
4002                }
4003                mSettings.mPermissions.remove(name);
4004                mSettings.writeLPr();
4005            }
4006        }
4007    }
4008
4009    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4010            BasePermission bp) {
4011        int index = pkg.requestedPermissions.indexOf(bp.name);
4012        if (index == -1) {
4013            throw new SecurityException("Package " + pkg.packageName
4014                    + " has not requested permission " + bp.name);
4015        }
4016        if (!bp.isRuntime() && !bp.isDevelopment()) {
4017            throw new SecurityException("Permission " + bp.name
4018                    + " is not a changeable permission type");
4019        }
4020    }
4021
4022    @Override
4023    public void grantRuntimePermission(String packageName, String name, final int userId) {
4024        if (!sUserManager.exists(userId)) {
4025            Log.e(TAG, "No such user:" + userId);
4026            return;
4027        }
4028
4029        mContext.enforceCallingOrSelfPermission(
4030                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4031                "grantRuntimePermission");
4032
4033        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4034                true /* requireFullPermission */, true /* checkShell */,
4035                "grantRuntimePermission");
4036
4037        final int uid;
4038        final SettingBase sb;
4039
4040        synchronized (mPackages) {
4041            final PackageParser.Package pkg = mPackages.get(packageName);
4042            if (pkg == null) {
4043                throw new IllegalArgumentException("Unknown package: " + packageName);
4044            }
4045
4046            final BasePermission bp = mSettings.mPermissions.get(name);
4047            if (bp == null) {
4048                throw new IllegalArgumentException("Unknown permission: " + name);
4049            }
4050
4051            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4052
4053            // If a permission review is required for legacy apps we represent
4054            // their permissions as always granted runtime ones since we need
4055            // to keep the review required permission flag per user while an
4056            // install permission's state is shared across all users.
4057            if (Build.PERMISSIONS_REVIEW_REQUIRED
4058                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4059                    && bp.isRuntime()) {
4060                return;
4061            }
4062
4063            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4064            sb = (SettingBase) pkg.mExtras;
4065            if (sb == null) {
4066                throw new IllegalArgumentException("Unknown package: " + packageName);
4067            }
4068
4069            final PermissionsState permissionsState = sb.getPermissionsState();
4070
4071            final int flags = permissionsState.getPermissionFlags(name, userId);
4072            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4073                throw new SecurityException("Cannot grant system fixed permission "
4074                        + name + " for package " + packageName);
4075            }
4076
4077            if (bp.isDevelopment()) {
4078                // Development permissions must be handled specially, since they are not
4079                // normal runtime permissions.  For now they apply to all users.
4080                if (permissionsState.grantInstallPermission(bp) !=
4081                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4082                    scheduleWriteSettingsLocked();
4083                }
4084                return;
4085            }
4086
4087            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4088                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4089                return;
4090            }
4091
4092            final int result = permissionsState.grantRuntimePermission(bp, userId);
4093            switch (result) {
4094                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4095                    return;
4096                }
4097
4098                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4099                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4100                    mHandler.post(new Runnable() {
4101                        @Override
4102                        public void run() {
4103                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4104                        }
4105                    });
4106                }
4107                break;
4108            }
4109
4110            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4111
4112            // Not critical if that is lost - app has to request again.
4113            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4114        }
4115
4116        // Only need to do this if user is initialized. Otherwise it's a new user
4117        // and there are no processes running as the user yet and there's no need
4118        // to make an expensive call to remount processes for the changed permissions.
4119        if (READ_EXTERNAL_STORAGE.equals(name)
4120                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4121            final long token = Binder.clearCallingIdentity();
4122            try {
4123                if (sUserManager.isInitialized(userId)) {
4124                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4125                            MountServiceInternal.class);
4126                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4127                }
4128            } finally {
4129                Binder.restoreCallingIdentity(token);
4130            }
4131        }
4132    }
4133
4134    @Override
4135    public void revokeRuntimePermission(String packageName, String name, int userId) {
4136        if (!sUserManager.exists(userId)) {
4137            Log.e(TAG, "No such user:" + userId);
4138            return;
4139        }
4140
4141        mContext.enforceCallingOrSelfPermission(
4142                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4143                "revokeRuntimePermission");
4144
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                true /* requireFullPermission */, true /* checkShell */,
4147                "revokeRuntimePermission");
4148
4149        final int appId;
4150
4151        synchronized (mPackages) {
4152            final PackageParser.Package pkg = mPackages.get(packageName);
4153            if (pkg == null) {
4154                throw new IllegalArgumentException("Unknown package: " + packageName);
4155            }
4156
4157            final BasePermission bp = mSettings.mPermissions.get(name);
4158            if (bp == null) {
4159                throw new IllegalArgumentException("Unknown permission: " + name);
4160            }
4161
4162            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4163
4164            // If a permission review is required for legacy apps we represent
4165            // their permissions as always granted runtime ones since we need
4166            // to keep the review required permission flag per user while an
4167            // install permission's state is shared across all users.
4168            if (Build.PERMISSIONS_REVIEW_REQUIRED
4169                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4170                    && bp.isRuntime()) {
4171                return;
4172            }
4173
4174            SettingBase sb = (SettingBase) pkg.mExtras;
4175            if (sb == null) {
4176                throw new IllegalArgumentException("Unknown package: " + packageName);
4177            }
4178
4179            final PermissionsState permissionsState = sb.getPermissionsState();
4180
4181            final int flags = permissionsState.getPermissionFlags(name, userId);
4182            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4183                throw new SecurityException("Cannot revoke system fixed permission "
4184                        + name + " for package " + packageName);
4185            }
4186
4187            if (bp.isDevelopment()) {
4188                // Development permissions must be handled specially, since they are not
4189                // normal runtime permissions.  For now they apply to all users.
4190                if (permissionsState.revokeInstallPermission(bp) !=
4191                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4192                    scheduleWriteSettingsLocked();
4193                }
4194                return;
4195            }
4196
4197            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4198                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4199                return;
4200            }
4201
4202            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4203
4204            // Critical, after this call app should never have the permission.
4205            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4206
4207            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4208        }
4209
4210        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4211    }
4212
4213    @Override
4214    public void resetRuntimePermissions() {
4215        mContext.enforceCallingOrSelfPermission(
4216                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4217                "revokeRuntimePermission");
4218
4219        int callingUid = Binder.getCallingUid();
4220        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4221            mContext.enforceCallingOrSelfPermission(
4222                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4223                    "resetRuntimePermissions");
4224        }
4225
4226        synchronized (mPackages) {
4227            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4228            for (int userId : UserManagerService.getInstance().getUserIds()) {
4229                final int packageCount = mPackages.size();
4230                for (int i = 0; i < packageCount; i++) {
4231                    PackageParser.Package pkg = mPackages.valueAt(i);
4232                    if (!(pkg.mExtras instanceof PackageSetting)) {
4233                        continue;
4234                    }
4235                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4236                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4237                }
4238            }
4239        }
4240    }
4241
4242    @Override
4243    public int getPermissionFlags(String name, String packageName, int userId) {
4244        if (!sUserManager.exists(userId)) {
4245            return 0;
4246        }
4247
4248        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4249
4250        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4251                true /* requireFullPermission */, false /* checkShell */,
4252                "getPermissionFlags");
4253
4254        synchronized (mPackages) {
4255            final PackageParser.Package pkg = mPackages.get(packageName);
4256            if (pkg == null) {
4257                throw new IllegalArgumentException("Unknown package: " + packageName);
4258            }
4259
4260            final BasePermission bp = mSettings.mPermissions.get(name);
4261            if (bp == null) {
4262                throw new IllegalArgumentException("Unknown permission: " + name);
4263            }
4264
4265            SettingBase sb = (SettingBase) pkg.mExtras;
4266            if (sb == null) {
4267                throw new IllegalArgumentException("Unknown package: " + packageName);
4268            }
4269
4270            PermissionsState permissionsState = sb.getPermissionsState();
4271            return permissionsState.getPermissionFlags(name, userId);
4272        }
4273    }
4274
4275    @Override
4276    public void updatePermissionFlags(String name, String packageName, int flagMask,
4277            int flagValues, int userId) {
4278        if (!sUserManager.exists(userId)) {
4279            return;
4280        }
4281
4282        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4283
4284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4285                true /* requireFullPermission */, true /* checkShell */,
4286                "updatePermissionFlags");
4287
4288        // Only the system can change these flags and nothing else.
4289        if (getCallingUid() != Process.SYSTEM_UID) {
4290            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4291            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4292            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4293            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4294            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4295        }
4296
4297        synchronized (mPackages) {
4298            final PackageParser.Package pkg = mPackages.get(packageName);
4299            if (pkg == null) {
4300                throw new IllegalArgumentException("Unknown package: " + packageName);
4301            }
4302
4303            final BasePermission bp = mSettings.mPermissions.get(name);
4304            if (bp == null) {
4305                throw new IllegalArgumentException("Unknown permission: " + name);
4306            }
4307
4308            SettingBase sb = (SettingBase) pkg.mExtras;
4309            if (sb == null) {
4310                throw new IllegalArgumentException("Unknown package: " + packageName);
4311            }
4312
4313            PermissionsState permissionsState = sb.getPermissionsState();
4314
4315            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4316
4317            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4318                // Install and runtime permissions are stored in different places,
4319                // so figure out what permission changed and persist the change.
4320                if (permissionsState.getInstallPermissionState(name) != null) {
4321                    scheduleWriteSettingsLocked();
4322                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4323                        || hadState) {
4324                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4325                }
4326            }
4327        }
4328    }
4329
4330    /**
4331     * Update the permission flags for all packages and runtime permissions of a user in order
4332     * to allow device or profile owner to remove POLICY_FIXED.
4333     */
4334    @Override
4335    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4336        if (!sUserManager.exists(userId)) {
4337            return;
4338        }
4339
4340        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4341
4342        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4343                true /* requireFullPermission */, true /* checkShell */,
4344                "updatePermissionFlagsForAllApps");
4345
4346        // Only the system can change system fixed flags.
4347        if (getCallingUid() != Process.SYSTEM_UID) {
4348            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4349            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4350        }
4351
4352        synchronized (mPackages) {
4353            boolean changed = false;
4354            final int packageCount = mPackages.size();
4355            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4356                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4357                SettingBase sb = (SettingBase) pkg.mExtras;
4358                if (sb == null) {
4359                    continue;
4360                }
4361                PermissionsState permissionsState = sb.getPermissionsState();
4362                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4363                        userId, flagMask, flagValues);
4364            }
4365            if (changed) {
4366                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4367            }
4368        }
4369    }
4370
4371    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4372        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4373                != PackageManager.PERMISSION_GRANTED
4374            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4375                != PackageManager.PERMISSION_GRANTED) {
4376            throw new SecurityException(message + " requires "
4377                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4378                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4379        }
4380    }
4381
4382    @Override
4383    public boolean shouldShowRequestPermissionRationale(String permissionName,
4384            String packageName, int userId) {
4385        if (UserHandle.getCallingUserId() != userId) {
4386            mContext.enforceCallingPermission(
4387                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4388                    "canShowRequestPermissionRationale for user " + userId);
4389        }
4390
4391        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4392        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4393            return false;
4394        }
4395
4396        if (checkPermission(permissionName, packageName, userId)
4397                == PackageManager.PERMISSION_GRANTED) {
4398            return false;
4399        }
4400
4401        final int flags;
4402
4403        final long identity = Binder.clearCallingIdentity();
4404        try {
4405            flags = getPermissionFlags(permissionName,
4406                    packageName, userId);
4407        } finally {
4408            Binder.restoreCallingIdentity(identity);
4409        }
4410
4411        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4412                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4413                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4414
4415        if ((flags & fixedFlags) != 0) {
4416            return false;
4417        }
4418
4419        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4420    }
4421
4422    @Override
4423    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4424        mContext.enforceCallingOrSelfPermission(
4425                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4426                "addOnPermissionsChangeListener");
4427
4428        synchronized (mPackages) {
4429            mOnPermissionChangeListeners.addListenerLocked(listener);
4430        }
4431    }
4432
4433    @Override
4434    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4435        synchronized (mPackages) {
4436            mOnPermissionChangeListeners.removeListenerLocked(listener);
4437        }
4438    }
4439
4440    @Override
4441    public boolean isProtectedBroadcast(String actionName) {
4442        synchronized (mPackages) {
4443            if (mProtectedBroadcasts.contains(actionName)) {
4444                return true;
4445            } else if (actionName != null) {
4446                // TODO: remove these terrible hacks
4447                if (actionName.startsWith("android.net.netmon.lingerExpired")
4448                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4449                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4450                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4451                    return true;
4452                }
4453            }
4454        }
4455        return false;
4456    }
4457
4458    @Override
4459    public int checkSignatures(String pkg1, String pkg2) {
4460        synchronized (mPackages) {
4461            final PackageParser.Package p1 = mPackages.get(pkg1);
4462            final PackageParser.Package p2 = mPackages.get(pkg2);
4463            if (p1 == null || p1.mExtras == null
4464                    || p2 == null || p2.mExtras == null) {
4465                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4466            }
4467            return compareSignatures(p1.mSignatures, p2.mSignatures);
4468        }
4469    }
4470
4471    @Override
4472    public int checkUidSignatures(int uid1, int uid2) {
4473        // Map to base uids.
4474        uid1 = UserHandle.getAppId(uid1);
4475        uid2 = UserHandle.getAppId(uid2);
4476        // reader
4477        synchronized (mPackages) {
4478            Signature[] s1;
4479            Signature[] s2;
4480            Object obj = mSettings.getUserIdLPr(uid1);
4481            if (obj != null) {
4482                if (obj instanceof SharedUserSetting) {
4483                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4484                } else if (obj instanceof PackageSetting) {
4485                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4486                } else {
4487                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4488                }
4489            } else {
4490                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4491            }
4492            obj = mSettings.getUserIdLPr(uid2);
4493            if (obj != null) {
4494                if (obj instanceof SharedUserSetting) {
4495                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4496                } else if (obj instanceof PackageSetting) {
4497                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4498                } else {
4499                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4500                }
4501            } else {
4502                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503            }
4504            return compareSignatures(s1, s2);
4505        }
4506    }
4507
4508    /**
4509     * This method should typically only be used when granting or revoking
4510     * permissions, since the app may immediately restart after this call.
4511     * <p>
4512     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4513     * guard your work against the app being relaunched.
4514     */
4515    private void killUid(int appId, int userId, String reason) {
4516        final long identity = Binder.clearCallingIdentity();
4517        try {
4518            IActivityManager am = ActivityManagerNative.getDefault();
4519            if (am != null) {
4520                try {
4521                    am.killUid(appId, userId, reason);
4522                } catch (RemoteException e) {
4523                    /* ignore - same process */
4524                }
4525            }
4526        } finally {
4527            Binder.restoreCallingIdentity(identity);
4528        }
4529    }
4530
4531    /**
4532     * Compares two sets of signatures. Returns:
4533     * <br />
4534     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4535     * <br />
4536     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4537     * <br />
4538     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4539     * <br />
4540     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4541     * <br />
4542     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4543     */
4544    static int compareSignatures(Signature[] s1, Signature[] s2) {
4545        if (s1 == null) {
4546            return s2 == null
4547                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4548                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4549        }
4550
4551        if (s2 == null) {
4552            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4553        }
4554
4555        if (s1.length != s2.length) {
4556            return PackageManager.SIGNATURE_NO_MATCH;
4557        }
4558
4559        // Since both signature sets are of size 1, we can compare without HashSets.
4560        if (s1.length == 1) {
4561            return s1[0].equals(s2[0]) ?
4562                    PackageManager.SIGNATURE_MATCH :
4563                    PackageManager.SIGNATURE_NO_MATCH;
4564        }
4565
4566        ArraySet<Signature> set1 = new ArraySet<Signature>();
4567        for (Signature sig : s1) {
4568            set1.add(sig);
4569        }
4570        ArraySet<Signature> set2 = new ArraySet<Signature>();
4571        for (Signature sig : s2) {
4572            set2.add(sig);
4573        }
4574        // Make sure s2 contains all signatures in s1.
4575        if (set1.equals(set2)) {
4576            return PackageManager.SIGNATURE_MATCH;
4577        }
4578        return PackageManager.SIGNATURE_NO_MATCH;
4579    }
4580
4581    /**
4582     * If the database version for this type of package (internal storage or
4583     * external storage) is less than the version where package signatures
4584     * were updated, return true.
4585     */
4586    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4587        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4588        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4589    }
4590
4591    /**
4592     * Used for backward compatibility to make sure any packages with
4593     * certificate chains get upgraded to the new style. {@code existingSigs}
4594     * will be in the old format (since they were stored on disk from before the
4595     * system upgrade) and {@code scannedSigs} will be in the newer format.
4596     */
4597    private int compareSignaturesCompat(PackageSignatures existingSigs,
4598            PackageParser.Package scannedPkg) {
4599        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4600            return PackageManager.SIGNATURE_NO_MATCH;
4601        }
4602
4603        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4604        for (Signature sig : existingSigs.mSignatures) {
4605            existingSet.add(sig);
4606        }
4607        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4608        for (Signature sig : scannedPkg.mSignatures) {
4609            try {
4610                Signature[] chainSignatures = sig.getChainSignatures();
4611                for (Signature chainSig : chainSignatures) {
4612                    scannedCompatSet.add(chainSig);
4613                }
4614            } catch (CertificateEncodingException e) {
4615                scannedCompatSet.add(sig);
4616            }
4617        }
4618        /*
4619         * Make sure the expanded scanned set contains all signatures in the
4620         * existing one.
4621         */
4622        if (scannedCompatSet.equals(existingSet)) {
4623            // Migrate the old signatures to the new scheme.
4624            existingSigs.assignSignatures(scannedPkg.mSignatures);
4625            // The new KeySets will be re-added later in the scanning process.
4626            synchronized (mPackages) {
4627                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4628            }
4629            return PackageManager.SIGNATURE_MATCH;
4630        }
4631        return PackageManager.SIGNATURE_NO_MATCH;
4632    }
4633
4634    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4635        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4636        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4637    }
4638
4639    private int compareSignaturesRecover(PackageSignatures existingSigs,
4640            PackageParser.Package scannedPkg) {
4641        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4642            return PackageManager.SIGNATURE_NO_MATCH;
4643        }
4644
4645        String msg = null;
4646        try {
4647            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4648                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4649                        + scannedPkg.packageName);
4650                return PackageManager.SIGNATURE_MATCH;
4651            }
4652        } catch (CertificateException e) {
4653            msg = e.getMessage();
4654        }
4655
4656        logCriticalInfo(Log.INFO,
4657                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4658        return PackageManager.SIGNATURE_NO_MATCH;
4659    }
4660
4661    @Override
4662    public List<String> getAllPackages() {
4663        synchronized (mPackages) {
4664            return new ArrayList<String>(mPackages.keySet());
4665        }
4666    }
4667
4668    @Override
4669    public String[] getPackagesForUid(int uid) {
4670        uid = UserHandle.getAppId(uid);
4671        // reader
4672        synchronized (mPackages) {
4673            Object obj = mSettings.getUserIdLPr(uid);
4674            if (obj instanceof SharedUserSetting) {
4675                final SharedUserSetting sus = (SharedUserSetting) obj;
4676                final int N = sus.packages.size();
4677                final String[] res = new String[N];
4678                final Iterator<PackageSetting> it = sus.packages.iterator();
4679                int i = 0;
4680                while (it.hasNext()) {
4681                    res[i++] = it.next().name;
4682                }
4683                return res;
4684            } else if (obj instanceof PackageSetting) {
4685                final PackageSetting ps = (PackageSetting) obj;
4686                return new String[] { ps.name };
4687            }
4688        }
4689        return null;
4690    }
4691
4692    @Override
4693    public String getNameForUid(int uid) {
4694        // reader
4695        synchronized (mPackages) {
4696            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4697            if (obj instanceof SharedUserSetting) {
4698                final SharedUserSetting sus = (SharedUserSetting) obj;
4699                return sus.name + ":" + sus.userId;
4700            } else if (obj instanceof PackageSetting) {
4701                final PackageSetting ps = (PackageSetting) obj;
4702                return ps.name;
4703            }
4704        }
4705        return null;
4706    }
4707
4708    @Override
4709    public int getUidForSharedUser(String sharedUserName) {
4710        if(sharedUserName == null) {
4711            return -1;
4712        }
4713        // reader
4714        synchronized (mPackages) {
4715            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4716            if (suid == null) {
4717                return -1;
4718            }
4719            return suid.userId;
4720        }
4721    }
4722
4723    @Override
4724    public int getFlagsForUid(int uid) {
4725        synchronized (mPackages) {
4726            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4727            if (obj instanceof SharedUserSetting) {
4728                final SharedUserSetting sus = (SharedUserSetting) obj;
4729                return sus.pkgFlags;
4730            } else if (obj instanceof PackageSetting) {
4731                final PackageSetting ps = (PackageSetting) obj;
4732                return ps.pkgFlags;
4733            }
4734        }
4735        return 0;
4736    }
4737
4738    @Override
4739    public int getPrivateFlagsForUid(int uid) {
4740        synchronized (mPackages) {
4741            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4742            if (obj instanceof SharedUserSetting) {
4743                final SharedUserSetting sus = (SharedUserSetting) obj;
4744                return sus.pkgPrivateFlags;
4745            } else if (obj instanceof PackageSetting) {
4746                final PackageSetting ps = (PackageSetting) obj;
4747                return ps.pkgPrivateFlags;
4748            }
4749        }
4750        return 0;
4751    }
4752
4753    @Override
4754    public boolean isUidPrivileged(int uid) {
4755        uid = UserHandle.getAppId(uid);
4756        // reader
4757        synchronized (mPackages) {
4758            Object obj = mSettings.getUserIdLPr(uid);
4759            if (obj instanceof SharedUserSetting) {
4760                final SharedUserSetting sus = (SharedUserSetting) obj;
4761                final Iterator<PackageSetting> it = sus.packages.iterator();
4762                while (it.hasNext()) {
4763                    if (it.next().isPrivileged()) {
4764                        return true;
4765                    }
4766                }
4767            } else if (obj instanceof PackageSetting) {
4768                final PackageSetting ps = (PackageSetting) obj;
4769                return ps.isPrivileged();
4770            }
4771        }
4772        return false;
4773    }
4774
4775    @Override
4776    public String[] getAppOpPermissionPackages(String permissionName) {
4777        synchronized (mPackages) {
4778            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4779            if (pkgs == null) {
4780                return null;
4781            }
4782            return pkgs.toArray(new String[pkgs.size()]);
4783        }
4784    }
4785
4786    @Override
4787    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4788            int flags, int userId) {
4789        try {
4790            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4791
4792            if (!sUserManager.exists(userId)) return null;
4793            flags = updateFlagsForResolve(flags, userId, intent);
4794            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4795                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4796
4797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4798            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4799                    flags, userId);
4800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4801
4802            final ResolveInfo bestChoice =
4803                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4804
4805            if (isEphemeralAllowed(intent, query, userId)) {
4806                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4807                final EphemeralResolveInfo ai =
4808                        getEphemeralResolveInfo(intent, resolvedType, userId);
4809                if (ai != null) {
4810                    if (DEBUG_EPHEMERAL) {
4811                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4812                    }
4813                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4814                    bestChoice.ephemeralResolveInfo = ai;
4815                }
4816                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4817            }
4818            return bestChoice;
4819        } finally {
4820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4821        }
4822    }
4823
4824    @Override
4825    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4826            IntentFilter filter, int match, ComponentName activity) {
4827        final int userId = UserHandle.getCallingUserId();
4828        if (DEBUG_PREFERRED) {
4829            Log.v(TAG, "setLastChosenActivity intent=" + intent
4830                + " resolvedType=" + resolvedType
4831                + " flags=" + flags
4832                + " filter=" + filter
4833                + " match=" + match
4834                + " activity=" + activity);
4835            filter.dump(new PrintStreamPrinter(System.out), "    ");
4836        }
4837        intent.setComponent(null);
4838        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4839                userId);
4840        // Find any earlier preferred or last chosen entries and nuke them
4841        findPreferredActivity(intent, resolvedType,
4842                flags, query, 0, false, true, false, userId);
4843        // Add the new activity as the last chosen for this filter
4844        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4845                "Setting last chosen");
4846    }
4847
4848    @Override
4849    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4850        final int userId = UserHandle.getCallingUserId();
4851        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4852        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4853                userId);
4854        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4855                false, false, false, userId);
4856    }
4857
4858
4859    private boolean isEphemeralAllowed(
4860            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4861        // Short circuit and return early if possible.
4862        if (DISABLE_EPHEMERAL_APPS) {
4863            return false;
4864        }
4865        final int callingUser = UserHandle.getCallingUserId();
4866        if (callingUser != UserHandle.USER_SYSTEM) {
4867            return false;
4868        }
4869        if (mEphemeralResolverConnection == null) {
4870            return false;
4871        }
4872        if (intent.getComponent() != null) {
4873            return false;
4874        }
4875        if (intent.getPackage() != null) {
4876            return false;
4877        }
4878        final boolean isWebUri = hasWebURI(intent);
4879        if (!isWebUri) {
4880            return false;
4881        }
4882        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4883        synchronized (mPackages) {
4884            final int count = resolvedActivites.size();
4885            for (int n = 0; n < count; n++) {
4886                ResolveInfo info = resolvedActivites.get(n);
4887                String packageName = info.activityInfo.packageName;
4888                PackageSetting ps = mSettings.mPackages.get(packageName);
4889                if (ps != null) {
4890                    // Try to get the status from User settings first
4891                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4892                    int status = (int) (packedStatus >> 32);
4893                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4894                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4895                        if (DEBUG_EPHEMERAL) {
4896                            Slog.v(TAG, "DENY ephemeral apps;"
4897                                + " pkg: " + packageName + ", status: " + status);
4898                        }
4899                        return false;
4900                    }
4901                }
4902            }
4903        }
4904        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4905        return true;
4906    }
4907
4908    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4909            int userId) {
4910        MessageDigest digest = null;
4911        try {
4912            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4913        } catch (NoSuchAlgorithmException e) {
4914            // If we can't create a digest, ignore ephemeral apps.
4915            return null;
4916        }
4917
4918        final byte[] hostBytes = intent.getData().getHost().getBytes();
4919        final byte[] digestBytes = digest.digest(hostBytes);
4920        int shaPrefix =
4921                digestBytes[0] << 24
4922                | digestBytes[1] << 16
4923                | digestBytes[2] << 8
4924                | digestBytes[3] << 0;
4925        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4926                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4927        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4928            // No hash prefix match; there are no ephemeral apps for this domain.
4929            return null;
4930        }
4931        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4932            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4933            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4934                continue;
4935            }
4936            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4937            // No filters; this should never happen.
4938            if (filters.isEmpty()) {
4939                continue;
4940            }
4941            // We have a domain match; resolve the filters to see if anything matches.
4942            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4943            for (int j = filters.size() - 1; j >= 0; --j) {
4944                final EphemeralResolveIntentInfo intentInfo =
4945                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4946                ephemeralResolver.addFilter(intentInfo);
4947            }
4948            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4949                    intent, resolvedType, false /*defaultOnly*/, userId);
4950            if (!matchedResolveInfoList.isEmpty()) {
4951                return matchedResolveInfoList.get(0);
4952            }
4953        }
4954        // Hash or filter mis-match; no ephemeral apps for this domain.
4955        return null;
4956    }
4957
4958    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4959            int flags, List<ResolveInfo> query, int userId) {
4960        if (query != null) {
4961            final int N = query.size();
4962            if (N == 1) {
4963                return query.get(0);
4964            } else if (N > 1) {
4965                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4966                // If there is more than one activity with the same priority,
4967                // then let the user decide between them.
4968                ResolveInfo r0 = query.get(0);
4969                ResolveInfo r1 = query.get(1);
4970                if (DEBUG_INTENT_MATCHING || debug) {
4971                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4972                            + r1.activityInfo.name + "=" + r1.priority);
4973                }
4974                // If the first activity has a higher priority, or a different
4975                // default, then it is always desirable to pick it.
4976                if (r0.priority != r1.priority
4977                        || r0.preferredOrder != r1.preferredOrder
4978                        || r0.isDefault != r1.isDefault) {
4979                    return query.get(0);
4980                }
4981                // If we have saved a preference for a preferred activity for
4982                // this Intent, use that.
4983                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4984                        flags, query, r0.priority, true, false, debug, userId);
4985                if (ri != null) {
4986                    return ri;
4987                }
4988                ri = new ResolveInfo(mResolveInfo);
4989                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4990                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4991                ri.activityInfo.applicationInfo = new ApplicationInfo(
4992                        ri.activityInfo.applicationInfo);
4993                if (userId != 0) {
4994                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4995                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4996                }
4997                // Make sure that the resolver is displayable in car mode
4998                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4999                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5000                return ri;
5001            }
5002        }
5003        return null;
5004    }
5005
5006    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5007            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5008        final int N = query.size();
5009        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5010                .get(userId);
5011        // Get the list of persistent preferred activities that handle the intent
5012        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5013        List<PersistentPreferredActivity> pprefs = ppir != null
5014                ? ppir.queryIntent(intent, resolvedType,
5015                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5016                : null;
5017        if (pprefs != null && pprefs.size() > 0) {
5018            final int M = pprefs.size();
5019            for (int i=0; i<M; i++) {
5020                final PersistentPreferredActivity ppa = pprefs.get(i);
5021                if (DEBUG_PREFERRED || debug) {
5022                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5023                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5024                            + "\n  component=" + ppa.mComponent);
5025                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5026                }
5027                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5028                        flags | MATCH_DISABLED_COMPONENTS, userId);
5029                if (DEBUG_PREFERRED || debug) {
5030                    Slog.v(TAG, "Found persistent preferred activity:");
5031                    if (ai != null) {
5032                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5033                    } else {
5034                        Slog.v(TAG, "  null");
5035                    }
5036                }
5037                if (ai == null) {
5038                    // This previously registered persistent preferred activity
5039                    // component is no longer known. Ignore it and do NOT remove it.
5040                    continue;
5041                }
5042                for (int j=0; j<N; j++) {
5043                    final ResolveInfo ri = query.get(j);
5044                    if (!ri.activityInfo.applicationInfo.packageName
5045                            .equals(ai.applicationInfo.packageName)) {
5046                        continue;
5047                    }
5048                    if (!ri.activityInfo.name.equals(ai.name)) {
5049                        continue;
5050                    }
5051                    //  Found a persistent preference that can handle the intent.
5052                    if (DEBUG_PREFERRED || debug) {
5053                        Slog.v(TAG, "Returning persistent preferred activity: " +
5054                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5055                    }
5056                    return ri;
5057                }
5058            }
5059        }
5060        return null;
5061    }
5062
5063    // TODO: handle preferred activities missing while user has amnesia
5064    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5065            List<ResolveInfo> query, int priority, boolean always,
5066            boolean removeMatches, boolean debug, int userId) {
5067        if (!sUserManager.exists(userId)) return null;
5068        flags = updateFlagsForResolve(flags, userId, intent);
5069        // writer
5070        synchronized (mPackages) {
5071            if (intent.getSelector() != null) {
5072                intent = intent.getSelector();
5073            }
5074            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5075
5076            // Try to find a matching persistent preferred activity.
5077            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5078                    debug, userId);
5079
5080            // If a persistent preferred activity matched, use it.
5081            if (pri != null) {
5082                return pri;
5083            }
5084
5085            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5086            // Get the list of preferred activities that handle the intent
5087            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5088            List<PreferredActivity> prefs = pir != null
5089                    ? pir.queryIntent(intent, resolvedType,
5090                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5091                    : null;
5092            if (prefs != null && prefs.size() > 0) {
5093                boolean changed = false;
5094                try {
5095                    // First figure out how good the original match set is.
5096                    // We will only allow preferred activities that came
5097                    // from the same match quality.
5098                    int match = 0;
5099
5100                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5101
5102                    final int N = query.size();
5103                    for (int j=0; j<N; j++) {
5104                        final ResolveInfo ri = query.get(j);
5105                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5106                                + ": 0x" + Integer.toHexString(match));
5107                        if (ri.match > match) {
5108                            match = ri.match;
5109                        }
5110                    }
5111
5112                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5113                            + Integer.toHexString(match));
5114
5115                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5116                    final int M = prefs.size();
5117                    for (int i=0; i<M; i++) {
5118                        final PreferredActivity pa = prefs.get(i);
5119                        if (DEBUG_PREFERRED || debug) {
5120                            Slog.v(TAG, "Checking PreferredActivity ds="
5121                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5122                                    + "\n  component=" + pa.mPref.mComponent);
5123                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5124                        }
5125                        if (pa.mPref.mMatch != match) {
5126                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5127                                    + Integer.toHexString(pa.mPref.mMatch));
5128                            continue;
5129                        }
5130                        // If it's not an "always" type preferred activity and that's what we're
5131                        // looking for, skip it.
5132                        if (always && !pa.mPref.mAlways) {
5133                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5134                            continue;
5135                        }
5136                        final ActivityInfo ai = getActivityInfo(
5137                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5138                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5139                                userId);
5140                        if (DEBUG_PREFERRED || debug) {
5141                            Slog.v(TAG, "Found preferred activity:");
5142                            if (ai != null) {
5143                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5144                            } else {
5145                                Slog.v(TAG, "  null");
5146                            }
5147                        }
5148                        if (ai == null) {
5149                            // This previously registered preferred activity
5150                            // component is no longer known.  Most likely an update
5151                            // to the app was installed and in the new version this
5152                            // component no longer exists.  Clean it up by removing
5153                            // it from the preferred activities list, and skip it.
5154                            Slog.w(TAG, "Removing dangling preferred activity: "
5155                                    + pa.mPref.mComponent);
5156                            pir.removeFilter(pa);
5157                            changed = true;
5158                            continue;
5159                        }
5160                        for (int j=0; j<N; j++) {
5161                            final ResolveInfo ri = query.get(j);
5162                            if (!ri.activityInfo.applicationInfo.packageName
5163                                    .equals(ai.applicationInfo.packageName)) {
5164                                continue;
5165                            }
5166                            if (!ri.activityInfo.name.equals(ai.name)) {
5167                                continue;
5168                            }
5169
5170                            if (removeMatches) {
5171                                pir.removeFilter(pa);
5172                                changed = true;
5173                                if (DEBUG_PREFERRED) {
5174                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5175                                }
5176                                break;
5177                            }
5178
5179                            // Okay we found a previously set preferred or last chosen app.
5180                            // If the result set is different from when this
5181                            // was created, we need to clear it and re-ask the
5182                            // user their preference, if we're looking for an "always" type entry.
5183                            if (always && !pa.mPref.sameSet(query)) {
5184                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5185                                        + intent + " type " + resolvedType);
5186                                if (DEBUG_PREFERRED) {
5187                                    Slog.v(TAG, "Removing preferred activity since set changed "
5188                                            + pa.mPref.mComponent);
5189                                }
5190                                pir.removeFilter(pa);
5191                                // Re-add the filter as a "last chosen" entry (!always)
5192                                PreferredActivity lastChosen = new PreferredActivity(
5193                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5194                                pir.addFilter(lastChosen);
5195                                changed = true;
5196                                return null;
5197                            }
5198
5199                            // Yay! Either the set matched or we're looking for the last chosen
5200                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5201                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5202                            return ri;
5203                        }
5204                    }
5205                } finally {
5206                    if (changed) {
5207                        if (DEBUG_PREFERRED) {
5208                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5209                        }
5210                        scheduleWritePackageRestrictionsLocked(userId);
5211                    }
5212                }
5213            }
5214        }
5215        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5216        return null;
5217    }
5218
5219    /*
5220     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5221     */
5222    @Override
5223    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5224            int targetUserId) {
5225        mContext.enforceCallingOrSelfPermission(
5226                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5227        List<CrossProfileIntentFilter> matches =
5228                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5229        if (matches != null) {
5230            int size = matches.size();
5231            for (int i = 0; i < size; i++) {
5232                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5233            }
5234        }
5235        if (hasWebURI(intent)) {
5236            // cross-profile app linking works only towards the parent.
5237            final UserInfo parent = getProfileParent(sourceUserId);
5238            synchronized(mPackages) {
5239                int flags = updateFlagsForResolve(0, parent.id, intent);
5240                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5241                        intent, resolvedType, flags, sourceUserId, parent.id);
5242                return xpDomainInfo != null;
5243            }
5244        }
5245        return false;
5246    }
5247
5248    private UserInfo getProfileParent(int userId) {
5249        final long identity = Binder.clearCallingIdentity();
5250        try {
5251            return sUserManager.getProfileParent(userId);
5252        } finally {
5253            Binder.restoreCallingIdentity(identity);
5254        }
5255    }
5256
5257    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5258            String resolvedType, int userId) {
5259        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5260        if (resolver != null) {
5261            return resolver.queryIntent(intent, resolvedType, false, userId);
5262        }
5263        return null;
5264    }
5265
5266    @Override
5267    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5268            String resolvedType, int flags, int userId) {
5269        try {
5270            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5271
5272            return new ParceledListSlice<>(
5273                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5274        } finally {
5275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5276        }
5277    }
5278
5279    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5280            String resolvedType, int flags, int userId) {
5281        if (!sUserManager.exists(userId)) return Collections.emptyList();
5282        flags = updateFlagsForResolve(flags, userId, intent);
5283        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5284                false /* requireFullPermission */, false /* checkShell */,
5285                "query intent activities");
5286        ComponentName comp = intent.getComponent();
5287        if (comp == null) {
5288            if (intent.getSelector() != null) {
5289                intent = intent.getSelector();
5290                comp = intent.getComponent();
5291            }
5292        }
5293
5294        if (comp != null) {
5295            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5296            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5297            if (ai != null) {
5298                final ResolveInfo ri = new ResolveInfo();
5299                ri.activityInfo = ai;
5300                list.add(ri);
5301            }
5302            return list;
5303        }
5304
5305        // reader
5306        synchronized (mPackages) {
5307            final String pkgName = intent.getPackage();
5308            if (pkgName == null) {
5309                List<CrossProfileIntentFilter> matchingFilters =
5310                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5311                // Check for results that need to skip the current profile.
5312                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5313                        resolvedType, flags, userId);
5314                if (xpResolveInfo != null) {
5315                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5316                    result.add(xpResolveInfo);
5317                    return filterIfNotSystemUser(result, userId);
5318                }
5319
5320                // Check for results in the current profile.
5321                List<ResolveInfo> result = mActivities.queryIntent(
5322                        intent, resolvedType, flags, userId);
5323                result = filterIfNotSystemUser(result, userId);
5324
5325                // Check for cross profile results.
5326                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5327                xpResolveInfo = queryCrossProfileIntents(
5328                        matchingFilters, intent, resolvedType, flags, userId,
5329                        hasNonNegativePriorityResult);
5330                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5331                    boolean isVisibleToUser = filterIfNotSystemUser(
5332                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5333                    if (isVisibleToUser) {
5334                        result.add(xpResolveInfo);
5335                        Collections.sort(result, mResolvePrioritySorter);
5336                    }
5337                }
5338                if (hasWebURI(intent)) {
5339                    CrossProfileDomainInfo xpDomainInfo = null;
5340                    final UserInfo parent = getProfileParent(userId);
5341                    if (parent != null) {
5342                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5343                                flags, userId, parent.id);
5344                    }
5345                    if (xpDomainInfo != null) {
5346                        if (xpResolveInfo != null) {
5347                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5348                            // in the result.
5349                            result.remove(xpResolveInfo);
5350                        }
5351                        if (result.size() == 0) {
5352                            result.add(xpDomainInfo.resolveInfo);
5353                            return result;
5354                        }
5355                    } else if (result.size() <= 1) {
5356                        return result;
5357                    }
5358                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5359                            xpDomainInfo, userId);
5360                    Collections.sort(result, mResolvePrioritySorter);
5361                }
5362                return result;
5363            }
5364            final PackageParser.Package pkg = mPackages.get(pkgName);
5365            if (pkg != null) {
5366                return filterIfNotSystemUser(
5367                        mActivities.queryIntentForPackage(
5368                                intent, resolvedType, flags, pkg.activities, userId),
5369                        userId);
5370            }
5371            return new ArrayList<ResolveInfo>();
5372        }
5373    }
5374
5375    private static class CrossProfileDomainInfo {
5376        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5377        ResolveInfo resolveInfo;
5378        /* Best domain verification status of the activities found in the other profile */
5379        int bestDomainVerificationStatus;
5380    }
5381
5382    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5383            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5384        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5385                sourceUserId)) {
5386            return null;
5387        }
5388        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5389                resolvedType, flags, parentUserId);
5390
5391        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5392            return null;
5393        }
5394        CrossProfileDomainInfo result = null;
5395        int size = resultTargetUser.size();
5396        for (int i = 0; i < size; i++) {
5397            ResolveInfo riTargetUser = resultTargetUser.get(i);
5398            // Intent filter verification is only for filters that specify a host. So don't return
5399            // those that handle all web uris.
5400            if (riTargetUser.handleAllWebDataURI) {
5401                continue;
5402            }
5403            String packageName = riTargetUser.activityInfo.packageName;
5404            PackageSetting ps = mSettings.mPackages.get(packageName);
5405            if (ps == null) {
5406                continue;
5407            }
5408            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5409            int status = (int)(verificationState >> 32);
5410            if (result == null) {
5411                result = new CrossProfileDomainInfo();
5412                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5413                        sourceUserId, parentUserId);
5414                result.bestDomainVerificationStatus = status;
5415            } else {
5416                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5417                        result.bestDomainVerificationStatus);
5418            }
5419        }
5420        // Don't consider matches with status NEVER across profiles.
5421        if (result != null && result.bestDomainVerificationStatus
5422                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5423            return null;
5424        }
5425        return result;
5426    }
5427
5428    /**
5429     * Verification statuses are ordered from the worse to the best, except for
5430     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5431     */
5432    private int bestDomainVerificationStatus(int status1, int status2) {
5433        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5434            return status2;
5435        }
5436        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5437            return status1;
5438        }
5439        return (int) MathUtils.max(status1, status2);
5440    }
5441
5442    private boolean isUserEnabled(int userId) {
5443        long callingId = Binder.clearCallingIdentity();
5444        try {
5445            UserInfo userInfo = sUserManager.getUserInfo(userId);
5446            return userInfo != null && userInfo.isEnabled();
5447        } finally {
5448            Binder.restoreCallingIdentity(callingId);
5449        }
5450    }
5451
5452    /**
5453     * Filter out activities with systemUserOnly flag set, when current user is not System.
5454     *
5455     * @return filtered list
5456     */
5457    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5458        if (userId == UserHandle.USER_SYSTEM) {
5459            return resolveInfos;
5460        }
5461        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5462            ResolveInfo info = resolveInfos.get(i);
5463            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5464                resolveInfos.remove(i);
5465            }
5466        }
5467        return resolveInfos;
5468    }
5469
5470    /**
5471     * @param resolveInfos list of resolve infos in descending priority order
5472     * @return if the list contains a resolve info with non-negative priority
5473     */
5474    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5475        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5476    }
5477
5478    private static boolean hasWebURI(Intent intent) {
5479        if (intent.getData() == null) {
5480            return false;
5481        }
5482        final String scheme = intent.getScheme();
5483        if (TextUtils.isEmpty(scheme)) {
5484            return false;
5485        }
5486        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5487    }
5488
5489    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5490            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5491            int userId) {
5492        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5493
5494        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5495            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5496                    candidates.size());
5497        }
5498
5499        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5500        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5501        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5502        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5503        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5504        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5505
5506        synchronized (mPackages) {
5507            final int count = candidates.size();
5508            // First, try to use linked apps. Partition the candidates into four lists:
5509            // one for the final results, one for the "do not use ever", one for "undefined status"
5510            // and finally one for "browser app type".
5511            for (int n=0; n<count; n++) {
5512                ResolveInfo info = candidates.get(n);
5513                String packageName = info.activityInfo.packageName;
5514                PackageSetting ps = mSettings.mPackages.get(packageName);
5515                if (ps != null) {
5516                    // Add to the special match all list (Browser use case)
5517                    if (info.handleAllWebDataURI) {
5518                        matchAllList.add(info);
5519                        continue;
5520                    }
5521                    // Try to get the status from User settings first
5522                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5523                    int status = (int)(packedStatus >> 32);
5524                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5525                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5526                        if (DEBUG_DOMAIN_VERIFICATION) {
5527                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5528                                    + " : linkgen=" + linkGeneration);
5529                        }
5530                        // Use link-enabled generation as preferredOrder, i.e.
5531                        // prefer newly-enabled over earlier-enabled.
5532                        info.preferredOrder = linkGeneration;
5533                        alwaysList.add(info);
5534                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5535                        if (DEBUG_DOMAIN_VERIFICATION) {
5536                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5537                        }
5538                        neverList.add(info);
5539                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5540                        if (DEBUG_DOMAIN_VERIFICATION) {
5541                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5542                        }
5543                        alwaysAskList.add(info);
5544                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5545                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5546                        if (DEBUG_DOMAIN_VERIFICATION) {
5547                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5548                        }
5549                        undefinedList.add(info);
5550                    }
5551                }
5552            }
5553
5554            // We'll want to include browser possibilities in a few cases
5555            boolean includeBrowser = false;
5556
5557            // First try to add the "always" resolution(s) for the current user, if any
5558            if (alwaysList.size() > 0) {
5559                result.addAll(alwaysList);
5560            } else {
5561                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5562                result.addAll(undefinedList);
5563                // Maybe add one for the other profile.
5564                if (xpDomainInfo != null && (
5565                        xpDomainInfo.bestDomainVerificationStatus
5566                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5567                    result.add(xpDomainInfo.resolveInfo);
5568                }
5569                includeBrowser = true;
5570            }
5571
5572            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5573            // If there were 'always' entries their preferred order has been set, so we also
5574            // back that off to make the alternatives equivalent
5575            if (alwaysAskList.size() > 0) {
5576                for (ResolveInfo i : result) {
5577                    i.preferredOrder = 0;
5578                }
5579                result.addAll(alwaysAskList);
5580                includeBrowser = true;
5581            }
5582
5583            if (includeBrowser) {
5584                // Also add browsers (all of them or only the default one)
5585                if (DEBUG_DOMAIN_VERIFICATION) {
5586                    Slog.v(TAG, "   ...including browsers in candidate set");
5587                }
5588                if ((matchFlags & MATCH_ALL) != 0) {
5589                    result.addAll(matchAllList);
5590                } else {
5591                    // Browser/generic handling case.  If there's a default browser, go straight
5592                    // to that (but only if there is no other higher-priority match).
5593                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5594                    int maxMatchPrio = 0;
5595                    ResolveInfo defaultBrowserMatch = null;
5596                    final int numCandidates = matchAllList.size();
5597                    for (int n = 0; n < numCandidates; n++) {
5598                        ResolveInfo info = matchAllList.get(n);
5599                        // track the highest overall match priority...
5600                        if (info.priority > maxMatchPrio) {
5601                            maxMatchPrio = info.priority;
5602                        }
5603                        // ...and the highest-priority default browser match
5604                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5605                            if (defaultBrowserMatch == null
5606                                    || (defaultBrowserMatch.priority < info.priority)) {
5607                                if (debug) {
5608                                    Slog.v(TAG, "Considering default browser match " + info);
5609                                }
5610                                defaultBrowserMatch = info;
5611                            }
5612                        }
5613                    }
5614                    if (defaultBrowserMatch != null
5615                            && defaultBrowserMatch.priority >= maxMatchPrio
5616                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5617                    {
5618                        if (debug) {
5619                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5620                        }
5621                        result.add(defaultBrowserMatch);
5622                    } else {
5623                        result.addAll(matchAllList);
5624                    }
5625                }
5626
5627                // If there is nothing selected, add all candidates and remove the ones that the user
5628                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5629                if (result.size() == 0) {
5630                    result.addAll(candidates);
5631                    result.removeAll(neverList);
5632                }
5633            }
5634        }
5635        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5636            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5637                    result.size());
5638            for (ResolveInfo info : result) {
5639                Slog.v(TAG, "  + " + info.activityInfo);
5640            }
5641        }
5642        return result;
5643    }
5644
5645    // Returns a packed value as a long:
5646    //
5647    // high 'int'-sized word: link status: undefined/ask/never/always.
5648    // low 'int'-sized word: relative priority among 'always' results.
5649    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5650        long result = ps.getDomainVerificationStatusForUser(userId);
5651        // if none available, get the master status
5652        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5653            if (ps.getIntentFilterVerificationInfo() != null) {
5654                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5655            }
5656        }
5657        return result;
5658    }
5659
5660    private ResolveInfo querySkipCurrentProfileIntents(
5661            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5662            int flags, int sourceUserId) {
5663        if (matchingFilters != null) {
5664            int size = matchingFilters.size();
5665            for (int i = 0; i < size; i ++) {
5666                CrossProfileIntentFilter filter = matchingFilters.get(i);
5667                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5668                    // Checking if there are activities in the target user that can handle the
5669                    // intent.
5670                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5671                            resolvedType, flags, sourceUserId);
5672                    if (resolveInfo != null) {
5673                        return resolveInfo;
5674                    }
5675                }
5676            }
5677        }
5678        return null;
5679    }
5680
5681    // Return matching ResolveInfo in target user if any.
5682    private ResolveInfo queryCrossProfileIntents(
5683            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5684            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5685        if (matchingFilters != null) {
5686            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5687            // match the same intent. For performance reasons, it is better not to
5688            // run queryIntent twice for the same userId
5689            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5690            int size = matchingFilters.size();
5691            for (int i = 0; i < size; i++) {
5692                CrossProfileIntentFilter filter = matchingFilters.get(i);
5693                int targetUserId = filter.getTargetUserId();
5694                boolean skipCurrentProfile =
5695                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5696                boolean skipCurrentProfileIfNoMatchFound =
5697                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5698                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5699                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5700                    // Checking if there are activities in the target user that can handle the
5701                    // intent.
5702                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5703                            resolvedType, flags, sourceUserId);
5704                    if (resolveInfo != null) return resolveInfo;
5705                    alreadyTriedUserIds.put(targetUserId, true);
5706                }
5707            }
5708        }
5709        return null;
5710    }
5711
5712    /**
5713     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5714     * will forward the intent to the filter's target user.
5715     * Otherwise, returns null.
5716     */
5717    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5718            String resolvedType, int flags, int sourceUserId) {
5719        int targetUserId = filter.getTargetUserId();
5720        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5721                resolvedType, flags, targetUserId);
5722        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5723            // If all the matches in the target profile are suspended, return null.
5724            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5725                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5726                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5727                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5728                            targetUserId);
5729                }
5730            }
5731        }
5732        return null;
5733    }
5734
5735    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5736            int sourceUserId, int targetUserId) {
5737        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5738        long ident = Binder.clearCallingIdentity();
5739        boolean targetIsProfile;
5740        try {
5741            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5742        } finally {
5743            Binder.restoreCallingIdentity(ident);
5744        }
5745        String className;
5746        if (targetIsProfile) {
5747            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5748        } else {
5749            className = FORWARD_INTENT_TO_PARENT;
5750        }
5751        ComponentName forwardingActivityComponentName = new ComponentName(
5752                mAndroidApplication.packageName, className);
5753        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5754                sourceUserId);
5755        if (!targetIsProfile) {
5756            forwardingActivityInfo.showUserIcon = targetUserId;
5757            forwardingResolveInfo.noResourceId = true;
5758        }
5759        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5760        forwardingResolveInfo.priority = 0;
5761        forwardingResolveInfo.preferredOrder = 0;
5762        forwardingResolveInfo.match = 0;
5763        forwardingResolveInfo.isDefault = true;
5764        forwardingResolveInfo.filter = filter;
5765        forwardingResolveInfo.targetUserId = targetUserId;
5766        return forwardingResolveInfo;
5767    }
5768
5769    @Override
5770    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5771            Intent[] specifics, String[] specificTypes, Intent intent,
5772            String resolvedType, int flags, int userId) {
5773        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5774                specificTypes, intent, resolvedType, flags, userId));
5775    }
5776
5777    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5778            Intent[] specifics, String[] specificTypes, Intent intent,
5779            String resolvedType, int flags, int userId) {
5780        if (!sUserManager.exists(userId)) return Collections.emptyList();
5781        flags = updateFlagsForResolve(flags, userId, intent);
5782        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5783                false /* requireFullPermission */, false /* checkShell */,
5784                "query intent activity options");
5785        final String resultsAction = intent.getAction();
5786
5787        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5788                | PackageManager.GET_RESOLVED_FILTER, userId);
5789
5790        if (DEBUG_INTENT_MATCHING) {
5791            Log.v(TAG, "Query " + intent + ": " + results);
5792        }
5793
5794        int specificsPos = 0;
5795        int N;
5796
5797        // todo: note that the algorithm used here is O(N^2).  This
5798        // isn't a problem in our current environment, but if we start running
5799        // into situations where we have more than 5 or 10 matches then this
5800        // should probably be changed to something smarter...
5801
5802        // First we go through and resolve each of the specific items
5803        // that were supplied, taking care of removing any corresponding
5804        // duplicate items in the generic resolve list.
5805        if (specifics != null) {
5806            for (int i=0; i<specifics.length; i++) {
5807                final Intent sintent = specifics[i];
5808                if (sintent == null) {
5809                    continue;
5810                }
5811
5812                if (DEBUG_INTENT_MATCHING) {
5813                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5814                }
5815
5816                String action = sintent.getAction();
5817                if (resultsAction != null && resultsAction.equals(action)) {
5818                    // If this action was explicitly requested, then don't
5819                    // remove things that have it.
5820                    action = null;
5821                }
5822
5823                ResolveInfo ri = null;
5824                ActivityInfo ai = null;
5825
5826                ComponentName comp = sintent.getComponent();
5827                if (comp == null) {
5828                    ri = resolveIntent(
5829                        sintent,
5830                        specificTypes != null ? specificTypes[i] : null,
5831                            flags, userId);
5832                    if (ri == null) {
5833                        continue;
5834                    }
5835                    if (ri == mResolveInfo) {
5836                        // ACK!  Must do something better with this.
5837                    }
5838                    ai = ri.activityInfo;
5839                    comp = new ComponentName(ai.applicationInfo.packageName,
5840                            ai.name);
5841                } else {
5842                    ai = getActivityInfo(comp, flags, userId);
5843                    if (ai == null) {
5844                        continue;
5845                    }
5846                }
5847
5848                // Look for any generic query activities that are duplicates
5849                // of this specific one, and remove them from the results.
5850                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5851                N = results.size();
5852                int j;
5853                for (j=specificsPos; j<N; j++) {
5854                    ResolveInfo sri = results.get(j);
5855                    if ((sri.activityInfo.name.equals(comp.getClassName())
5856                            && sri.activityInfo.applicationInfo.packageName.equals(
5857                                    comp.getPackageName()))
5858                        || (action != null && sri.filter.matchAction(action))) {
5859                        results.remove(j);
5860                        if (DEBUG_INTENT_MATCHING) Log.v(
5861                            TAG, "Removing duplicate item from " + j
5862                            + " due to specific " + specificsPos);
5863                        if (ri == null) {
5864                            ri = sri;
5865                        }
5866                        j--;
5867                        N--;
5868                    }
5869                }
5870
5871                // Add this specific item to its proper place.
5872                if (ri == null) {
5873                    ri = new ResolveInfo();
5874                    ri.activityInfo = ai;
5875                }
5876                results.add(specificsPos, ri);
5877                ri.specificIndex = i;
5878                specificsPos++;
5879            }
5880        }
5881
5882        // Now we go through the remaining generic results and remove any
5883        // duplicate actions that are found here.
5884        N = results.size();
5885        for (int i=specificsPos; i<N-1; i++) {
5886            final ResolveInfo rii = results.get(i);
5887            if (rii.filter == null) {
5888                continue;
5889            }
5890
5891            // Iterate over all of the actions of this result's intent
5892            // filter...  typically this should be just one.
5893            final Iterator<String> it = rii.filter.actionsIterator();
5894            if (it == null) {
5895                continue;
5896            }
5897            while (it.hasNext()) {
5898                final String action = it.next();
5899                if (resultsAction != null && resultsAction.equals(action)) {
5900                    // If this action was explicitly requested, then don't
5901                    // remove things that have it.
5902                    continue;
5903                }
5904                for (int j=i+1; j<N; j++) {
5905                    final ResolveInfo rij = results.get(j);
5906                    if (rij.filter != null && rij.filter.hasAction(action)) {
5907                        results.remove(j);
5908                        if (DEBUG_INTENT_MATCHING) Log.v(
5909                            TAG, "Removing duplicate item from " + j
5910                            + " due to action " + action + " at " + i);
5911                        j--;
5912                        N--;
5913                    }
5914                }
5915            }
5916
5917            // If the caller didn't request filter information, drop it now
5918            // so we don't have to marshall/unmarshall it.
5919            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5920                rii.filter = null;
5921            }
5922        }
5923
5924        // Filter out the caller activity if so requested.
5925        if (caller != null) {
5926            N = results.size();
5927            for (int i=0; i<N; i++) {
5928                ActivityInfo ainfo = results.get(i).activityInfo;
5929                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5930                        && caller.getClassName().equals(ainfo.name)) {
5931                    results.remove(i);
5932                    break;
5933                }
5934            }
5935        }
5936
5937        // If the caller didn't request filter information,
5938        // drop them now so we don't have to
5939        // marshall/unmarshall it.
5940        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5941            N = results.size();
5942            for (int i=0; i<N; i++) {
5943                results.get(i).filter = null;
5944            }
5945        }
5946
5947        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5948        return results;
5949    }
5950
5951    @Override
5952    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5953            String resolvedType, int flags, int userId) {
5954        return new ParceledListSlice<>(
5955                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5956    }
5957
5958    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5959            String resolvedType, int flags, int userId) {
5960        if (!sUserManager.exists(userId)) return Collections.emptyList();
5961        flags = updateFlagsForResolve(flags, userId, intent);
5962        ComponentName comp = intent.getComponent();
5963        if (comp == null) {
5964            if (intent.getSelector() != null) {
5965                intent = intent.getSelector();
5966                comp = intent.getComponent();
5967            }
5968        }
5969        if (comp != null) {
5970            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5971            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5972            if (ai != null) {
5973                ResolveInfo ri = new ResolveInfo();
5974                ri.activityInfo = ai;
5975                list.add(ri);
5976            }
5977            return list;
5978        }
5979
5980        // reader
5981        synchronized (mPackages) {
5982            String pkgName = intent.getPackage();
5983            if (pkgName == null) {
5984                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5985            }
5986            final PackageParser.Package pkg = mPackages.get(pkgName);
5987            if (pkg != null) {
5988                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5989                        userId);
5990            }
5991            return Collections.emptyList();
5992        }
5993    }
5994
5995    @Override
5996    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5997        if (!sUserManager.exists(userId)) return null;
5998        flags = updateFlagsForResolve(flags, userId, intent);
5999        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6000        if (query != null) {
6001            if (query.size() >= 1) {
6002                // If there is more than one service with the same priority,
6003                // just arbitrarily pick the first one.
6004                return query.get(0);
6005            }
6006        }
6007        return null;
6008    }
6009
6010    @Override
6011    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6012            String resolvedType, int flags, int userId) {
6013        return new ParceledListSlice<>(
6014                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6015    }
6016
6017    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6018            String resolvedType, int flags, int userId) {
6019        if (!sUserManager.exists(userId)) return Collections.emptyList();
6020        flags = updateFlagsForResolve(flags, userId, intent);
6021        ComponentName comp = intent.getComponent();
6022        if (comp == null) {
6023            if (intent.getSelector() != null) {
6024                intent = intent.getSelector();
6025                comp = intent.getComponent();
6026            }
6027        }
6028        if (comp != null) {
6029            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6030            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6031            if (si != null) {
6032                final ResolveInfo ri = new ResolveInfo();
6033                ri.serviceInfo = si;
6034                list.add(ri);
6035            }
6036            return list;
6037        }
6038
6039        // reader
6040        synchronized (mPackages) {
6041            String pkgName = intent.getPackage();
6042            if (pkgName == null) {
6043                return mServices.queryIntent(intent, resolvedType, flags, userId);
6044            }
6045            final PackageParser.Package pkg = mPackages.get(pkgName);
6046            if (pkg != null) {
6047                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6048                        userId);
6049            }
6050            return Collections.emptyList();
6051        }
6052    }
6053
6054    @Override
6055    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6056            String resolvedType, int flags, int userId) {
6057        return new ParceledListSlice<>(
6058                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6059    }
6060
6061    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6062            Intent intent, String resolvedType, int flags, int userId) {
6063        if (!sUserManager.exists(userId)) return Collections.emptyList();
6064        flags = updateFlagsForResolve(flags, userId, intent);
6065        ComponentName comp = intent.getComponent();
6066        if (comp == null) {
6067            if (intent.getSelector() != null) {
6068                intent = intent.getSelector();
6069                comp = intent.getComponent();
6070            }
6071        }
6072        if (comp != null) {
6073            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6074            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6075            if (pi != null) {
6076                final ResolveInfo ri = new ResolveInfo();
6077                ri.providerInfo = pi;
6078                list.add(ri);
6079            }
6080            return list;
6081        }
6082
6083        // reader
6084        synchronized (mPackages) {
6085            String pkgName = intent.getPackage();
6086            if (pkgName == null) {
6087                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6088            }
6089            final PackageParser.Package pkg = mPackages.get(pkgName);
6090            if (pkg != null) {
6091                return mProviders.queryIntentForPackage(
6092                        intent, resolvedType, flags, pkg.providers, userId);
6093            }
6094            return Collections.emptyList();
6095        }
6096    }
6097
6098    @Override
6099    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6100        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6101        flags = updateFlagsForPackage(flags, userId, null);
6102        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6103        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6104                true /* requireFullPermission */, false /* checkShell */,
6105                "get installed packages");
6106
6107        // writer
6108        synchronized (mPackages) {
6109            ArrayList<PackageInfo> list;
6110            if (listUninstalled) {
6111                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6112                for (PackageSetting ps : mSettings.mPackages.values()) {
6113                    final PackageInfo pi;
6114                    if (ps.pkg != null) {
6115                        pi = generatePackageInfo(ps, flags, userId);
6116                    } else {
6117                        pi = generatePackageInfo(ps, flags, userId);
6118                    }
6119                    if (pi != null) {
6120                        list.add(pi);
6121                    }
6122                }
6123            } else {
6124                list = new ArrayList<PackageInfo>(mPackages.size());
6125                for (PackageParser.Package p : mPackages.values()) {
6126                    final PackageInfo pi =
6127                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6128                    if (pi != null) {
6129                        list.add(pi);
6130                    }
6131                }
6132            }
6133
6134            return new ParceledListSlice<PackageInfo>(list);
6135        }
6136    }
6137
6138    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6139            String[] permissions, boolean[] tmp, int flags, int userId) {
6140        int numMatch = 0;
6141        final PermissionsState permissionsState = ps.getPermissionsState();
6142        for (int i=0; i<permissions.length; i++) {
6143            final String permission = permissions[i];
6144            if (permissionsState.hasPermission(permission, userId)) {
6145                tmp[i] = true;
6146                numMatch++;
6147            } else {
6148                tmp[i] = false;
6149            }
6150        }
6151        if (numMatch == 0) {
6152            return;
6153        }
6154        final PackageInfo pi;
6155        if (ps.pkg != null) {
6156            pi = generatePackageInfo(ps, flags, userId);
6157        } else {
6158            pi = generatePackageInfo(ps, flags, userId);
6159        }
6160        // The above might return null in cases of uninstalled apps or install-state
6161        // skew across users/profiles.
6162        if (pi != null) {
6163            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6164                if (numMatch == permissions.length) {
6165                    pi.requestedPermissions = permissions;
6166                } else {
6167                    pi.requestedPermissions = new String[numMatch];
6168                    numMatch = 0;
6169                    for (int i=0; i<permissions.length; i++) {
6170                        if (tmp[i]) {
6171                            pi.requestedPermissions[numMatch] = permissions[i];
6172                            numMatch++;
6173                        }
6174                    }
6175                }
6176            }
6177            list.add(pi);
6178        }
6179    }
6180
6181    @Override
6182    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6183            String[] permissions, int flags, int userId) {
6184        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6185        flags = updateFlagsForPackage(flags, userId, permissions);
6186        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6187
6188        // writer
6189        synchronized (mPackages) {
6190            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6191            boolean[] tmpBools = new boolean[permissions.length];
6192            if (listUninstalled) {
6193                for (PackageSetting ps : mSettings.mPackages.values()) {
6194                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6195                }
6196            } else {
6197                for (PackageParser.Package pkg : mPackages.values()) {
6198                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6199                    if (ps != null) {
6200                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6201                                userId);
6202                    }
6203                }
6204            }
6205
6206            return new ParceledListSlice<PackageInfo>(list);
6207        }
6208    }
6209
6210    @Override
6211    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6212        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6213        flags = updateFlagsForApplication(flags, userId, null);
6214        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6215
6216        // writer
6217        synchronized (mPackages) {
6218            ArrayList<ApplicationInfo> list;
6219            if (listUninstalled) {
6220                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6221                for (PackageSetting ps : mSettings.mPackages.values()) {
6222                    ApplicationInfo ai;
6223                    if (ps.pkg != null) {
6224                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6225                                ps.readUserState(userId), userId);
6226                    } else {
6227                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6228                    }
6229                    if (ai != null) {
6230                        list.add(ai);
6231                    }
6232                }
6233            } else {
6234                list = new ArrayList<ApplicationInfo>(mPackages.size());
6235                for (PackageParser.Package p : mPackages.values()) {
6236                    if (p.mExtras != null) {
6237                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6238                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6239                        if (ai != null) {
6240                            list.add(ai);
6241                        }
6242                    }
6243                }
6244            }
6245
6246            return new ParceledListSlice<ApplicationInfo>(list);
6247        }
6248    }
6249
6250    @Override
6251    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6252        if (DISABLE_EPHEMERAL_APPS) {
6253            return null;
6254        }
6255
6256        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6257                "getEphemeralApplications");
6258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6259                true /* requireFullPermission */, false /* checkShell */,
6260                "getEphemeralApplications");
6261        synchronized (mPackages) {
6262            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6263                    .getEphemeralApplicationsLPw(userId);
6264            if (ephemeralApps != null) {
6265                return new ParceledListSlice<>(ephemeralApps);
6266            }
6267        }
6268        return null;
6269    }
6270
6271    @Override
6272    public boolean isEphemeralApplication(String packageName, int userId) {
6273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6274                true /* requireFullPermission */, false /* checkShell */,
6275                "isEphemeral");
6276        if (DISABLE_EPHEMERAL_APPS) {
6277            return false;
6278        }
6279
6280        if (!isCallerSameApp(packageName)) {
6281            return false;
6282        }
6283        synchronized (mPackages) {
6284            PackageParser.Package pkg = mPackages.get(packageName);
6285            if (pkg != null) {
6286                return pkg.applicationInfo.isEphemeralApp();
6287            }
6288        }
6289        return false;
6290    }
6291
6292    @Override
6293    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6294        if (DISABLE_EPHEMERAL_APPS) {
6295            return null;
6296        }
6297
6298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6299                true /* requireFullPermission */, false /* checkShell */,
6300                "getCookie");
6301        if (!isCallerSameApp(packageName)) {
6302            return null;
6303        }
6304        synchronized (mPackages) {
6305            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6306                    packageName, userId);
6307        }
6308    }
6309
6310    @Override
6311    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6312        if (DISABLE_EPHEMERAL_APPS) {
6313            return true;
6314        }
6315
6316        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6317                true /* requireFullPermission */, true /* checkShell */,
6318                "setCookie");
6319        if (!isCallerSameApp(packageName)) {
6320            return false;
6321        }
6322        synchronized (mPackages) {
6323            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6324                    packageName, cookie, userId);
6325        }
6326    }
6327
6328    @Override
6329    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6330        if (DISABLE_EPHEMERAL_APPS) {
6331            return null;
6332        }
6333
6334        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6335                "getEphemeralApplicationIcon");
6336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6337                true /* requireFullPermission */, false /* checkShell */,
6338                "getEphemeralApplicationIcon");
6339        synchronized (mPackages) {
6340            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6341                    packageName, userId);
6342        }
6343    }
6344
6345    private boolean isCallerSameApp(String packageName) {
6346        PackageParser.Package pkg = mPackages.get(packageName);
6347        return pkg != null
6348                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6349    }
6350
6351    @Override
6352    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6353        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6354    }
6355
6356    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6357        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6358
6359        // reader
6360        synchronized (mPackages) {
6361            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6362            final int userId = UserHandle.getCallingUserId();
6363            while (i.hasNext()) {
6364                final PackageParser.Package p = i.next();
6365                if (p.applicationInfo == null) continue;
6366
6367                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6368                        && !p.applicationInfo.isDirectBootAware();
6369                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6370                        && p.applicationInfo.isDirectBootAware();
6371
6372                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6373                        && (!mSafeMode || isSystemApp(p))
6374                        && (matchesUnaware || matchesAware)) {
6375                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6376                    if (ps != null) {
6377                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6378                                ps.readUserState(userId), userId);
6379                        if (ai != null) {
6380                            finalList.add(ai);
6381                        }
6382                    }
6383                }
6384            }
6385        }
6386
6387        return finalList;
6388    }
6389
6390    @Override
6391    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6392        if (!sUserManager.exists(userId)) return null;
6393        flags = updateFlagsForComponent(flags, userId, name);
6394        // reader
6395        synchronized (mPackages) {
6396            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6397            PackageSetting ps = provider != null
6398                    ? mSettings.mPackages.get(provider.owner.packageName)
6399                    : null;
6400            return ps != null
6401                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6402                    ? PackageParser.generateProviderInfo(provider, flags,
6403                            ps.readUserState(userId), userId)
6404                    : null;
6405        }
6406    }
6407
6408    /**
6409     * @deprecated
6410     */
6411    @Deprecated
6412    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6413        // reader
6414        synchronized (mPackages) {
6415            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6416                    .entrySet().iterator();
6417            final int userId = UserHandle.getCallingUserId();
6418            while (i.hasNext()) {
6419                Map.Entry<String, PackageParser.Provider> entry = i.next();
6420                PackageParser.Provider p = entry.getValue();
6421                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6422
6423                if (ps != null && p.syncable
6424                        && (!mSafeMode || (p.info.applicationInfo.flags
6425                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6426                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6427                            ps.readUserState(userId), userId);
6428                    if (info != null) {
6429                        outNames.add(entry.getKey());
6430                        outInfo.add(info);
6431                    }
6432                }
6433            }
6434        }
6435    }
6436
6437    @Override
6438    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6439            int uid, int flags) {
6440        final int userId = processName != null ? UserHandle.getUserId(uid)
6441                : UserHandle.getCallingUserId();
6442        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6443        flags = updateFlagsForComponent(flags, userId, processName);
6444
6445        ArrayList<ProviderInfo> finalList = null;
6446        // reader
6447        synchronized (mPackages) {
6448            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6449            while (i.hasNext()) {
6450                final PackageParser.Provider p = i.next();
6451                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6452                if (ps != null && p.info.authority != null
6453                        && (processName == null
6454                                || (p.info.processName.equals(processName)
6455                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6456                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6457                    if (finalList == null) {
6458                        finalList = new ArrayList<ProviderInfo>(3);
6459                    }
6460                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6461                            ps.readUserState(userId), userId);
6462                    if (info != null) {
6463                        finalList.add(info);
6464                    }
6465                }
6466            }
6467        }
6468
6469        if (finalList != null) {
6470            Collections.sort(finalList, mProviderInitOrderSorter);
6471            return new ParceledListSlice<ProviderInfo>(finalList);
6472        }
6473
6474        return ParceledListSlice.emptyList();
6475    }
6476
6477    @Override
6478    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6479        // reader
6480        synchronized (mPackages) {
6481            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6482            return PackageParser.generateInstrumentationInfo(i, flags);
6483        }
6484    }
6485
6486    @Override
6487    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6488            String targetPackage, int flags) {
6489        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6490    }
6491
6492    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6493            int flags) {
6494        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6495
6496        // reader
6497        synchronized (mPackages) {
6498            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6499            while (i.hasNext()) {
6500                final PackageParser.Instrumentation p = i.next();
6501                if (targetPackage == null
6502                        || targetPackage.equals(p.info.targetPackage)) {
6503                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6504                            flags);
6505                    if (ii != null) {
6506                        finalList.add(ii);
6507                    }
6508                }
6509            }
6510        }
6511
6512        return finalList;
6513    }
6514
6515    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6516        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6517        if (overlays == null) {
6518            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6519            return;
6520        }
6521        for (PackageParser.Package opkg : overlays.values()) {
6522            // Not much to do if idmap fails: we already logged the error
6523            // and we certainly don't want to abort installation of pkg simply
6524            // because an overlay didn't fit properly. For these reasons,
6525            // ignore the return value of createIdmapForPackagePairLI.
6526            createIdmapForPackagePairLI(pkg, opkg);
6527        }
6528    }
6529
6530    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6531            PackageParser.Package opkg) {
6532        if (!opkg.mTrustedOverlay) {
6533            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6534                    opkg.baseCodePath + ": overlay not trusted");
6535            return false;
6536        }
6537        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6538        if (overlaySet == null) {
6539            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6540                    opkg.baseCodePath + " but target package has no known overlays");
6541            return false;
6542        }
6543        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6544        // TODO: generate idmap for split APKs
6545        try {
6546            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6547        } catch (InstallerException e) {
6548            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6549                    + opkg.baseCodePath);
6550            return false;
6551        }
6552        PackageParser.Package[] overlayArray =
6553            overlaySet.values().toArray(new PackageParser.Package[0]);
6554        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6555            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6556                return p1.mOverlayPriority - p2.mOverlayPriority;
6557            }
6558        };
6559        Arrays.sort(overlayArray, cmp);
6560
6561        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6562        int i = 0;
6563        for (PackageParser.Package p : overlayArray) {
6564            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6565        }
6566        return true;
6567    }
6568
6569    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6570        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6571        try {
6572            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6573        } finally {
6574            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6575        }
6576    }
6577
6578    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6579        final File[] files = dir.listFiles();
6580        if (ArrayUtils.isEmpty(files)) {
6581            Log.d(TAG, "No files in app dir " + dir);
6582            return;
6583        }
6584
6585        if (DEBUG_PACKAGE_SCANNING) {
6586            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6587                    + " flags=0x" + Integer.toHexString(parseFlags));
6588        }
6589
6590        for (File file : files) {
6591            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6592                    && !PackageInstallerService.isStageName(file.getName());
6593            if (!isPackage) {
6594                // Ignore entries which are not packages
6595                continue;
6596            }
6597            try {
6598                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6599                        scanFlags, currentTime, null);
6600            } catch (PackageManagerException e) {
6601                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6602
6603                // Delete invalid userdata apps
6604                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6605                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6606                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6607                    removeCodePathLI(file);
6608                }
6609            }
6610        }
6611    }
6612
6613    private static File getSettingsProblemFile() {
6614        File dataDir = Environment.getDataDirectory();
6615        File systemDir = new File(dataDir, "system");
6616        File fname = new File(systemDir, "uiderrors.txt");
6617        return fname;
6618    }
6619
6620    static void reportSettingsProblem(int priority, String msg) {
6621        logCriticalInfo(priority, msg);
6622    }
6623
6624    static void logCriticalInfo(int priority, String msg) {
6625        Slog.println(priority, TAG, msg);
6626        EventLogTags.writePmCriticalInfo(msg);
6627        try {
6628            File fname = getSettingsProblemFile();
6629            FileOutputStream out = new FileOutputStream(fname, true);
6630            PrintWriter pw = new FastPrintWriter(out);
6631            SimpleDateFormat formatter = new SimpleDateFormat();
6632            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6633            pw.println(dateString + ": " + msg);
6634            pw.close();
6635            FileUtils.setPermissions(
6636                    fname.toString(),
6637                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6638                    -1, -1);
6639        } catch (java.io.IOException e) {
6640        }
6641    }
6642
6643    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6644            final int policyFlags) throws PackageManagerException {
6645        if (ps != null
6646                && ps.codePath.equals(srcFile)
6647                && ps.timeStamp == srcFile.lastModified()
6648                && !isCompatSignatureUpdateNeeded(pkg)
6649                && !isRecoverSignatureUpdateNeeded(pkg)) {
6650            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6651            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6652            ArraySet<PublicKey> signingKs;
6653            synchronized (mPackages) {
6654                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6655            }
6656            if (ps.signatures.mSignatures != null
6657                    && ps.signatures.mSignatures.length != 0
6658                    && signingKs != null) {
6659                // Optimization: reuse the existing cached certificates
6660                // if the package appears to be unchanged.
6661                pkg.mSignatures = ps.signatures.mSignatures;
6662                pkg.mSigningKeys = signingKs;
6663                return;
6664            }
6665
6666            Slog.w(TAG, "PackageSetting for " + ps.name
6667                    + " is missing signatures.  Collecting certs again to recover them.");
6668        } else {
6669            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6670        }
6671
6672        try {
6673            PackageParser.collectCertificates(pkg, policyFlags);
6674        } catch (PackageParserException e) {
6675            throw PackageManagerException.from(e);
6676        }
6677    }
6678
6679    /**
6680     *  Traces a package scan.
6681     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6682     */
6683    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6684            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6685        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6686        try {
6687            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6688        } finally {
6689            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6690        }
6691    }
6692
6693    /**
6694     *  Scans a package and returns the newly parsed package.
6695     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6696     */
6697    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6698            long currentTime, UserHandle user) throws PackageManagerException {
6699        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6700        PackageParser pp = new PackageParser();
6701        pp.setSeparateProcesses(mSeparateProcesses);
6702        pp.setOnlyCoreApps(mOnlyCore);
6703        pp.setDisplayMetrics(mMetrics);
6704
6705        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6706            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6707        }
6708
6709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6710        final PackageParser.Package pkg;
6711        try {
6712            pkg = pp.parsePackage(scanFile, parseFlags);
6713        } catch (PackageParserException e) {
6714            throw PackageManagerException.from(e);
6715        } finally {
6716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6717        }
6718
6719        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6720    }
6721
6722    /**
6723     *  Scans a package and returns the newly parsed package.
6724     *  @throws PackageManagerException on a parse error.
6725     */
6726    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6727            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6728            throws PackageManagerException {
6729        // If the package has children and this is the first dive in the function
6730        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6731        // packages (parent and children) would be successfully scanned before the
6732        // actual scan since scanning mutates internal state and we want to atomically
6733        // install the package and its children.
6734        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6735            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6736                scanFlags |= SCAN_CHECK_ONLY;
6737            }
6738        } else {
6739            scanFlags &= ~SCAN_CHECK_ONLY;
6740        }
6741
6742        // Scan the parent
6743        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6744                scanFlags, currentTime, user);
6745
6746        // Scan the children
6747        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6748        for (int i = 0; i < childCount; i++) {
6749            PackageParser.Package childPackage = pkg.childPackages.get(i);
6750            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6751                    currentTime, user);
6752        }
6753
6754
6755        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6756            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6757        }
6758
6759        return scannedPkg;
6760    }
6761
6762    /**
6763     *  Scans a package and returns the newly parsed package.
6764     *  @throws PackageManagerException on a parse error.
6765     */
6766    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6767            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6768            throws PackageManagerException {
6769        PackageSetting ps = null;
6770        PackageSetting updatedPkg;
6771        // reader
6772        synchronized (mPackages) {
6773            // Look to see if we already know about this package.
6774            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6775            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6776                // This package has been renamed to its original name.  Let's
6777                // use that.
6778                ps = mSettings.peekPackageLPr(oldName);
6779            }
6780            // If there was no original package, see one for the real package name.
6781            if (ps == null) {
6782                ps = mSettings.peekPackageLPr(pkg.packageName);
6783            }
6784            // Check to see if this package could be hiding/updating a system
6785            // package.  Must look for it either under the original or real
6786            // package name depending on our state.
6787            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6788            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6789
6790            // If this is a package we don't know about on the system partition, we
6791            // may need to remove disabled child packages on the system partition
6792            // or may need to not add child packages if the parent apk is updated
6793            // on the data partition and no longer defines this child package.
6794            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6795                // If this is a parent package for an updated system app and this system
6796                // app got an OTA update which no longer defines some of the child packages
6797                // we have to prune them from the disabled system packages.
6798                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6799                if (disabledPs != null) {
6800                    final int scannedChildCount = (pkg.childPackages != null)
6801                            ? pkg.childPackages.size() : 0;
6802                    final int disabledChildCount = disabledPs.childPackageNames != null
6803                            ? disabledPs.childPackageNames.size() : 0;
6804                    for (int i = 0; i < disabledChildCount; i++) {
6805                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6806                        boolean disabledPackageAvailable = false;
6807                        for (int j = 0; j < scannedChildCount; j++) {
6808                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6809                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6810                                disabledPackageAvailable = true;
6811                                break;
6812                            }
6813                         }
6814                         if (!disabledPackageAvailable) {
6815                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6816                         }
6817                    }
6818                }
6819            }
6820        }
6821
6822        boolean updatedPkgBetter = false;
6823        // First check if this is a system package that may involve an update
6824        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6825            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6826            // it needs to drop FLAG_PRIVILEGED.
6827            if (locationIsPrivileged(scanFile)) {
6828                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6829            } else {
6830                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6831            }
6832
6833            if (ps != null && !ps.codePath.equals(scanFile)) {
6834                // The path has changed from what was last scanned...  check the
6835                // version of the new path against what we have stored to determine
6836                // what to do.
6837                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6838                if (pkg.mVersionCode <= ps.versionCode) {
6839                    // The system package has been updated and the code path does not match
6840                    // Ignore entry. Skip it.
6841                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6842                            + " ignored: updated version " + ps.versionCode
6843                            + " better than this " + pkg.mVersionCode);
6844                    if (!updatedPkg.codePath.equals(scanFile)) {
6845                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6846                                + ps.name + " changing from " + updatedPkg.codePathString
6847                                + " to " + scanFile);
6848                        updatedPkg.codePath = scanFile;
6849                        updatedPkg.codePathString = scanFile.toString();
6850                        updatedPkg.resourcePath = scanFile;
6851                        updatedPkg.resourcePathString = scanFile.toString();
6852                    }
6853                    updatedPkg.pkg = pkg;
6854                    updatedPkg.versionCode = pkg.mVersionCode;
6855
6856                    // Update the disabled system child packages to point to the package too.
6857                    final int childCount = updatedPkg.childPackageNames != null
6858                            ? updatedPkg.childPackageNames.size() : 0;
6859                    for (int i = 0; i < childCount; i++) {
6860                        String childPackageName = updatedPkg.childPackageNames.get(i);
6861                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6862                                childPackageName);
6863                        if (updatedChildPkg != null) {
6864                            updatedChildPkg.pkg = pkg;
6865                            updatedChildPkg.versionCode = pkg.mVersionCode;
6866                        }
6867                    }
6868
6869                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6870                            + scanFile + " ignored: updated version " + ps.versionCode
6871                            + " better than this " + pkg.mVersionCode);
6872                } else {
6873                    // The current app on the system partition is better than
6874                    // what we have updated to on the data partition; switch
6875                    // back to the system partition version.
6876                    // At this point, its safely assumed that package installation for
6877                    // apps in system partition will go through. If not there won't be a working
6878                    // version of the app
6879                    // writer
6880                    synchronized (mPackages) {
6881                        // Just remove the loaded entries from package lists.
6882                        mPackages.remove(ps.name);
6883                    }
6884
6885                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6886                            + " reverting from " + ps.codePathString
6887                            + ": new version " + pkg.mVersionCode
6888                            + " better than installed " + ps.versionCode);
6889
6890                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6891                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6892                    synchronized (mInstallLock) {
6893                        args.cleanUpResourcesLI();
6894                    }
6895                    synchronized (mPackages) {
6896                        mSettings.enableSystemPackageLPw(ps.name);
6897                    }
6898                    updatedPkgBetter = true;
6899                }
6900            }
6901        }
6902
6903        if (updatedPkg != null) {
6904            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6905            // initially
6906            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6907
6908            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6909            // flag set initially
6910            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6911                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6912            }
6913        }
6914
6915        // Verify certificates against what was last scanned
6916        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6917
6918        /*
6919         * A new system app appeared, but we already had a non-system one of the
6920         * same name installed earlier.
6921         */
6922        boolean shouldHideSystemApp = false;
6923        if (updatedPkg == null && ps != null
6924                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6925            /*
6926             * Check to make sure the signatures match first. If they don't,
6927             * wipe the installed application and its data.
6928             */
6929            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6930                    != PackageManager.SIGNATURE_MATCH) {
6931                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6932                        + " signatures don't match existing userdata copy; removing");
6933                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6934                        "scanPackageInternalLI")) {
6935                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6936                }
6937                ps = null;
6938            } else {
6939                /*
6940                 * If the newly-added system app is an older version than the
6941                 * already installed version, hide it. It will be scanned later
6942                 * and re-added like an update.
6943                 */
6944                if (pkg.mVersionCode <= ps.versionCode) {
6945                    shouldHideSystemApp = true;
6946                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6947                            + " but new version " + pkg.mVersionCode + " better than installed "
6948                            + ps.versionCode + "; hiding system");
6949                } else {
6950                    /*
6951                     * The newly found system app is a newer version that the
6952                     * one previously installed. Simply remove the
6953                     * already-installed application and replace it with our own
6954                     * while keeping the application data.
6955                     */
6956                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6957                            + " reverting from " + ps.codePathString + ": new version "
6958                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6959                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6960                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6961                    synchronized (mInstallLock) {
6962                        args.cleanUpResourcesLI();
6963                    }
6964                }
6965            }
6966        }
6967
6968        // The apk is forward locked (not public) if its code and resources
6969        // are kept in different files. (except for app in either system or
6970        // vendor path).
6971        // TODO grab this value from PackageSettings
6972        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6973            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6974                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6975            }
6976        }
6977
6978        // TODO: extend to support forward-locked splits
6979        String resourcePath = null;
6980        String baseResourcePath = null;
6981        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6982            if (ps != null && ps.resourcePathString != null) {
6983                resourcePath = ps.resourcePathString;
6984                baseResourcePath = ps.resourcePathString;
6985            } else {
6986                // Should not happen at all. Just log an error.
6987                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6988            }
6989        } else {
6990            resourcePath = pkg.codePath;
6991            baseResourcePath = pkg.baseCodePath;
6992        }
6993
6994        // Set application objects path explicitly.
6995        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6996        pkg.setApplicationInfoCodePath(pkg.codePath);
6997        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6998        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6999        pkg.setApplicationInfoResourcePath(resourcePath);
7000        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7001        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7002
7003        // Note that we invoke the following method only if we are about to unpack an application
7004        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7005                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7006
7007        /*
7008         * If the system app should be overridden by a previously installed
7009         * data, hide the system app now and let the /data/app scan pick it up
7010         * again.
7011         */
7012        if (shouldHideSystemApp) {
7013            synchronized (mPackages) {
7014                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7015            }
7016        }
7017
7018        return scannedPkg;
7019    }
7020
7021    private static String fixProcessName(String defProcessName,
7022            String processName, int uid) {
7023        if (processName == null) {
7024            return defProcessName;
7025        }
7026        return processName;
7027    }
7028
7029    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7030            throws PackageManagerException {
7031        if (pkgSetting.signatures.mSignatures != null) {
7032            // Already existing package. Make sure signatures match
7033            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7034                    == PackageManager.SIGNATURE_MATCH;
7035            if (!match) {
7036                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7037                        == PackageManager.SIGNATURE_MATCH;
7038            }
7039            if (!match) {
7040                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7041                        == PackageManager.SIGNATURE_MATCH;
7042            }
7043            if (!match) {
7044                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7045                        + pkg.packageName + " signatures do not match the "
7046                        + "previously installed version; ignoring!");
7047            }
7048        }
7049
7050        // Check for shared user signatures
7051        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7052            // Already existing package. Make sure signatures match
7053            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7054                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7055            if (!match) {
7056                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7057                        == PackageManager.SIGNATURE_MATCH;
7058            }
7059            if (!match) {
7060                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7061                        == PackageManager.SIGNATURE_MATCH;
7062            }
7063            if (!match) {
7064                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7065                        "Package " + pkg.packageName
7066                        + " has no signatures that match those in shared user "
7067                        + pkgSetting.sharedUser.name + "; ignoring!");
7068            }
7069        }
7070    }
7071
7072    /**
7073     * Enforces that only the system UID or root's UID can call a method exposed
7074     * via Binder.
7075     *
7076     * @param message used as message if SecurityException is thrown
7077     * @throws SecurityException if the caller is not system or root
7078     */
7079    private static final void enforceSystemOrRoot(String message) {
7080        final int uid = Binder.getCallingUid();
7081        if (uid != Process.SYSTEM_UID && uid != 0) {
7082            throw new SecurityException(message);
7083        }
7084    }
7085
7086    @Override
7087    public void performFstrimIfNeeded() {
7088        enforceSystemOrRoot("Only the system can request fstrim");
7089
7090        // Before everything else, see whether we need to fstrim.
7091        try {
7092            IMountService ms = PackageHelper.getMountService();
7093            if (ms != null) {
7094                final boolean isUpgrade = isUpgrade();
7095                boolean doTrim = isUpgrade;
7096                if (doTrim) {
7097                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7098                } else {
7099                    final long interval = android.provider.Settings.Global.getLong(
7100                            mContext.getContentResolver(),
7101                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7102                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7103                    if (interval > 0) {
7104                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7105                        if (timeSinceLast > interval) {
7106                            doTrim = true;
7107                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7108                                    + "; running immediately");
7109                        }
7110                    }
7111                }
7112                if (doTrim) {
7113                    if (!isFirstBoot()) {
7114                        try {
7115                            ActivityManagerNative.getDefault().showBootMessage(
7116                                    mContext.getResources().getString(
7117                                            R.string.android_upgrading_fstrim), true);
7118                        } catch (RemoteException e) {
7119                        }
7120                    }
7121                    ms.runMaintenance();
7122                }
7123            } else {
7124                Slog.e(TAG, "Mount service unavailable!");
7125            }
7126        } catch (RemoteException e) {
7127            // Can't happen; MountService is local
7128        }
7129    }
7130
7131    @Override
7132    public void updatePackagesIfNeeded() {
7133        enforceSystemOrRoot("Only the system can request package update");
7134
7135        // We need to re-extract after an OTA.
7136        boolean causeUpgrade = isUpgrade();
7137
7138        // First boot or factory reset.
7139        // Note: we also handle devices that are upgrading to N right now as if it is their
7140        //       first boot, as they do not have profile data.
7141        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7142
7143        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7144        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7145
7146        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7147            return;
7148        }
7149
7150        List<PackageParser.Package> pkgs;
7151        synchronized (mPackages) {
7152            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7153        }
7154
7155        int curr = 0;
7156        int total = pkgs.size();
7157        for (PackageParser.Package pkg : pkgs) {
7158            curr++;
7159
7160            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7161                if (DEBUG_DEXOPT) {
7162                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7163                }
7164                continue;
7165            }
7166
7167            if (DEBUG_DEXOPT) {
7168                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7169            }
7170
7171            if (!isFirstBoot()) {
7172                try {
7173                    ActivityManagerNative.getDefault().showBootMessage(
7174                            mContext.getResources().getString(R.string.android_upgrading_apk,
7175                                    curr, total), true);
7176                } catch (RemoteException e) {
7177                }
7178            }
7179
7180            performDexOpt(pkg.packageName,
7181                    null /* instructionSet */,
7182                    true /* checkProfiles */,
7183                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7184                    false /* force */);
7185        }
7186    }
7187
7188    @Override
7189    public void notifyPackageUse(String packageName, int reason) {
7190        synchronized (mPackages) {
7191            PackageParser.Package p = mPackages.get(packageName);
7192            if (p == null) {
7193                return;
7194            }
7195            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7196        }
7197    }
7198
7199    // TODO: this is not used nor needed. Delete it.
7200    @Override
7201    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7202        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7203                getFullCompilerFilter(), false /* force */);
7204    }
7205
7206    @Override
7207    public boolean performDexOpt(String packageName, String instructionSet,
7208            boolean checkProfiles, int compileReason, boolean force) {
7209        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7210                getCompilerFilterForReason(compileReason), force);
7211    }
7212
7213    @Override
7214    public boolean performDexOptMode(String packageName, String instructionSet,
7215            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7216        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7217                targetCompilerFilter, force);
7218    }
7219
7220    private boolean performDexOptTraced(String packageName, String instructionSet,
7221                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7222        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7223        try {
7224            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7225                    targetCompilerFilter, force);
7226        } finally {
7227            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7228        }
7229    }
7230
7231    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7232    // if the package can now be considered up to date for the given filter.
7233    private boolean performDexOptInternal(String packageName, String instructionSet,
7234                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7235        PackageParser.Package p;
7236        final String targetInstructionSet;
7237        synchronized (mPackages) {
7238            p = mPackages.get(packageName);
7239            if (p == null) {
7240                return false;
7241            }
7242            mPackageUsage.write(false);
7243
7244            targetInstructionSet = instructionSet != null ? instructionSet :
7245                    getPrimaryInstructionSet(p.applicationInfo);
7246        }
7247        long callingId = Binder.clearCallingIdentity();
7248        try {
7249            synchronized (mInstallLock) {
7250                final String[] instructionSets = new String[] { targetInstructionSet };
7251                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7252                        checkProfiles, targetCompilerFilter, force);
7253                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7254            }
7255        } finally {
7256            Binder.restoreCallingIdentity(callingId);
7257        }
7258    }
7259
7260    public ArraySet<String> getOptimizablePackages() {
7261        ArraySet<String> pkgs = new ArraySet<String>();
7262        synchronized (mPackages) {
7263            for (PackageParser.Package p : mPackages.values()) {
7264                if (PackageDexOptimizer.canOptimizePackage(p)) {
7265                    pkgs.add(p.packageName);
7266                }
7267            }
7268        }
7269        return pkgs;
7270    }
7271
7272    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7273            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7274            boolean force) {
7275        // Select the dex optimizer based on the force parameter.
7276        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7277        //       allocate an object here.
7278        PackageDexOptimizer pdo = force
7279                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7280                : mPackageDexOptimizer;
7281
7282        // Optimize all dependencies first. Note: we ignore the return value and march on
7283        // on errors.
7284        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7285        if (!deps.isEmpty()) {
7286            for (PackageParser.Package depPackage : deps) {
7287                // TODO: Analyze and investigate if we (should) profile libraries.
7288                // Currently this will do a full compilation of the library by default.
7289                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7290                        false /* checkProfiles */,
7291                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7292            }
7293        }
7294
7295        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7296                targetCompilerFilter);
7297    }
7298
7299    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7300        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7301            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7302            Set<String> collectedNames = new HashSet<>();
7303            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7304
7305            retValue.remove(p);
7306
7307            return retValue;
7308        } else {
7309            return Collections.emptyList();
7310        }
7311    }
7312
7313    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7314            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7315        if (!collectedNames.contains(p.packageName)) {
7316            collectedNames.add(p.packageName);
7317            collected.add(p);
7318
7319            if (p.usesLibraries != null) {
7320                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7321            }
7322            if (p.usesOptionalLibraries != null) {
7323                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7324                        collectedNames);
7325            }
7326        }
7327    }
7328
7329    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7330            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7331        for (String libName : libs) {
7332            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7333            if (libPkg != null) {
7334                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7335            }
7336        }
7337    }
7338
7339    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7340        synchronized (mPackages) {
7341            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7342            if (lib != null && lib.apk != null) {
7343                return mPackages.get(lib.apk);
7344            }
7345        }
7346        return null;
7347    }
7348
7349    public void shutdown() {
7350        mPackageUsage.write(true);
7351    }
7352
7353    @Override
7354    public void forceDexOpt(String packageName) {
7355        enforceSystemOrRoot("forceDexOpt");
7356
7357        PackageParser.Package pkg;
7358        synchronized (mPackages) {
7359            pkg = mPackages.get(packageName);
7360            if (pkg == null) {
7361                throw new IllegalArgumentException("Unknown package: " + packageName);
7362            }
7363        }
7364
7365        synchronized (mInstallLock) {
7366            final String[] instructionSets = new String[] {
7367                    getPrimaryInstructionSet(pkg.applicationInfo) };
7368
7369            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7370
7371            // Whoever is calling forceDexOpt wants a fully compiled package.
7372            // Don't use profiles since that may cause compilation to be skipped.
7373            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7374                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7375                    true /* force */);
7376
7377            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7378            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7379                throw new IllegalStateException("Failed to dexopt: " + res);
7380            }
7381        }
7382    }
7383
7384    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7385        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7386            Slog.w(TAG, "Unable to update from " + oldPkg.name
7387                    + " to " + newPkg.packageName
7388                    + ": old package not in system partition");
7389            return false;
7390        } else if (mPackages.get(oldPkg.name) != null) {
7391            Slog.w(TAG, "Unable to update from " + oldPkg.name
7392                    + " to " + newPkg.packageName
7393                    + ": old package still exists");
7394            return false;
7395        }
7396        return true;
7397    }
7398
7399    void removeCodePathLI(File codePath) {
7400        if (codePath.isDirectory()) {
7401            try {
7402                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7403            } catch (InstallerException e) {
7404                Slog.w(TAG, "Failed to remove code path", e);
7405            }
7406        } else {
7407            codePath.delete();
7408        }
7409    }
7410
7411    private int[] resolveUserIds(int userId) {
7412        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7413    }
7414
7415    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7416        if (pkg == null) {
7417            Slog.wtf(TAG, "Package was null!", new Throwable());
7418            return;
7419        }
7420        clearAppDataLeafLIF(pkg, userId, flags);
7421        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7422        for (int i = 0; i < childCount; i++) {
7423            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7424        }
7425    }
7426
7427    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7428        final PackageSetting ps;
7429        synchronized (mPackages) {
7430            ps = mSettings.mPackages.get(pkg.packageName);
7431        }
7432        for (int realUserId : resolveUserIds(userId)) {
7433            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7434            try {
7435                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7436                        ceDataInode);
7437            } catch (InstallerException e) {
7438                Slog.w(TAG, String.valueOf(e));
7439            }
7440        }
7441    }
7442
7443    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7444        if (pkg == null) {
7445            Slog.wtf(TAG, "Package was null!", new Throwable());
7446            return;
7447        }
7448        destroyAppDataLeafLIF(pkg, userId, flags);
7449        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7450        for (int i = 0; i < childCount; i++) {
7451            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7452        }
7453    }
7454
7455    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7456        final PackageSetting ps;
7457        synchronized (mPackages) {
7458            ps = mSettings.mPackages.get(pkg.packageName);
7459        }
7460        for (int realUserId : resolveUserIds(userId)) {
7461            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7462            try {
7463                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7464                        ceDataInode);
7465            } catch (InstallerException e) {
7466                Slog.w(TAG, String.valueOf(e));
7467            }
7468        }
7469    }
7470
7471    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7472        if (pkg == null) {
7473            Slog.wtf(TAG, "Package was null!", new Throwable());
7474            return;
7475        }
7476        destroyAppProfilesLeafLIF(pkg);
7477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7478        for (int i = 0; i < childCount; i++) {
7479            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7480        }
7481    }
7482
7483    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7484        try {
7485            mInstaller.destroyAppProfiles(pkg.packageName);
7486        } catch (InstallerException e) {
7487            Slog.w(TAG, String.valueOf(e));
7488        }
7489    }
7490
7491    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7492        if (pkg == null) {
7493            Slog.wtf(TAG, "Package was null!", new Throwable());
7494            return;
7495        }
7496        clearAppProfilesLeafLIF(pkg);
7497        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7498        for (int i = 0; i < childCount; i++) {
7499            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7500        }
7501    }
7502
7503    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7504        try {
7505            mInstaller.clearAppProfiles(pkg.packageName);
7506        } catch (InstallerException e) {
7507            Slog.w(TAG, String.valueOf(e));
7508        }
7509    }
7510
7511    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7512            long lastUpdateTime) {
7513        // Set parent install/update time
7514        PackageSetting ps = (PackageSetting) pkg.mExtras;
7515        if (ps != null) {
7516            ps.firstInstallTime = firstInstallTime;
7517            ps.lastUpdateTime = lastUpdateTime;
7518        }
7519        // Set children install/update time
7520        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7521        for (int i = 0; i < childCount; i++) {
7522            PackageParser.Package childPkg = pkg.childPackages.get(i);
7523            ps = (PackageSetting) childPkg.mExtras;
7524            if (ps != null) {
7525                ps.firstInstallTime = firstInstallTime;
7526                ps.lastUpdateTime = lastUpdateTime;
7527            }
7528        }
7529    }
7530
7531    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7532            PackageParser.Package changingLib) {
7533        if (file.path != null) {
7534            usesLibraryFiles.add(file.path);
7535            return;
7536        }
7537        PackageParser.Package p = mPackages.get(file.apk);
7538        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7539            // If we are doing this while in the middle of updating a library apk,
7540            // then we need to make sure to use that new apk for determining the
7541            // dependencies here.  (We haven't yet finished committing the new apk
7542            // to the package manager state.)
7543            if (p == null || p.packageName.equals(changingLib.packageName)) {
7544                p = changingLib;
7545            }
7546        }
7547        if (p != null) {
7548            usesLibraryFiles.addAll(p.getAllCodePaths());
7549        }
7550    }
7551
7552    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7553            PackageParser.Package changingLib) throws PackageManagerException {
7554        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7555            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7556            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7557            for (int i=0; i<N; i++) {
7558                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7559                if (file == null) {
7560                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7561                            "Package " + pkg.packageName + " requires unavailable shared library "
7562                            + pkg.usesLibraries.get(i) + "; failing!");
7563                }
7564                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7565            }
7566            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7567            for (int i=0; i<N; i++) {
7568                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7569                if (file == null) {
7570                    Slog.w(TAG, "Package " + pkg.packageName
7571                            + " desires unavailable shared library "
7572                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7573                } else {
7574                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7575                }
7576            }
7577            N = usesLibraryFiles.size();
7578            if (N > 0) {
7579                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7580            } else {
7581                pkg.usesLibraryFiles = null;
7582            }
7583        }
7584    }
7585
7586    private static boolean hasString(List<String> list, List<String> which) {
7587        if (list == null) {
7588            return false;
7589        }
7590        for (int i=list.size()-1; i>=0; i--) {
7591            for (int j=which.size()-1; j>=0; j--) {
7592                if (which.get(j).equals(list.get(i))) {
7593                    return true;
7594                }
7595            }
7596        }
7597        return false;
7598    }
7599
7600    private void updateAllSharedLibrariesLPw() {
7601        for (PackageParser.Package pkg : mPackages.values()) {
7602            try {
7603                updateSharedLibrariesLPw(pkg, null);
7604            } catch (PackageManagerException e) {
7605                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7606            }
7607        }
7608    }
7609
7610    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7611            PackageParser.Package changingPkg) {
7612        ArrayList<PackageParser.Package> res = null;
7613        for (PackageParser.Package pkg : mPackages.values()) {
7614            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7615                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7616                if (res == null) {
7617                    res = new ArrayList<PackageParser.Package>();
7618                }
7619                res.add(pkg);
7620                try {
7621                    updateSharedLibrariesLPw(pkg, changingPkg);
7622                } catch (PackageManagerException e) {
7623                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7624                }
7625            }
7626        }
7627        return res;
7628    }
7629
7630    /**
7631     * Derive the value of the {@code cpuAbiOverride} based on the provided
7632     * value and an optional stored value from the package settings.
7633     */
7634    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7635        String cpuAbiOverride = null;
7636
7637        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7638            cpuAbiOverride = null;
7639        } else if (abiOverride != null) {
7640            cpuAbiOverride = abiOverride;
7641        } else if (settings != null) {
7642            cpuAbiOverride = settings.cpuAbiOverrideString;
7643        }
7644
7645        return cpuAbiOverride;
7646    }
7647
7648    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7649            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7650                    throws PackageManagerException {
7651        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7652        // If the package has children and this is the first dive in the function
7653        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7654        // whether all packages (parent and children) would be successfully scanned
7655        // before the actual scan since scanning mutates internal state and we want
7656        // to atomically install the package and its children.
7657        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7658            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7659                scanFlags |= SCAN_CHECK_ONLY;
7660            }
7661        } else {
7662            scanFlags &= ~SCAN_CHECK_ONLY;
7663        }
7664
7665        final PackageParser.Package scannedPkg;
7666        try {
7667            // Scan the parent
7668            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7669            // Scan the children
7670            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7671            for (int i = 0; i < childCount; i++) {
7672                PackageParser.Package childPkg = pkg.childPackages.get(i);
7673                scanPackageLI(childPkg, policyFlags,
7674                        scanFlags, currentTime, user);
7675            }
7676        } finally {
7677            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7678        }
7679
7680        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7681            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7682        }
7683
7684        return scannedPkg;
7685    }
7686
7687    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7688            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7689        boolean success = false;
7690        try {
7691            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7692                    currentTime, user);
7693            success = true;
7694            return res;
7695        } finally {
7696            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7697                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7698                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7699                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7700                destroyAppProfilesLIF(pkg);
7701            }
7702        }
7703    }
7704
7705    /**
7706     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7707     */
7708    private static boolean apkHasCode(String fileName) {
7709        StrictJarFile jarFile = null;
7710        try {
7711            jarFile = new StrictJarFile(fileName,
7712                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7713            return jarFile.findEntry("classes.dex") != null;
7714        } catch (IOException ignore) {
7715        } finally {
7716            try {
7717                jarFile.close();
7718            } catch (IOException ignore) {}
7719        }
7720        return false;
7721    }
7722
7723    /**
7724     * Enforces code policy for the package. This ensures that if an APK has
7725     * declared hasCode="true" in its manifest that the APK actually contains
7726     * code.
7727     *
7728     * @throws PackageManagerException If bytecode could not be found when it should exist
7729     */
7730    private static void enforceCodePolicy(PackageParser.Package pkg)
7731            throws PackageManagerException {
7732        final boolean shouldHaveCode =
7733                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7734        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7735            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7736                    "Package " + pkg.baseCodePath + " code is missing");
7737        }
7738
7739        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7740            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7741                final boolean splitShouldHaveCode =
7742                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7743                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7744                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7745                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7746                }
7747            }
7748        }
7749    }
7750
7751    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7752            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7753            throws PackageManagerException {
7754        final File scanFile = new File(pkg.codePath);
7755        if (pkg.applicationInfo.getCodePath() == null ||
7756                pkg.applicationInfo.getResourcePath() == null) {
7757            // Bail out. The resource and code paths haven't been set.
7758            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7759                    "Code and resource paths haven't been set correctly");
7760        }
7761
7762        // Apply policy
7763        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7764            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7765            if (pkg.applicationInfo.isDirectBootAware()) {
7766                // we're direct boot aware; set for all components
7767                for (PackageParser.Service s : pkg.services) {
7768                    s.info.encryptionAware = s.info.directBootAware = true;
7769                }
7770                for (PackageParser.Provider p : pkg.providers) {
7771                    p.info.encryptionAware = p.info.directBootAware = true;
7772                }
7773                for (PackageParser.Activity a : pkg.activities) {
7774                    a.info.encryptionAware = a.info.directBootAware = true;
7775                }
7776                for (PackageParser.Activity r : pkg.receivers) {
7777                    r.info.encryptionAware = r.info.directBootAware = true;
7778                }
7779            }
7780        } else {
7781            // Only allow system apps to be flagged as core apps.
7782            pkg.coreApp = false;
7783            // clear flags not applicable to regular apps
7784            pkg.applicationInfo.privateFlags &=
7785                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7786            pkg.applicationInfo.privateFlags &=
7787                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7788        }
7789        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7790
7791        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7792            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7793        }
7794
7795        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7796            enforceCodePolicy(pkg);
7797        }
7798
7799        if (mCustomResolverComponentName != null &&
7800                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7801            setUpCustomResolverActivity(pkg);
7802        }
7803
7804        if (pkg.packageName.equals("android")) {
7805            synchronized (mPackages) {
7806                if (mAndroidApplication != null) {
7807                    Slog.w(TAG, "*************************************************");
7808                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7809                    Slog.w(TAG, " file=" + scanFile);
7810                    Slog.w(TAG, "*************************************************");
7811                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7812                            "Core android package being redefined.  Skipping.");
7813                }
7814
7815                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7816                    // Set up information for our fall-back user intent resolution activity.
7817                    mPlatformPackage = pkg;
7818                    pkg.mVersionCode = mSdkVersion;
7819                    mAndroidApplication = pkg.applicationInfo;
7820
7821                    if (!mResolverReplaced) {
7822                        mResolveActivity.applicationInfo = mAndroidApplication;
7823                        mResolveActivity.name = ResolverActivity.class.getName();
7824                        mResolveActivity.packageName = mAndroidApplication.packageName;
7825                        mResolveActivity.processName = "system:ui";
7826                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7827                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7828                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7829                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7830                        mResolveActivity.exported = true;
7831                        mResolveActivity.enabled = true;
7832                        mResolveInfo.activityInfo = mResolveActivity;
7833                        mResolveInfo.priority = 0;
7834                        mResolveInfo.preferredOrder = 0;
7835                        mResolveInfo.match = 0;
7836                        mResolveComponentName = new ComponentName(
7837                                mAndroidApplication.packageName, mResolveActivity.name);
7838                    }
7839                }
7840            }
7841        }
7842
7843        if (DEBUG_PACKAGE_SCANNING) {
7844            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7845                Log.d(TAG, "Scanning package " + pkg.packageName);
7846        }
7847
7848        synchronized (mPackages) {
7849            if (mPackages.containsKey(pkg.packageName)
7850                    || mSharedLibraries.containsKey(pkg.packageName)) {
7851                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7852                        "Application package " + pkg.packageName
7853                                + " already installed.  Skipping duplicate.");
7854            }
7855
7856            // If we're only installing presumed-existing packages, require that the
7857            // scanned APK is both already known and at the path previously established
7858            // for it.  Previously unknown packages we pick up normally, but if we have an
7859            // a priori expectation about this package's install presence, enforce it.
7860            // With a singular exception for new system packages. When an OTA contains
7861            // a new system package, we allow the codepath to change from a system location
7862            // to the user-installed location. If we don't allow this change, any newer,
7863            // user-installed version of the application will be ignored.
7864            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7865                if (mExpectingBetter.containsKey(pkg.packageName)) {
7866                    logCriticalInfo(Log.WARN,
7867                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7868                } else {
7869                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7870                    if (known != null) {
7871                        if (DEBUG_PACKAGE_SCANNING) {
7872                            Log.d(TAG, "Examining " + pkg.codePath
7873                                    + " and requiring known paths " + known.codePathString
7874                                    + " & " + known.resourcePathString);
7875                        }
7876                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7877                                || !pkg.applicationInfo.getResourcePath().equals(
7878                                known.resourcePathString)) {
7879                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7880                                    "Application package " + pkg.packageName
7881                                            + " found at " + pkg.applicationInfo.getCodePath()
7882                                            + " but expected at " + known.codePathString
7883                                            + "; ignoring.");
7884                        }
7885                    }
7886                }
7887            }
7888        }
7889
7890        // Initialize package source and resource directories
7891        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7892        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7893
7894        SharedUserSetting suid = null;
7895        PackageSetting pkgSetting = null;
7896
7897        if (!isSystemApp(pkg)) {
7898            // Only system apps can use these features.
7899            pkg.mOriginalPackages = null;
7900            pkg.mRealPackage = null;
7901            pkg.mAdoptPermissions = null;
7902        }
7903
7904        // Getting the package setting may have a side-effect, so if we
7905        // are only checking if scan would succeed, stash a copy of the
7906        // old setting to restore at the end.
7907        PackageSetting nonMutatedPs = null;
7908
7909        // writer
7910        synchronized (mPackages) {
7911            if (pkg.mSharedUserId != null) {
7912                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7913                if (suid == null) {
7914                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7915                            "Creating application package " + pkg.packageName
7916                            + " for shared user failed");
7917                }
7918                if (DEBUG_PACKAGE_SCANNING) {
7919                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7920                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7921                                + "): packages=" + suid.packages);
7922                }
7923            }
7924
7925            // Check if we are renaming from an original package name.
7926            PackageSetting origPackage = null;
7927            String realName = null;
7928            if (pkg.mOriginalPackages != null) {
7929                // This package may need to be renamed to a previously
7930                // installed name.  Let's check on that...
7931                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7932                if (pkg.mOriginalPackages.contains(renamed)) {
7933                    // This package had originally been installed as the
7934                    // original name, and we have already taken care of
7935                    // transitioning to the new one.  Just update the new
7936                    // one to continue using the old name.
7937                    realName = pkg.mRealPackage;
7938                    if (!pkg.packageName.equals(renamed)) {
7939                        // Callers into this function may have already taken
7940                        // care of renaming the package; only do it here if
7941                        // it is not already done.
7942                        pkg.setPackageName(renamed);
7943                    }
7944
7945                } else {
7946                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7947                        if ((origPackage = mSettings.peekPackageLPr(
7948                                pkg.mOriginalPackages.get(i))) != null) {
7949                            // We do have the package already installed under its
7950                            // original name...  should we use it?
7951                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7952                                // New package is not compatible with original.
7953                                origPackage = null;
7954                                continue;
7955                            } else if (origPackage.sharedUser != null) {
7956                                // Make sure uid is compatible between packages.
7957                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7958                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7959                                            + " to " + pkg.packageName + ": old uid "
7960                                            + origPackage.sharedUser.name
7961                                            + " differs from " + pkg.mSharedUserId);
7962                                    origPackage = null;
7963                                    continue;
7964                                }
7965                                // TODO: Add case when shared user id is added [b/28144775]
7966                            } else {
7967                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7968                                        + pkg.packageName + " to old name " + origPackage.name);
7969                            }
7970                            break;
7971                        }
7972                    }
7973                }
7974            }
7975
7976            if (mTransferedPackages.contains(pkg.packageName)) {
7977                Slog.w(TAG, "Package " + pkg.packageName
7978                        + " was transferred to another, but its .apk remains");
7979            }
7980
7981            // See comments in nonMutatedPs declaration
7982            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7983                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7984                if (foundPs != null) {
7985                    nonMutatedPs = new PackageSetting(foundPs);
7986                }
7987            }
7988
7989            // Just create the setting, don't add it yet. For already existing packages
7990            // the PkgSetting exists already and doesn't have to be created.
7991            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7992                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7993                    pkg.applicationInfo.primaryCpuAbi,
7994                    pkg.applicationInfo.secondaryCpuAbi,
7995                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7996                    user, false);
7997            if (pkgSetting == null) {
7998                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7999                        "Creating application package " + pkg.packageName + " failed");
8000            }
8001
8002            if (pkgSetting.origPackage != null) {
8003                // If we are first transitioning from an original package,
8004                // fix up the new package's name now.  We need to do this after
8005                // looking up the package under its new name, so getPackageLP
8006                // can take care of fiddling things correctly.
8007                pkg.setPackageName(origPackage.name);
8008
8009                // File a report about this.
8010                String msg = "New package " + pkgSetting.realName
8011                        + " renamed to replace old package " + pkgSetting.name;
8012                reportSettingsProblem(Log.WARN, msg);
8013
8014                // Make a note of it.
8015                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8016                    mTransferedPackages.add(origPackage.name);
8017                }
8018
8019                // No longer need to retain this.
8020                pkgSetting.origPackage = null;
8021            }
8022
8023            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8024                // Make a note of it.
8025                mTransferedPackages.add(pkg.packageName);
8026            }
8027
8028            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8029                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8030            }
8031
8032            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8033                // Check all shared libraries and map to their actual file path.
8034                // We only do this here for apps not on a system dir, because those
8035                // are the only ones that can fail an install due to this.  We
8036                // will take care of the system apps by updating all of their
8037                // library paths after the scan is done.
8038                updateSharedLibrariesLPw(pkg, null);
8039            }
8040
8041            if (mFoundPolicyFile) {
8042                SELinuxMMAC.assignSeinfoValue(pkg);
8043            }
8044
8045            pkg.applicationInfo.uid = pkgSetting.appId;
8046            pkg.mExtras = pkgSetting;
8047            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8048                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8049                    // We just determined the app is signed correctly, so bring
8050                    // over the latest parsed certs.
8051                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8052                } else {
8053                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8054                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8055                                "Package " + pkg.packageName + " upgrade keys do not match the "
8056                                + "previously installed version");
8057                    } else {
8058                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8059                        String msg = "System package " + pkg.packageName
8060                            + " signature changed; retaining data.";
8061                        reportSettingsProblem(Log.WARN, msg);
8062                    }
8063                }
8064            } else {
8065                try {
8066                    verifySignaturesLP(pkgSetting, pkg);
8067                    // We just determined the app is signed correctly, so bring
8068                    // over the latest parsed certs.
8069                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8070                } catch (PackageManagerException e) {
8071                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8072                        throw e;
8073                    }
8074                    // The signature has changed, but this package is in the system
8075                    // image...  let's recover!
8076                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8077                    // However...  if this package is part of a shared user, but it
8078                    // doesn't match the signature of the shared user, let's fail.
8079                    // What this means is that you can't change the signatures
8080                    // associated with an overall shared user, which doesn't seem all
8081                    // that unreasonable.
8082                    if (pkgSetting.sharedUser != null) {
8083                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8084                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8085                            throw new PackageManagerException(
8086                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8087                                            "Signature mismatch for shared user: "
8088                                            + pkgSetting.sharedUser);
8089                        }
8090                    }
8091                    // File a report about this.
8092                    String msg = "System package " + pkg.packageName
8093                        + " signature changed; retaining data.";
8094                    reportSettingsProblem(Log.WARN, msg);
8095                }
8096            }
8097            // Verify that this new package doesn't have any content providers
8098            // that conflict with existing packages.  Only do this if the
8099            // package isn't already installed, since we don't want to break
8100            // things that are installed.
8101            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8102                final int N = pkg.providers.size();
8103                int i;
8104                for (i=0; i<N; i++) {
8105                    PackageParser.Provider p = pkg.providers.get(i);
8106                    if (p.info.authority != null) {
8107                        String names[] = p.info.authority.split(";");
8108                        for (int j = 0; j < names.length; j++) {
8109                            if (mProvidersByAuthority.containsKey(names[j])) {
8110                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8111                                final String otherPackageName =
8112                                        ((other != null && other.getComponentName() != null) ?
8113                                                other.getComponentName().getPackageName() : "?");
8114                                throw new PackageManagerException(
8115                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8116                                                "Can't install because provider name " + names[j]
8117                                                + " (in package " + pkg.applicationInfo.packageName
8118                                                + ") is already used by " + otherPackageName);
8119                            }
8120                        }
8121                    }
8122                }
8123            }
8124
8125            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8126                // This package wants to adopt ownership of permissions from
8127                // another package.
8128                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8129                    final String origName = pkg.mAdoptPermissions.get(i);
8130                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8131                    if (orig != null) {
8132                        if (verifyPackageUpdateLPr(orig, pkg)) {
8133                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8134                                    + pkg.packageName);
8135                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8136                        }
8137                    }
8138                }
8139            }
8140        }
8141
8142        final String pkgName = pkg.packageName;
8143
8144        final long scanFileTime = scanFile.lastModified();
8145        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8146        pkg.applicationInfo.processName = fixProcessName(
8147                pkg.applicationInfo.packageName,
8148                pkg.applicationInfo.processName,
8149                pkg.applicationInfo.uid);
8150
8151        if (pkg != mPlatformPackage) {
8152            // Get all of our default paths setup
8153            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8154        }
8155
8156        final String path = scanFile.getPath();
8157        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8158
8159        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8160            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8161
8162            // Some system apps still use directory structure for native libraries
8163            // in which case we might end up not detecting abi solely based on apk
8164            // structure. Try to detect abi based on directory structure.
8165            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8166                    pkg.applicationInfo.primaryCpuAbi == null) {
8167                setBundledAppAbisAndRoots(pkg, pkgSetting);
8168                setNativeLibraryPaths(pkg);
8169            }
8170
8171        } else {
8172            if ((scanFlags & SCAN_MOVE) != 0) {
8173                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8174                // but we already have this packages package info in the PackageSetting. We just
8175                // use that and derive the native library path based on the new codepath.
8176                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8177                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8178            }
8179
8180            // Set native library paths again. For moves, the path will be updated based on the
8181            // ABIs we've determined above. For non-moves, the path will be updated based on the
8182            // ABIs we determined during compilation, but the path will depend on the final
8183            // package path (after the rename away from the stage path).
8184            setNativeLibraryPaths(pkg);
8185        }
8186
8187        // This is a special case for the "system" package, where the ABI is
8188        // dictated by the zygote configuration (and init.rc). We should keep track
8189        // of this ABI so that we can deal with "normal" applications that run under
8190        // the same UID correctly.
8191        if (mPlatformPackage == pkg) {
8192            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8193                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8194        }
8195
8196        // If there's a mismatch between the abi-override in the package setting
8197        // and the abiOverride specified for the install. Warn about this because we
8198        // would've already compiled the app without taking the package setting into
8199        // account.
8200        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8201            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8202                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8203                        " for package " + pkg.packageName);
8204            }
8205        }
8206
8207        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8208        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8209        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8210
8211        // Copy the derived override back to the parsed package, so that we can
8212        // update the package settings accordingly.
8213        pkg.cpuAbiOverride = cpuAbiOverride;
8214
8215        if (DEBUG_ABI_SELECTION) {
8216            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8217                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8218                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8219        }
8220
8221        // Push the derived path down into PackageSettings so we know what to
8222        // clean up at uninstall time.
8223        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8224
8225        if (DEBUG_ABI_SELECTION) {
8226            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8227                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8228                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8229        }
8230
8231        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8232            // We don't do this here during boot because we can do it all
8233            // at once after scanning all existing packages.
8234            //
8235            // We also do this *before* we perform dexopt on this package, so that
8236            // we can avoid redundant dexopts, and also to make sure we've got the
8237            // code and package path correct.
8238            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8239                    pkg, true /* boot complete */);
8240        }
8241
8242        if (mFactoryTest && pkg.requestedPermissions.contains(
8243                android.Manifest.permission.FACTORY_TEST)) {
8244            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8245        }
8246
8247        ArrayList<PackageParser.Package> clientLibPkgs = null;
8248
8249        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8250            if (nonMutatedPs != null) {
8251                synchronized (mPackages) {
8252                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8253                }
8254            }
8255            return pkg;
8256        }
8257
8258        // Only privileged apps and updated privileged apps can add child packages.
8259        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8260            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8261                throw new PackageManagerException("Only privileged apps and updated "
8262                        + "privileged apps can add child packages. Ignoring package "
8263                        + pkg.packageName);
8264            }
8265            final int childCount = pkg.childPackages.size();
8266            for (int i = 0; i < childCount; i++) {
8267                PackageParser.Package childPkg = pkg.childPackages.get(i);
8268                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8269                        childPkg.packageName)) {
8270                    throw new PackageManagerException("Cannot override a child package of "
8271                            + "another disabled system app. Ignoring package " + pkg.packageName);
8272                }
8273            }
8274        }
8275
8276        // writer
8277        synchronized (mPackages) {
8278            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8279                // Only system apps can add new shared libraries.
8280                if (pkg.libraryNames != null) {
8281                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8282                        String name = pkg.libraryNames.get(i);
8283                        boolean allowed = false;
8284                        if (pkg.isUpdatedSystemApp()) {
8285                            // New library entries can only be added through the
8286                            // system image.  This is important to get rid of a lot
8287                            // of nasty edge cases: for example if we allowed a non-
8288                            // system update of the app to add a library, then uninstalling
8289                            // the update would make the library go away, and assumptions
8290                            // we made such as through app install filtering would now
8291                            // have allowed apps on the device which aren't compatible
8292                            // with it.  Better to just have the restriction here, be
8293                            // conservative, and create many fewer cases that can negatively
8294                            // impact the user experience.
8295                            final PackageSetting sysPs = mSettings
8296                                    .getDisabledSystemPkgLPr(pkg.packageName);
8297                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8298                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8299                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8300                                        allowed = true;
8301                                        break;
8302                                    }
8303                                }
8304                            }
8305                        } else {
8306                            allowed = true;
8307                        }
8308                        if (allowed) {
8309                            if (!mSharedLibraries.containsKey(name)) {
8310                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8311                            } else if (!name.equals(pkg.packageName)) {
8312                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8313                                        + name + " already exists; skipping");
8314                            }
8315                        } else {
8316                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8317                                    + name + " that is not declared on system image; skipping");
8318                        }
8319                    }
8320                    if ((scanFlags & SCAN_BOOTING) == 0) {
8321                        // If we are not booting, we need to update any applications
8322                        // that are clients of our shared library.  If we are booting,
8323                        // this will all be done once the scan is complete.
8324                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8325                    }
8326                }
8327            }
8328        }
8329
8330        if ((scanFlags & SCAN_BOOTING) != 0) {
8331            // No apps can run during boot scan, so they don't need to be frozen
8332        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8333            // Caller asked to not kill app, so it's probably not frozen
8334        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8335            // Caller asked us to ignore frozen check for some reason; they
8336            // probably didn't know the package name
8337        } else {
8338            // We're doing major surgery on this package, so it better be frozen
8339            // right now to keep it from launching
8340            checkPackageFrozen(pkgName);
8341        }
8342
8343        // Also need to kill any apps that are dependent on the library.
8344        if (clientLibPkgs != null) {
8345            for (int i=0; i<clientLibPkgs.size(); i++) {
8346                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8347                killApplication(clientPkg.applicationInfo.packageName,
8348                        clientPkg.applicationInfo.uid, "update lib");
8349            }
8350        }
8351
8352        // Make sure we're not adding any bogus keyset info
8353        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8354        ksms.assertScannedPackageValid(pkg);
8355
8356        // writer
8357        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8358
8359        boolean createIdmapFailed = false;
8360        synchronized (mPackages) {
8361            // We don't expect installation to fail beyond this point
8362
8363            // Add the new setting to mSettings
8364            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8365            // Add the new setting to mPackages
8366            mPackages.put(pkg.applicationInfo.packageName, pkg);
8367            // Make sure we don't accidentally delete its data.
8368            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8369            while (iter.hasNext()) {
8370                PackageCleanItem item = iter.next();
8371                if (pkgName.equals(item.packageName)) {
8372                    iter.remove();
8373                }
8374            }
8375
8376            // Take care of first install / last update times.
8377            if (currentTime != 0) {
8378                if (pkgSetting.firstInstallTime == 0) {
8379                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8380                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8381                    pkgSetting.lastUpdateTime = currentTime;
8382                }
8383            } else if (pkgSetting.firstInstallTime == 0) {
8384                // We need *something*.  Take time time stamp of the file.
8385                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8386            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8387                if (scanFileTime != pkgSetting.timeStamp) {
8388                    // A package on the system image has changed; consider this
8389                    // to be an update.
8390                    pkgSetting.lastUpdateTime = scanFileTime;
8391                }
8392            }
8393
8394            // Add the package's KeySets to the global KeySetManagerService
8395            ksms.addScannedPackageLPw(pkg);
8396
8397            int N = pkg.providers.size();
8398            StringBuilder r = null;
8399            int i;
8400            for (i=0; i<N; i++) {
8401                PackageParser.Provider p = pkg.providers.get(i);
8402                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8403                        p.info.processName, pkg.applicationInfo.uid);
8404                mProviders.addProvider(p);
8405                p.syncable = p.info.isSyncable;
8406                if (p.info.authority != null) {
8407                    String names[] = p.info.authority.split(";");
8408                    p.info.authority = null;
8409                    for (int j = 0; j < names.length; j++) {
8410                        if (j == 1 && p.syncable) {
8411                            // We only want the first authority for a provider to possibly be
8412                            // syncable, so if we already added this provider using a different
8413                            // authority clear the syncable flag. We copy the provider before
8414                            // changing it because the mProviders object contains a reference
8415                            // to a provider that we don't want to change.
8416                            // Only do this for the second authority since the resulting provider
8417                            // object can be the same for all future authorities for this provider.
8418                            p = new PackageParser.Provider(p);
8419                            p.syncable = false;
8420                        }
8421                        if (!mProvidersByAuthority.containsKey(names[j])) {
8422                            mProvidersByAuthority.put(names[j], p);
8423                            if (p.info.authority == null) {
8424                                p.info.authority = names[j];
8425                            } else {
8426                                p.info.authority = p.info.authority + ";" + names[j];
8427                            }
8428                            if (DEBUG_PACKAGE_SCANNING) {
8429                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8430                                    Log.d(TAG, "Registered content provider: " + names[j]
8431                                            + ", className = " + p.info.name + ", isSyncable = "
8432                                            + p.info.isSyncable);
8433                            }
8434                        } else {
8435                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8436                            Slog.w(TAG, "Skipping provider name " + names[j] +
8437                                    " (in package " + pkg.applicationInfo.packageName +
8438                                    "): name already used by "
8439                                    + ((other != null && other.getComponentName() != null)
8440                                            ? other.getComponentName().getPackageName() : "?"));
8441                        }
8442                    }
8443                }
8444                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8445                    if (r == null) {
8446                        r = new StringBuilder(256);
8447                    } else {
8448                        r.append(' ');
8449                    }
8450                    r.append(p.info.name);
8451                }
8452            }
8453            if (r != null) {
8454                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8455            }
8456
8457            N = pkg.services.size();
8458            r = null;
8459            for (i=0; i<N; i++) {
8460                PackageParser.Service s = pkg.services.get(i);
8461                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8462                        s.info.processName, pkg.applicationInfo.uid);
8463                mServices.addService(s);
8464                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8465                    if (r == null) {
8466                        r = new StringBuilder(256);
8467                    } else {
8468                        r.append(' ');
8469                    }
8470                    r.append(s.info.name);
8471                }
8472            }
8473            if (r != null) {
8474                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8475            }
8476
8477            N = pkg.receivers.size();
8478            r = null;
8479            for (i=0; i<N; i++) {
8480                PackageParser.Activity a = pkg.receivers.get(i);
8481                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8482                        a.info.processName, pkg.applicationInfo.uid);
8483                mReceivers.addActivity(a, "receiver");
8484                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8485                    if (r == null) {
8486                        r = new StringBuilder(256);
8487                    } else {
8488                        r.append(' ');
8489                    }
8490                    r.append(a.info.name);
8491                }
8492            }
8493            if (r != null) {
8494                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8495            }
8496
8497            N = pkg.activities.size();
8498            r = null;
8499            for (i=0; i<N; i++) {
8500                PackageParser.Activity a = pkg.activities.get(i);
8501                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8502                        a.info.processName, pkg.applicationInfo.uid);
8503                mActivities.addActivity(a, "activity");
8504                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8505                    if (r == null) {
8506                        r = new StringBuilder(256);
8507                    } else {
8508                        r.append(' ');
8509                    }
8510                    r.append(a.info.name);
8511                }
8512            }
8513            if (r != null) {
8514                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8515            }
8516
8517            N = pkg.permissionGroups.size();
8518            r = null;
8519            for (i=0; i<N; i++) {
8520                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8521                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8522                if (cur == null) {
8523                    mPermissionGroups.put(pg.info.name, pg);
8524                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8525                        if (r == null) {
8526                            r = new StringBuilder(256);
8527                        } else {
8528                            r.append(' ');
8529                        }
8530                        r.append(pg.info.name);
8531                    }
8532                } else {
8533                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8534                            + pg.info.packageName + " ignored: original from "
8535                            + cur.info.packageName);
8536                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8537                        if (r == null) {
8538                            r = new StringBuilder(256);
8539                        } else {
8540                            r.append(' ');
8541                        }
8542                        r.append("DUP:");
8543                        r.append(pg.info.name);
8544                    }
8545                }
8546            }
8547            if (r != null) {
8548                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8549            }
8550
8551            N = pkg.permissions.size();
8552            r = null;
8553            for (i=0; i<N; i++) {
8554                PackageParser.Permission p = pkg.permissions.get(i);
8555
8556                // Assume by default that we did not install this permission into the system.
8557                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8558
8559                // Now that permission groups have a special meaning, we ignore permission
8560                // groups for legacy apps to prevent unexpected behavior. In particular,
8561                // permissions for one app being granted to someone just becase they happen
8562                // to be in a group defined by another app (before this had no implications).
8563                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8564                    p.group = mPermissionGroups.get(p.info.group);
8565                    // Warn for a permission in an unknown group.
8566                    if (p.info.group != null && p.group == null) {
8567                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8568                                + p.info.packageName + " in an unknown group " + p.info.group);
8569                    }
8570                }
8571
8572                ArrayMap<String, BasePermission> permissionMap =
8573                        p.tree ? mSettings.mPermissionTrees
8574                                : mSettings.mPermissions;
8575                BasePermission bp = permissionMap.get(p.info.name);
8576
8577                // Allow system apps to redefine non-system permissions
8578                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8579                    final boolean currentOwnerIsSystem = (bp.perm != null
8580                            && isSystemApp(bp.perm.owner));
8581                    if (isSystemApp(p.owner)) {
8582                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8583                            // It's a built-in permission and no owner, take ownership now
8584                            bp.packageSetting = pkgSetting;
8585                            bp.perm = p;
8586                            bp.uid = pkg.applicationInfo.uid;
8587                            bp.sourcePackage = p.info.packageName;
8588                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8589                        } else if (!currentOwnerIsSystem) {
8590                            String msg = "New decl " + p.owner + " of permission  "
8591                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8592                            reportSettingsProblem(Log.WARN, msg);
8593                            bp = null;
8594                        }
8595                    }
8596                }
8597
8598                if (bp == null) {
8599                    bp = new BasePermission(p.info.name, p.info.packageName,
8600                            BasePermission.TYPE_NORMAL);
8601                    permissionMap.put(p.info.name, bp);
8602                }
8603
8604                if (bp.perm == null) {
8605                    if (bp.sourcePackage == null
8606                            || bp.sourcePackage.equals(p.info.packageName)) {
8607                        BasePermission tree = findPermissionTreeLP(p.info.name);
8608                        if (tree == null
8609                                || tree.sourcePackage.equals(p.info.packageName)) {
8610                            bp.packageSetting = pkgSetting;
8611                            bp.perm = p;
8612                            bp.uid = pkg.applicationInfo.uid;
8613                            bp.sourcePackage = p.info.packageName;
8614                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8615                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8616                                if (r == null) {
8617                                    r = new StringBuilder(256);
8618                                } else {
8619                                    r.append(' ');
8620                                }
8621                                r.append(p.info.name);
8622                            }
8623                        } else {
8624                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8625                                    + p.info.packageName + " ignored: base tree "
8626                                    + tree.name + " is from package "
8627                                    + tree.sourcePackage);
8628                        }
8629                    } else {
8630                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8631                                + p.info.packageName + " ignored: original from "
8632                                + bp.sourcePackage);
8633                    }
8634                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8635                    if (r == null) {
8636                        r = new StringBuilder(256);
8637                    } else {
8638                        r.append(' ');
8639                    }
8640                    r.append("DUP:");
8641                    r.append(p.info.name);
8642                }
8643                if (bp.perm == p) {
8644                    bp.protectionLevel = p.info.protectionLevel;
8645                }
8646            }
8647
8648            if (r != null) {
8649                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8650            }
8651
8652            N = pkg.instrumentation.size();
8653            r = null;
8654            for (i=0; i<N; i++) {
8655                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8656                a.info.packageName = pkg.applicationInfo.packageName;
8657                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8658                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8659                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8660                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8661                a.info.dataDir = pkg.applicationInfo.dataDir;
8662                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8663                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8664
8665                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8666                // need other information about the application, like the ABI and what not ?
8667                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8668                mInstrumentation.put(a.getComponentName(), a);
8669                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8670                    if (r == null) {
8671                        r = new StringBuilder(256);
8672                    } else {
8673                        r.append(' ');
8674                    }
8675                    r.append(a.info.name);
8676                }
8677            }
8678            if (r != null) {
8679                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8680            }
8681
8682            if (pkg.protectedBroadcasts != null) {
8683                N = pkg.protectedBroadcasts.size();
8684                for (i=0; i<N; i++) {
8685                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8686                }
8687            }
8688
8689            pkgSetting.setTimeStamp(scanFileTime);
8690
8691            // Create idmap files for pairs of (packages, overlay packages).
8692            // Note: "android", ie framework-res.apk, is handled by native layers.
8693            if (pkg.mOverlayTarget != null) {
8694                // This is an overlay package.
8695                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8696                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8697                        mOverlays.put(pkg.mOverlayTarget,
8698                                new ArrayMap<String, PackageParser.Package>());
8699                    }
8700                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8701                    map.put(pkg.packageName, pkg);
8702                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8703                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8704                        createIdmapFailed = true;
8705                    }
8706                }
8707            } else if (mOverlays.containsKey(pkg.packageName) &&
8708                    !pkg.packageName.equals("android")) {
8709                // This is a regular package, with one or more known overlay packages.
8710                createIdmapsForPackageLI(pkg);
8711            }
8712        }
8713
8714        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8715
8716        if (createIdmapFailed) {
8717            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8718                    "scanPackageLI failed to createIdmap");
8719        }
8720        return pkg;
8721    }
8722
8723    /**
8724     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8725     * is derived purely on the basis of the contents of {@code scanFile} and
8726     * {@code cpuAbiOverride}.
8727     *
8728     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8729     */
8730    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8731                                 String cpuAbiOverride, boolean extractLibs)
8732            throws PackageManagerException {
8733        // TODO: We can probably be smarter about this stuff. For installed apps,
8734        // we can calculate this information at install time once and for all. For
8735        // system apps, we can probably assume that this information doesn't change
8736        // after the first boot scan. As things stand, we do lots of unnecessary work.
8737
8738        // Give ourselves some initial paths; we'll come back for another
8739        // pass once we've determined ABI below.
8740        setNativeLibraryPaths(pkg);
8741
8742        // We would never need to extract libs for forward-locked and external packages,
8743        // since the container service will do it for us. We shouldn't attempt to
8744        // extract libs from system app when it was not updated.
8745        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8746                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8747            extractLibs = false;
8748        }
8749
8750        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8751        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8752
8753        NativeLibraryHelper.Handle handle = null;
8754        try {
8755            handle = NativeLibraryHelper.Handle.create(pkg);
8756            // TODO(multiArch): This can be null for apps that didn't go through the
8757            // usual installation process. We can calculate it again, like we
8758            // do during install time.
8759            //
8760            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8761            // unnecessary.
8762            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8763
8764            // Null out the abis so that they can be recalculated.
8765            pkg.applicationInfo.primaryCpuAbi = null;
8766            pkg.applicationInfo.secondaryCpuAbi = null;
8767            if (isMultiArch(pkg.applicationInfo)) {
8768                // Warn if we've set an abiOverride for multi-lib packages..
8769                // By definition, we need to copy both 32 and 64 bit libraries for
8770                // such packages.
8771                if (pkg.cpuAbiOverride != null
8772                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8773                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8774                }
8775
8776                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8777                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8778                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8779                    if (extractLibs) {
8780                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8781                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8782                                useIsaSpecificSubdirs);
8783                    } else {
8784                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8785                    }
8786                }
8787
8788                maybeThrowExceptionForMultiArchCopy(
8789                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8790
8791                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8792                    if (extractLibs) {
8793                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8794                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8795                                useIsaSpecificSubdirs);
8796                    } else {
8797                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8798                    }
8799                }
8800
8801                maybeThrowExceptionForMultiArchCopy(
8802                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8803
8804                if (abi64 >= 0) {
8805                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8806                }
8807
8808                if (abi32 >= 0) {
8809                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8810                    if (abi64 >= 0) {
8811                        if (pkg.use32bitAbi) {
8812                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8813                            pkg.applicationInfo.primaryCpuAbi = abi;
8814                        } else {
8815                            pkg.applicationInfo.secondaryCpuAbi = abi;
8816                        }
8817                    } else {
8818                        pkg.applicationInfo.primaryCpuAbi = abi;
8819                    }
8820                }
8821
8822            } else {
8823                String[] abiList = (cpuAbiOverride != null) ?
8824                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8825
8826                // Enable gross and lame hacks for apps that are built with old
8827                // SDK tools. We must scan their APKs for renderscript bitcode and
8828                // not launch them if it's present. Don't bother checking on devices
8829                // that don't have 64 bit support.
8830                boolean needsRenderScriptOverride = false;
8831                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8832                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8833                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8834                    needsRenderScriptOverride = true;
8835                }
8836
8837                final int copyRet;
8838                if (extractLibs) {
8839                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8840                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8841                } else {
8842                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8843                }
8844
8845                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8846                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8847                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8848                }
8849
8850                if (copyRet >= 0) {
8851                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8852                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8853                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8854                } else if (needsRenderScriptOverride) {
8855                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8856                }
8857            }
8858        } catch (IOException ioe) {
8859            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8860        } finally {
8861            IoUtils.closeQuietly(handle);
8862        }
8863
8864        // Now that we've calculated the ABIs and determined if it's an internal app,
8865        // we will go ahead and populate the nativeLibraryPath.
8866        setNativeLibraryPaths(pkg);
8867    }
8868
8869    /**
8870     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8871     * i.e, so that all packages can be run inside a single process if required.
8872     *
8873     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8874     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8875     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8876     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8877     * updating a package that belongs to a shared user.
8878     *
8879     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8880     * adds unnecessary complexity.
8881     */
8882    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8883            PackageParser.Package scannedPackage, boolean bootComplete) {
8884        String requiredInstructionSet = null;
8885        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8886            requiredInstructionSet = VMRuntime.getInstructionSet(
8887                     scannedPackage.applicationInfo.primaryCpuAbi);
8888        }
8889
8890        PackageSetting requirer = null;
8891        for (PackageSetting ps : packagesForUser) {
8892            // If packagesForUser contains scannedPackage, we skip it. This will happen
8893            // when scannedPackage is an update of an existing package. Without this check,
8894            // we will never be able to change the ABI of any package belonging to a shared
8895            // user, even if it's compatible with other packages.
8896            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8897                if (ps.primaryCpuAbiString == null) {
8898                    continue;
8899                }
8900
8901                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8902                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8903                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8904                    // this but there's not much we can do.
8905                    String errorMessage = "Instruction set mismatch, "
8906                            + ((requirer == null) ? "[caller]" : requirer)
8907                            + " requires " + requiredInstructionSet + " whereas " + ps
8908                            + " requires " + instructionSet;
8909                    Slog.w(TAG, errorMessage);
8910                }
8911
8912                if (requiredInstructionSet == null) {
8913                    requiredInstructionSet = instructionSet;
8914                    requirer = ps;
8915                }
8916            }
8917        }
8918
8919        if (requiredInstructionSet != null) {
8920            String adjustedAbi;
8921            if (requirer != null) {
8922                // requirer != null implies that either scannedPackage was null or that scannedPackage
8923                // did not require an ABI, in which case we have to adjust scannedPackage to match
8924                // the ABI of the set (which is the same as requirer's ABI)
8925                adjustedAbi = requirer.primaryCpuAbiString;
8926                if (scannedPackage != null) {
8927                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8928                }
8929            } else {
8930                // requirer == null implies that we're updating all ABIs in the set to
8931                // match scannedPackage.
8932                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8933            }
8934
8935            for (PackageSetting ps : packagesForUser) {
8936                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8937                    if (ps.primaryCpuAbiString != null) {
8938                        continue;
8939                    }
8940
8941                    ps.primaryCpuAbiString = adjustedAbi;
8942                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8943                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8944                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8945                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8946                                + " (requirer="
8947                                + (requirer == null ? "null" : requirer.pkg.packageName)
8948                                + ", scannedPackage="
8949                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8950                                + ")");
8951                        try {
8952                            mInstaller.rmdex(ps.codePathString,
8953                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8954                        } catch (InstallerException ignored) {
8955                        }
8956                    }
8957                }
8958            }
8959        }
8960    }
8961
8962    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8963        synchronized (mPackages) {
8964            mResolverReplaced = true;
8965            // Set up information for custom user intent resolution activity.
8966            mResolveActivity.applicationInfo = pkg.applicationInfo;
8967            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8968            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8969            mResolveActivity.processName = pkg.applicationInfo.packageName;
8970            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8971            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8972                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8973            mResolveActivity.theme = 0;
8974            mResolveActivity.exported = true;
8975            mResolveActivity.enabled = true;
8976            mResolveInfo.activityInfo = mResolveActivity;
8977            mResolveInfo.priority = 0;
8978            mResolveInfo.preferredOrder = 0;
8979            mResolveInfo.match = 0;
8980            mResolveComponentName = mCustomResolverComponentName;
8981            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8982                    mResolveComponentName);
8983        }
8984    }
8985
8986    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8987        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8988
8989        // Set up information for ephemeral installer activity
8990        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8991        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8992        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8993        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8994        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8995        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8996                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8997        mEphemeralInstallerActivity.theme = 0;
8998        mEphemeralInstallerActivity.exported = true;
8999        mEphemeralInstallerActivity.enabled = true;
9000        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9001        mEphemeralInstallerInfo.priority = 0;
9002        mEphemeralInstallerInfo.preferredOrder = 0;
9003        mEphemeralInstallerInfo.match = 0;
9004
9005        if (DEBUG_EPHEMERAL) {
9006            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9007        }
9008    }
9009
9010    private static String calculateBundledApkRoot(final String codePathString) {
9011        final File codePath = new File(codePathString);
9012        final File codeRoot;
9013        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9014            codeRoot = Environment.getRootDirectory();
9015        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9016            codeRoot = Environment.getOemDirectory();
9017        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9018            codeRoot = Environment.getVendorDirectory();
9019        } else {
9020            // Unrecognized code path; take its top real segment as the apk root:
9021            // e.g. /something/app/blah.apk => /something
9022            try {
9023                File f = codePath.getCanonicalFile();
9024                File parent = f.getParentFile();    // non-null because codePath is a file
9025                File tmp;
9026                while ((tmp = parent.getParentFile()) != null) {
9027                    f = parent;
9028                    parent = tmp;
9029                }
9030                codeRoot = f;
9031                Slog.w(TAG, "Unrecognized code path "
9032                        + codePath + " - using " + codeRoot);
9033            } catch (IOException e) {
9034                // Can't canonicalize the code path -- shenanigans?
9035                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9036                return Environment.getRootDirectory().getPath();
9037            }
9038        }
9039        return codeRoot.getPath();
9040    }
9041
9042    /**
9043     * Derive and set the location of native libraries for the given package,
9044     * which varies depending on where and how the package was installed.
9045     */
9046    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9047        final ApplicationInfo info = pkg.applicationInfo;
9048        final String codePath = pkg.codePath;
9049        final File codeFile = new File(codePath);
9050        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9051        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9052
9053        info.nativeLibraryRootDir = null;
9054        info.nativeLibraryRootRequiresIsa = false;
9055        info.nativeLibraryDir = null;
9056        info.secondaryNativeLibraryDir = null;
9057
9058        if (isApkFile(codeFile)) {
9059            // Monolithic install
9060            if (bundledApp) {
9061                // If "/system/lib64/apkname" exists, assume that is the per-package
9062                // native library directory to use; otherwise use "/system/lib/apkname".
9063                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9064                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9065                        getPrimaryInstructionSet(info));
9066
9067                // This is a bundled system app so choose the path based on the ABI.
9068                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9069                // is just the default path.
9070                final String apkName = deriveCodePathName(codePath);
9071                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9072                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9073                        apkName).getAbsolutePath();
9074
9075                if (info.secondaryCpuAbi != null) {
9076                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9077                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9078                            secondaryLibDir, apkName).getAbsolutePath();
9079                }
9080            } else if (asecApp) {
9081                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9082                        .getAbsolutePath();
9083            } else {
9084                final String apkName = deriveCodePathName(codePath);
9085                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9086                        .getAbsolutePath();
9087            }
9088
9089            info.nativeLibraryRootRequiresIsa = false;
9090            info.nativeLibraryDir = info.nativeLibraryRootDir;
9091        } else {
9092            // Cluster install
9093            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9094            info.nativeLibraryRootRequiresIsa = true;
9095
9096            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9097                    getPrimaryInstructionSet(info)).getAbsolutePath();
9098
9099            if (info.secondaryCpuAbi != null) {
9100                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9101                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9102            }
9103        }
9104    }
9105
9106    /**
9107     * Calculate the abis and roots for a bundled app. These can uniquely
9108     * be determined from the contents of the system partition, i.e whether
9109     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9110     * of this information, and instead assume that the system was built
9111     * sensibly.
9112     */
9113    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9114                                           PackageSetting pkgSetting) {
9115        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9116
9117        // If "/system/lib64/apkname" exists, assume that is the per-package
9118        // native library directory to use; otherwise use "/system/lib/apkname".
9119        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9120        setBundledAppAbi(pkg, apkRoot, apkName);
9121        // pkgSetting might be null during rescan following uninstall of updates
9122        // to a bundled app, so accommodate that possibility.  The settings in
9123        // that case will be established later from the parsed package.
9124        //
9125        // If the settings aren't null, sync them up with what we've just derived.
9126        // note that apkRoot isn't stored in the package settings.
9127        if (pkgSetting != null) {
9128            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9129            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9130        }
9131    }
9132
9133    /**
9134     * Deduces the ABI of a bundled app and sets the relevant fields on the
9135     * parsed pkg object.
9136     *
9137     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9138     *        under which system libraries are installed.
9139     * @param apkName the name of the installed package.
9140     */
9141    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9142        final File codeFile = new File(pkg.codePath);
9143
9144        final boolean has64BitLibs;
9145        final boolean has32BitLibs;
9146        if (isApkFile(codeFile)) {
9147            // Monolithic install
9148            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9149            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9150        } else {
9151            // Cluster install
9152            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9153            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9154                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9155                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9156                has64BitLibs = (new File(rootDir, isa)).exists();
9157            } else {
9158                has64BitLibs = false;
9159            }
9160            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9161                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9162                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9163                has32BitLibs = (new File(rootDir, isa)).exists();
9164            } else {
9165                has32BitLibs = false;
9166            }
9167        }
9168
9169        if (has64BitLibs && !has32BitLibs) {
9170            // The package has 64 bit libs, but not 32 bit libs. Its primary
9171            // ABI should be 64 bit. We can safely assume here that the bundled
9172            // native libraries correspond to the most preferred ABI in the list.
9173
9174            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9175            pkg.applicationInfo.secondaryCpuAbi = null;
9176        } else if (has32BitLibs && !has64BitLibs) {
9177            // The package has 32 bit libs but not 64 bit libs. Its primary
9178            // ABI should be 32 bit.
9179
9180            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9181            pkg.applicationInfo.secondaryCpuAbi = null;
9182        } else if (has32BitLibs && has64BitLibs) {
9183            // The application has both 64 and 32 bit bundled libraries. We check
9184            // here that the app declares multiArch support, and warn if it doesn't.
9185            //
9186            // We will be lenient here and record both ABIs. The primary will be the
9187            // ABI that's higher on the list, i.e, a device that's configured to prefer
9188            // 64 bit apps will see a 64 bit primary ABI,
9189
9190            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9191                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9192            }
9193
9194            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9195                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9196                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9197            } else {
9198                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9199                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9200            }
9201        } else {
9202            pkg.applicationInfo.primaryCpuAbi = null;
9203            pkg.applicationInfo.secondaryCpuAbi = null;
9204        }
9205    }
9206
9207    private void killApplication(String pkgName, int appId, String reason) {
9208        // Request the ActivityManager to kill the process(only for existing packages)
9209        // so that we do not end up in a confused state while the user is still using the older
9210        // version of the application while the new one gets installed.
9211        final long token = Binder.clearCallingIdentity();
9212        try {
9213            IActivityManager am = ActivityManagerNative.getDefault();
9214            if (am != null) {
9215                try {
9216                    am.killApplicationWithAppId(pkgName, appId, reason);
9217                } catch (RemoteException e) {
9218                }
9219            }
9220        } finally {
9221            Binder.restoreCallingIdentity(token);
9222        }
9223    }
9224
9225    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9226        // Remove the parent package setting
9227        PackageSetting ps = (PackageSetting) pkg.mExtras;
9228        if (ps != null) {
9229            removePackageLI(ps, chatty);
9230        }
9231        // Remove the child package setting
9232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9233        for (int i = 0; i < childCount; i++) {
9234            PackageParser.Package childPkg = pkg.childPackages.get(i);
9235            ps = (PackageSetting) childPkg.mExtras;
9236            if (ps != null) {
9237                removePackageLI(ps, chatty);
9238            }
9239        }
9240    }
9241
9242    void removePackageLI(PackageSetting ps, boolean chatty) {
9243        if (DEBUG_INSTALL) {
9244            if (chatty)
9245                Log.d(TAG, "Removing package " + ps.name);
9246        }
9247
9248        // writer
9249        synchronized (mPackages) {
9250            mPackages.remove(ps.name);
9251            final PackageParser.Package pkg = ps.pkg;
9252            if (pkg != null) {
9253                cleanPackageDataStructuresLILPw(pkg, chatty);
9254            }
9255        }
9256    }
9257
9258    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9259        if (DEBUG_INSTALL) {
9260            if (chatty)
9261                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9262        }
9263
9264        // writer
9265        synchronized (mPackages) {
9266            // Remove the parent package
9267            mPackages.remove(pkg.applicationInfo.packageName);
9268            cleanPackageDataStructuresLILPw(pkg, chatty);
9269
9270            // Remove the child packages
9271            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9272            for (int i = 0; i < childCount; i++) {
9273                PackageParser.Package childPkg = pkg.childPackages.get(i);
9274                mPackages.remove(childPkg.applicationInfo.packageName);
9275                cleanPackageDataStructuresLILPw(childPkg, chatty);
9276            }
9277        }
9278    }
9279
9280    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9281        int N = pkg.providers.size();
9282        StringBuilder r = null;
9283        int i;
9284        for (i=0; i<N; i++) {
9285            PackageParser.Provider p = pkg.providers.get(i);
9286            mProviders.removeProvider(p);
9287            if (p.info.authority == null) {
9288
9289                /* There was another ContentProvider with this authority when
9290                 * this app was installed so this authority is null,
9291                 * Ignore it as we don't have to unregister the provider.
9292                 */
9293                continue;
9294            }
9295            String names[] = p.info.authority.split(";");
9296            for (int j = 0; j < names.length; j++) {
9297                if (mProvidersByAuthority.get(names[j]) == p) {
9298                    mProvidersByAuthority.remove(names[j]);
9299                    if (DEBUG_REMOVE) {
9300                        if (chatty)
9301                            Log.d(TAG, "Unregistered content provider: " + names[j]
9302                                    + ", className = " + p.info.name + ", isSyncable = "
9303                                    + p.info.isSyncable);
9304                    }
9305                }
9306            }
9307            if (DEBUG_REMOVE && chatty) {
9308                if (r == null) {
9309                    r = new StringBuilder(256);
9310                } else {
9311                    r.append(' ');
9312                }
9313                r.append(p.info.name);
9314            }
9315        }
9316        if (r != null) {
9317            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9318        }
9319
9320        N = pkg.services.size();
9321        r = null;
9322        for (i=0; i<N; i++) {
9323            PackageParser.Service s = pkg.services.get(i);
9324            mServices.removeService(s);
9325            if (chatty) {
9326                if (r == null) {
9327                    r = new StringBuilder(256);
9328                } else {
9329                    r.append(' ');
9330                }
9331                r.append(s.info.name);
9332            }
9333        }
9334        if (r != null) {
9335            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9336        }
9337
9338        N = pkg.receivers.size();
9339        r = null;
9340        for (i=0; i<N; i++) {
9341            PackageParser.Activity a = pkg.receivers.get(i);
9342            mReceivers.removeActivity(a, "receiver");
9343            if (DEBUG_REMOVE && chatty) {
9344                if (r == null) {
9345                    r = new StringBuilder(256);
9346                } else {
9347                    r.append(' ');
9348                }
9349                r.append(a.info.name);
9350            }
9351        }
9352        if (r != null) {
9353            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9354        }
9355
9356        N = pkg.activities.size();
9357        r = null;
9358        for (i=0; i<N; i++) {
9359            PackageParser.Activity a = pkg.activities.get(i);
9360            mActivities.removeActivity(a, "activity");
9361            if (DEBUG_REMOVE && chatty) {
9362                if (r == null) {
9363                    r = new StringBuilder(256);
9364                } else {
9365                    r.append(' ');
9366                }
9367                r.append(a.info.name);
9368            }
9369        }
9370        if (r != null) {
9371            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9372        }
9373
9374        N = pkg.permissions.size();
9375        r = null;
9376        for (i=0; i<N; i++) {
9377            PackageParser.Permission p = pkg.permissions.get(i);
9378            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9379            if (bp == null) {
9380                bp = mSettings.mPermissionTrees.get(p.info.name);
9381            }
9382            if (bp != null && bp.perm == p) {
9383                bp.perm = null;
9384                if (DEBUG_REMOVE && chatty) {
9385                    if (r == null) {
9386                        r = new StringBuilder(256);
9387                    } else {
9388                        r.append(' ');
9389                    }
9390                    r.append(p.info.name);
9391                }
9392            }
9393            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9394                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9395                if (appOpPkgs != null) {
9396                    appOpPkgs.remove(pkg.packageName);
9397                }
9398            }
9399        }
9400        if (r != null) {
9401            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9402        }
9403
9404        N = pkg.requestedPermissions.size();
9405        r = null;
9406        for (i=0; i<N; i++) {
9407            String perm = pkg.requestedPermissions.get(i);
9408            BasePermission bp = mSettings.mPermissions.get(perm);
9409            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9410                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9411                if (appOpPkgs != null) {
9412                    appOpPkgs.remove(pkg.packageName);
9413                    if (appOpPkgs.isEmpty()) {
9414                        mAppOpPermissionPackages.remove(perm);
9415                    }
9416                }
9417            }
9418        }
9419        if (r != null) {
9420            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9421        }
9422
9423        N = pkg.instrumentation.size();
9424        r = null;
9425        for (i=0; i<N; i++) {
9426            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9427            mInstrumentation.remove(a.getComponentName());
9428            if (DEBUG_REMOVE && chatty) {
9429                if (r == null) {
9430                    r = new StringBuilder(256);
9431                } else {
9432                    r.append(' ');
9433                }
9434                r.append(a.info.name);
9435            }
9436        }
9437        if (r != null) {
9438            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9439        }
9440
9441        r = null;
9442        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9443            // Only system apps can hold shared libraries.
9444            if (pkg.libraryNames != null) {
9445                for (i=0; i<pkg.libraryNames.size(); i++) {
9446                    String name = pkg.libraryNames.get(i);
9447                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9448                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9449                        mSharedLibraries.remove(name);
9450                        if (DEBUG_REMOVE && chatty) {
9451                            if (r == null) {
9452                                r = new StringBuilder(256);
9453                            } else {
9454                                r.append(' ');
9455                            }
9456                            r.append(name);
9457                        }
9458                    }
9459                }
9460            }
9461        }
9462        if (r != null) {
9463            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9464        }
9465    }
9466
9467    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9468        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9469            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9470                return true;
9471            }
9472        }
9473        return false;
9474    }
9475
9476    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9477    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9478    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9479
9480    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9481        // Update the parent permissions
9482        updatePermissionsLPw(pkg.packageName, pkg, flags);
9483        // Update the child permissions
9484        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9485        for (int i = 0; i < childCount; i++) {
9486            PackageParser.Package childPkg = pkg.childPackages.get(i);
9487            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9488        }
9489    }
9490
9491    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9492            int flags) {
9493        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9494        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9495    }
9496
9497    private void updatePermissionsLPw(String changingPkg,
9498            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9499        // Make sure there are no dangling permission trees.
9500        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9501        while (it.hasNext()) {
9502            final BasePermission bp = it.next();
9503            if (bp.packageSetting == null) {
9504                // We may not yet have parsed the package, so just see if
9505                // we still know about its settings.
9506                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9507            }
9508            if (bp.packageSetting == null) {
9509                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9510                        + " from package " + bp.sourcePackage);
9511                it.remove();
9512            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9513                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9514                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9515                            + " from package " + bp.sourcePackage);
9516                    flags |= UPDATE_PERMISSIONS_ALL;
9517                    it.remove();
9518                }
9519            }
9520        }
9521
9522        // Make sure all dynamic permissions have been assigned to a package,
9523        // and make sure there are no dangling permissions.
9524        it = mSettings.mPermissions.values().iterator();
9525        while (it.hasNext()) {
9526            final BasePermission bp = it.next();
9527            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9528                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9529                        + bp.name + " pkg=" + bp.sourcePackage
9530                        + " info=" + bp.pendingInfo);
9531                if (bp.packageSetting == null && bp.pendingInfo != null) {
9532                    final BasePermission tree = findPermissionTreeLP(bp.name);
9533                    if (tree != null && tree.perm != null) {
9534                        bp.packageSetting = tree.packageSetting;
9535                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9536                                new PermissionInfo(bp.pendingInfo));
9537                        bp.perm.info.packageName = tree.perm.info.packageName;
9538                        bp.perm.info.name = bp.name;
9539                        bp.uid = tree.uid;
9540                    }
9541                }
9542            }
9543            if (bp.packageSetting == null) {
9544                // We may not yet have parsed the package, so just see if
9545                // we still know about its settings.
9546                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9547            }
9548            if (bp.packageSetting == null) {
9549                Slog.w(TAG, "Removing dangling permission: " + bp.name
9550                        + " from package " + bp.sourcePackage);
9551                it.remove();
9552            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9553                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9554                    Slog.i(TAG, "Removing old permission: " + bp.name
9555                            + " from package " + bp.sourcePackage);
9556                    flags |= UPDATE_PERMISSIONS_ALL;
9557                    it.remove();
9558                }
9559            }
9560        }
9561
9562        // Now update the permissions for all packages, in particular
9563        // replace the granted permissions of the system packages.
9564        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9565            for (PackageParser.Package pkg : mPackages.values()) {
9566                if (pkg != pkgInfo) {
9567                    // Only replace for packages on requested volume
9568                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9569                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9570                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9571                    grantPermissionsLPw(pkg, replace, changingPkg);
9572                }
9573            }
9574        }
9575
9576        if (pkgInfo != null) {
9577            // Only replace for packages on requested volume
9578            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9579            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9580                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9581            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9582        }
9583    }
9584
9585    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9586            String packageOfInterest) {
9587        // IMPORTANT: There are two types of permissions: install and runtime.
9588        // Install time permissions are granted when the app is installed to
9589        // all device users and users added in the future. Runtime permissions
9590        // are granted at runtime explicitly to specific users. Normal and signature
9591        // protected permissions are install time permissions. Dangerous permissions
9592        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9593        // otherwise they are runtime permissions. This function does not manage
9594        // runtime permissions except for the case an app targeting Lollipop MR1
9595        // being upgraded to target a newer SDK, in which case dangerous permissions
9596        // are transformed from install time to runtime ones.
9597
9598        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9599        if (ps == null) {
9600            return;
9601        }
9602
9603        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9604
9605        PermissionsState permissionsState = ps.getPermissionsState();
9606        PermissionsState origPermissions = permissionsState;
9607
9608        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9609
9610        boolean runtimePermissionsRevoked = false;
9611        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9612
9613        boolean changedInstallPermission = false;
9614
9615        if (replace) {
9616            ps.installPermissionsFixed = false;
9617            if (!ps.isSharedUser()) {
9618                origPermissions = new PermissionsState(permissionsState);
9619                permissionsState.reset();
9620            } else {
9621                // We need to know only about runtime permission changes since the
9622                // calling code always writes the install permissions state but
9623                // the runtime ones are written only if changed. The only cases of
9624                // changed runtime permissions here are promotion of an install to
9625                // runtime and revocation of a runtime from a shared user.
9626                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9627                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9628                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9629                    runtimePermissionsRevoked = true;
9630                }
9631            }
9632        }
9633
9634        permissionsState.setGlobalGids(mGlobalGids);
9635
9636        final int N = pkg.requestedPermissions.size();
9637        for (int i=0; i<N; i++) {
9638            final String name = pkg.requestedPermissions.get(i);
9639            final BasePermission bp = mSettings.mPermissions.get(name);
9640
9641            if (DEBUG_INSTALL) {
9642                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9643            }
9644
9645            if (bp == null || bp.packageSetting == null) {
9646                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9647                    Slog.w(TAG, "Unknown permission " + name
9648                            + " in package " + pkg.packageName);
9649                }
9650                continue;
9651            }
9652
9653            final String perm = bp.name;
9654            boolean allowedSig = false;
9655            int grant = GRANT_DENIED;
9656
9657            // Keep track of app op permissions.
9658            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9659                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9660                if (pkgs == null) {
9661                    pkgs = new ArraySet<>();
9662                    mAppOpPermissionPackages.put(bp.name, pkgs);
9663                }
9664                pkgs.add(pkg.packageName);
9665            }
9666
9667            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9668            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9669                    >= Build.VERSION_CODES.M;
9670            switch (level) {
9671                case PermissionInfo.PROTECTION_NORMAL: {
9672                    // For all apps normal permissions are install time ones.
9673                    grant = GRANT_INSTALL;
9674                } break;
9675
9676                case PermissionInfo.PROTECTION_DANGEROUS: {
9677                    // If a permission review is required for legacy apps we represent
9678                    // their permissions as always granted runtime ones since we need
9679                    // to keep the review required permission flag per user while an
9680                    // install permission's state is shared across all users.
9681                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9682                        // For legacy apps dangerous permissions are install time ones.
9683                        grant = GRANT_INSTALL;
9684                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9685                        // For legacy apps that became modern, install becomes runtime.
9686                        grant = GRANT_UPGRADE;
9687                    } else if (mPromoteSystemApps
9688                            && isSystemApp(ps)
9689                            && mExistingSystemPackages.contains(ps.name)) {
9690                        // For legacy system apps, install becomes runtime.
9691                        // We cannot check hasInstallPermission() for system apps since those
9692                        // permissions were granted implicitly and not persisted pre-M.
9693                        grant = GRANT_UPGRADE;
9694                    } else {
9695                        // For modern apps keep runtime permissions unchanged.
9696                        grant = GRANT_RUNTIME;
9697                    }
9698                } break;
9699
9700                case PermissionInfo.PROTECTION_SIGNATURE: {
9701                    // For all apps signature permissions are install time ones.
9702                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9703                    if (allowedSig) {
9704                        grant = GRANT_INSTALL;
9705                    }
9706                } break;
9707            }
9708
9709            if (DEBUG_INSTALL) {
9710                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9711            }
9712
9713            if (grant != GRANT_DENIED) {
9714                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9715                    // If this is an existing, non-system package, then
9716                    // we can't add any new permissions to it.
9717                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9718                        // Except...  if this is a permission that was added
9719                        // to the platform (note: need to only do this when
9720                        // updating the platform).
9721                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9722                            grant = GRANT_DENIED;
9723                        }
9724                    }
9725                }
9726
9727                switch (grant) {
9728                    case GRANT_INSTALL: {
9729                        // Revoke this as runtime permission to handle the case of
9730                        // a runtime permission being downgraded to an install one.
9731                        // Also in permission review mode we keep dangerous permissions
9732                        // for legacy apps
9733                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9734                            if (origPermissions.getRuntimePermissionState(
9735                                    bp.name, userId) != null) {
9736                                // Revoke the runtime permission and clear the flags.
9737                                origPermissions.revokeRuntimePermission(bp, userId);
9738                                origPermissions.updatePermissionFlags(bp, userId,
9739                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9740                                // If we revoked a permission permission, we have to write.
9741                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9742                                        changedRuntimePermissionUserIds, userId);
9743                            }
9744                        }
9745                        // Grant an install permission.
9746                        if (permissionsState.grantInstallPermission(bp) !=
9747                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9748                            changedInstallPermission = true;
9749                        }
9750                    } break;
9751
9752                    case GRANT_RUNTIME: {
9753                        // Grant previously granted runtime permissions.
9754                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9755                            PermissionState permissionState = origPermissions
9756                                    .getRuntimePermissionState(bp.name, userId);
9757                            int flags = permissionState != null
9758                                    ? permissionState.getFlags() : 0;
9759                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9760                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9761                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9762                                    // If we cannot put the permission as it was, we have to write.
9763                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9764                                            changedRuntimePermissionUserIds, userId);
9765                                }
9766                                // If the app supports runtime permissions no need for a review.
9767                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9768                                        && appSupportsRuntimePermissions
9769                                        && (flags & PackageManager
9770                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9771                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9772                                    // Since we changed the flags, we have to write.
9773                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9774                                            changedRuntimePermissionUserIds, userId);
9775                                }
9776                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9777                                    && !appSupportsRuntimePermissions) {
9778                                // For legacy apps that need a permission review, every new
9779                                // runtime permission is granted but it is pending a review.
9780                                // We also need to review only platform defined runtime
9781                                // permissions as these are the only ones the platform knows
9782                                // how to disable the API to simulate revocation as legacy
9783                                // apps don't expect to run with revoked permissions.
9784                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9785                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9786                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9787                                        // We changed the flags, hence have to write.
9788                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9789                                                changedRuntimePermissionUserIds, userId);
9790                                    }
9791                                }
9792                                if (permissionsState.grantRuntimePermission(bp, userId)
9793                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9794                                    // We changed the permission, hence have to write.
9795                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9796                                            changedRuntimePermissionUserIds, userId);
9797                                }
9798                            }
9799                            // Propagate the permission flags.
9800                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9801                        }
9802                    } break;
9803
9804                    case GRANT_UPGRADE: {
9805                        // Grant runtime permissions for a previously held install permission.
9806                        PermissionState permissionState = origPermissions
9807                                .getInstallPermissionState(bp.name);
9808                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9809
9810                        if (origPermissions.revokeInstallPermission(bp)
9811                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9812                            // We will be transferring the permission flags, so clear them.
9813                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9814                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9815                            changedInstallPermission = true;
9816                        }
9817
9818                        // If the permission is not to be promoted to runtime we ignore it and
9819                        // also its other flags as they are not applicable to install permissions.
9820                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9821                            for (int userId : currentUserIds) {
9822                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9823                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9824                                    // Transfer the permission flags.
9825                                    permissionsState.updatePermissionFlags(bp, userId,
9826                                            flags, flags);
9827                                    // If we granted the permission, we have to write.
9828                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9829                                            changedRuntimePermissionUserIds, userId);
9830                                }
9831                            }
9832                        }
9833                    } break;
9834
9835                    default: {
9836                        if (packageOfInterest == null
9837                                || packageOfInterest.equals(pkg.packageName)) {
9838                            Slog.w(TAG, "Not granting permission " + perm
9839                                    + " to package " + pkg.packageName
9840                                    + " because it was previously installed without");
9841                        }
9842                    } break;
9843                }
9844            } else {
9845                if (permissionsState.revokeInstallPermission(bp) !=
9846                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9847                    // Also drop the permission flags.
9848                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9849                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9850                    changedInstallPermission = true;
9851                    Slog.i(TAG, "Un-granting permission " + perm
9852                            + " from package " + pkg.packageName
9853                            + " (protectionLevel=" + bp.protectionLevel
9854                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9855                            + ")");
9856                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9857                    // Don't print warning for app op permissions, since it is fine for them
9858                    // not to be granted, there is a UI for the user to decide.
9859                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9860                        Slog.w(TAG, "Not granting permission " + perm
9861                                + " to package " + pkg.packageName
9862                                + " (protectionLevel=" + bp.protectionLevel
9863                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9864                                + ")");
9865                    }
9866                }
9867            }
9868        }
9869
9870        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9871                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9872            // This is the first that we have heard about this package, so the
9873            // permissions we have now selected are fixed until explicitly
9874            // changed.
9875            ps.installPermissionsFixed = true;
9876        }
9877
9878        // Persist the runtime permissions state for users with changes. If permissions
9879        // were revoked because no app in the shared user declares them we have to
9880        // write synchronously to avoid losing runtime permissions state.
9881        for (int userId : changedRuntimePermissionUserIds) {
9882            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9883        }
9884
9885        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9886    }
9887
9888    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9889        boolean allowed = false;
9890        final int NP = PackageParser.NEW_PERMISSIONS.length;
9891        for (int ip=0; ip<NP; ip++) {
9892            final PackageParser.NewPermissionInfo npi
9893                    = PackageParser.NEW_PERMISSIONS[ip];
9894            if (npi.name.equals(perm)
9895                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9896                allowed = true;
9897                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9898                        + pkg.packageName);
9899                break;
9900            }
9901        }
9902        return allowed;
9903    }
9904
9905    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9906            BasePermission bp, PermissionsState origPermissions) {
9907        boolean allowed;
9908        allowed = (compareSignatures(
9909                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9910                        == PackageManager.SIGNATURE_MATCH)
9911                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9912                        == PackageManager.SIGNATURE_MATCH);
9913        if (!allowed && (bp.protectionLevel
9914                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9915            if (isSystemApp(pkg)) {
9916                // For updated system applications, a system permission
9917                // is granted only if it had been defined by the original application.
9918                if (pkg.isUpdatedSystemApp()) {
9919                    final PackageSetting sysPs = mSettings
9920                            .getDisabledSystemPkgLPr(pkg.packageName);
9921                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9922                        // If the original was granted this permission, we take
9923                        // that grant decision as read and propagate it to the
9924                        // update.
9925                        if (sysPs.isPrivileged()) {
9926                            allowed = true;
9927                        }
9928                    } else {
9929                        // The system apk may have been updated with an older
9930                        // version of the one on the data partition, but which
9931                        // granted a new system permission that it didn't have
9932                        // before.  In this case we do want to allow the app to
9933                        // now get the new permission if the ancestral apk is
9934                        // privileged to get it.
9935                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9936                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9937                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9938                                    allowed = true;
9939                                    break;
9940                                }
9941                            }
9942                        }
9943                        // Also if a privileged parent package on the system image or any of
9944                        // its children requested a privileged permission, the updated child
9945                        // packages can also get the permission.
9946                        if (pkg.parentPackage != null) {
9947                            final PackageSetting disabledSysParentPs = mSettings
9948                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9949                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9950                                    && disabledSysParentPs.isPrivileged()) {
9951                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9952                                    allowed = true;
9953                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9954                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9955                                    for (int i = 0; i < count; i++) {
9956                                        PackageParser.Package disabledSysChildPkg =
9957                                                disabledSysParentPs.pkg.childPackages.get(i);
9958                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9959                                                perm)) {
9960                                            allowed = true;
9961                                            break;
9962                                        }
9963                                    }
9964                                }
9965                            }
9966                        }
9967                    }
9968                } else {
9969                    allowed = isPrivilegedApp(pkg);
9970                }
9971            }
9972        }
9973        if (!allowed) {
9974            if (!allowed && (bp.protectionLevel
9975                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9976                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9977                // If this was a previously normal/dangerous permission that got moved
9978                // to a system permission as part of the runtime permission redesign, then
9979                // we still want to blindly grant it to old apps.
9980                allowed = true;
9981            }
9982            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9983                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9984                // If this permission is to be granted to the system installer and
9985                // this app is an installer, then it gets the permission.
9986                allowed = true;
9987            }
9988            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9989                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9990                // If this permission is to be granted to the system verifier and
9991                // this app is a verifier, then it gets the permission.
9992                allowed = true;
9993            }
9994            if (!allowed && (bp.protectionLevel
9995                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9996                    && isSystemApp(pkg)) {
9997                // Any pre-installed system app is allowed to get this permission.
9998                allowed = true;
9999            }
10000            if (!allowed && (bp.protectionLevel
10001                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10002                // For development permissions, a development permission
10003                // is granted only if it was already granted.
10004                allowed = origPermissions.hasInstallPermission(perm);
10005            }
10006            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10007                    && pkg.packageName.equals(mSetupWizardPackage)) {
10008                // If this permission is to be granted to the system setup wizard and
10009                // this app is a setup wizard, then it gets the permission.
10010                allowed = true;
10011            }
10012        }
10013        return allowed;
10014    }
10015
10016    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10017        final int permCount = pkg.requestedPermissions.size();
10018        for (int j = 0; j < permCount; j++) {
10019            String requestedPermission = pkg.requestedPermissions.get(j);
10020            if (permission.equals(requestedPermission)) {
10021                return true;
10022            }
10023        }
10024        return false;
10025    }
10026
10027    final class ActivityIntentResolver
10028            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10029        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10030                boolean defaultOnly, int userId) {
10031            if (!sUserManager.exists(userId)) return null;
10032            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10033            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10034        }
10035
10036        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10037                int userId) {
10038            if (!sUserManager.exists(userId)) return null;
10039            mFlags = flags;
10040            return super.queryIntent(intent, resolvedType,
10041                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10042        }
10043
10044        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10045                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10046            if (!sUserManager.exists(userId)) return null;
10047            if (packageActivities == null) {
10048                return null;
10049            }
10050            mFlags = flags;
10051            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10052            final int N = packageActivities.size();
10053            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10054                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10055
10056            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10057            for (int i = 0; i < N; ++i) {
10058                intentFilters = packageActivities.get(i).intents;
10059                if (intentFilters != null && intentFilters.size() > 0) {
10060                    PackageParser.ActivityIntentInfo[] array =
10061                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10062                    intentFilters.toArray(array);
10063                    listCut.add(array);
10064                }
10065            }
10066            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10067        }
10068
10069        /**
10070         * Finds a privileged activity that matches the specified activity names.
10071         */
10072        private PackageParser.Activity findMatchingActivity(
10073                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10074            for (PackageParser.Activity sysActivity : activityList) {
10075                if (sysActivity.info.name.equals(activityInfo.name)) {
10076                    return sysActivity;
10077                }
10078                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10079                    return sysActivity;
10080                }
10081                if (sysActivity.info.targetActivity != null) {
10082                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10083                        return sysActivity;
10084                    }
10085                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10086                        return sysActivity;
10087                    }
10088                }
10089            }
10090            return null;
10091        }
10092
10093        public class IterGenerator<E> {
10094            public Iterator<E> generate(ActivityIntentInfo info) {
10095                return null;
10096            }
10097        }
10098
10099        public class ActionIterGenerator extends IterGenerator<String> {
10100            @Override
10101            public Iterator<String> generate(ActivityIntentInfo info) {
10102                return info.actionsIterator();
10103            }
10104        }
10105
10106        public class CategoriesIterGenerator extends IterGenerator<String> {
10107            @Override
10108            public Iterator<String> generate(ActivityIntentInfo info) {
10109                return info.categoriesIterator();
10110            }
10111        }
10112
10113        public class SchemesIterGenerator extends IterGenerator<String> {
10114            @Override
10115            public Iterator<String> generate(ActivityIntentInfo info) {
10116                return info.schemesIterator();
10117            }
10118        }
10119
10120        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10121            @Override
10122            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10123                return info.authoritiesIterator();
10124            }
10125        }
10126
10127        /**
10128         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10129         * MODIFIED. Do not pass in a list that should not be changed.
10130         */
10131        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10132                IterGenerator<T> generator, Iterator<T> searchIterator) {
10133            // loop through the set of actions; every one must be found in the intent filter
10134            while (searchIterator.hasNext()) {
10135                // we must have at least one filter in the list to consider a match
10136                if (intentList.size() == 0) {
10137                    break;
10138                }
10139
10140                final T searchAction = searchIterator.next();
10141
10142                // loop through the set of intent filters
10143                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10144                while (intentIter.hasNext()) {
10145                    final ActivityIntentInfo intentInfo = intentIter.next();
10146                    boolean selectionFound = false;
10147
10148                    // loop through the intent filter's selection criteria; at least one
10149                    // of them must match the searched criteria
10150                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10151                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10152                        final T intentSelection = intentSelectionIter.next();
10153                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10154                            selectionFound = true;
10155                            break;
10156                        }
10157                    }
10158
10159                    // the selection criteria wasn't found in this filter's set; this filter
10160                    // is not a potential match
10161                    if (!selectionFound) {
10162                        intentIter.remove();
10163                    }
10164                }
10165            }
10166        }
10167
10168        private boolean isProtectedAction(ActivityIntentInfo filter) {
10169            final Iterator<String> actionsIter = filter.actionsIterator();
10170            while (actionsIter != null && actionsIter.hasNext()) {
10171                final String filterAction = actionsIter.next();
10172                if (PROTECTED_ACTIONS.contains(filterAction)) {
10173                    return true;
10174                }
10175            }
10176            return false;
10177        }
10178
10179        /**
10180         * Adjusts the priority of the given intent filter according to policy.
10181         * <p>
10182         * <ul>
10183         * <li>The priority for non privileged applications is capped to '0'</li>
10184         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10185         * <li>The priority for unbundled updates to privileged applications is capped to the
10186         *      priority defined on the system partition</li>
10187         * </ul>
10188         * <p>
10189         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10190         * allowed to obtain any priority on any action.
10191         */
10192        private void adjustPriority(
10193                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10194            // nothing to do; priority is fine as-is
10195            if (intent.getPriority() <= 0) {
10196                return;
10197            }
10198
10199            final ActivityInfo activityInfo = intent.activity.info;
10200            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10201
10202            final boolean privilegedApp =
10203                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10204            if (!privilegedApp) {
10205                // non-privileged applications can never define a priority >0
10206                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10207                        + " package: " + applicationInfo.packageName
10208                        + " activity: " + intent.activity.className
10209                        + " origPrio: " + intent.getPriority());
10210                intent.setPriority(0);
10211                return;
10212            }
10213
10214            if (systemActivities == null) {
10215                // the system package is not disabled; we're parsing the system partition
10216                if (isProtectedAction(intent)) {
10217                    if (mDeferProtectedFilters) {
10218                        // We can't deal with these just yet. No component should ever obtain a
10219                        // >0 priority for a protected actions, with ONE exception -- the setup
10220                        // wizard. The setup wizard, however, cannot be known until we're able to
10221                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10222                        // until all intent filters have been processed. Chicken, meet egg.
10223                        // Let the filter temporarily have a high priority and rectify the
10224                        // priorities after all system packages have been scanned.
10225                        mProtectedFilters.add(intent);
10226                        if (DEBUG_FILTERS) {
10227                            Slog.i(TAG, "Protected action; save for later;"
10228                                    + " package: " + applicationInfo.packageName
10229                                    + " activity: " + intent.activity.className
10230                                    + " origPrio: " + intent.getPriority());
10231                        }
10232                        return;
10233                    } else {
10234                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10235                            Slog.i(TAG, "No setup wizard;"
10236                                + " All protected intents capped to priority 0");
10237                        }
10238                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10239                            if (DEBUG_FILTERS) {
10240                                Slog.i(TAG, "Found setup wizard;"
10241                                    + " allow priority " + intent.getPriority() + ";"
10242                                    + " package: " + intent.activity.info.packageName
10243                                    + " activity: " + intent.activity.className
10244                                    + " priority: " + intent.getPriority());
10245                            }
10246                            // setup wizard gets whatever it wants
10247                            return;
10248                        }
10249                        Slog.w(TAG, "Protected action; cap priority to 0;"
10250                                + " package: " + intent.activity.info.packageName
10251                                + " activity: " + intent.activity.className
10252                                + " origPrio: " + intent.getPriority());
10253                        intent.setPriority(0);
10254                        return;
10255                    }
10256                }
10257                // privileged apps on the system image get whatever priority they request
10258                return;
10259            }
10260
10261            // privileged app unbundled update ... try to find the same activity
10262            final PackageParser.Activity foundActivity =
10263                    findMatchingActivity(systemActivities, activityInfo);
10264            if (foundActivity == null) {
10265                // this is a new activity; it cannot obtain >0 priority
10266                if (DEBUG_FILTERS) {
10267                    Slog.i(TAG, "New activity; cap priority to 0;"
10268                            + " package: " + applicationInfo.packageName
10269                            + " activity: " + intent.activity.className
10270                            + " origPrio: " + intent.getPriority());
10271                }
10272                intent.setPriority(0);
10273                return;
10274            }
10275
10276            // found activity, now check for filter equivalence
10277
10278            // a shallow copy is enough; we modify the list, not its contents
10279            final List<ActivityIntentInfo> intentListCopy =
10280                    new ArrayList<>(foundActivity.intents);
10281            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10282
10283            // find matching action subsets
10284            final Iterator<String> actionsIterator = intent.actionsIterator();
10285            if (actionsIterator != null) {
10286                getIntentListSubset(
10287                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10288                if (intentListCopy.size() == 0) {
10289                    // no more intents to match; we're not equivalent
10290                    if (DEBUG_FILTERS) {
10291                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10292                                + " package: " + applicationInfo.packageName
10293                                + " activity: " + intent.activity.className
10294                                + " origPrio: " + intent.getPriority());
10295                    }
10296                    intent.setPriority(0);
10297                    return;
10298                }
10299            }
10300
10301            // find matching category subsets
10302            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10303            if (categoriesIterator != null) {
10304                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10305                        categoriesIterator);
10306                if (intentListCopy.size() == 0) {
10307                    // no more intents to match; we're not equivalent
10308                    if (DEBUG_FILTERS) {
10309                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10310                                + " package: " + applicationInfo.packageName
10311                                + " activity: " + intent.activity.className
10312                                + " origPrio: " + intent.getPriority());
10313                    }
10314                    intent.setPriority(0);
10315                    return;
10316                }
10317            }
10318
10319            // find matching schemes subsets
10320            final Iterator<String> schemesIterator = intent.schemesIterator();
10321            if (schemesIterator != null) {
10322                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10323                        schemesIterator);
10324                if (intentListCopy.size() == 0) {
10325                    // no more intents to match; we're not equivalent
10326                    if (DEBUG_FILTERS) {
10327                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10328                                + " package: " + applicationInfo.packageName
10329                                + " activity: " + intent.activity.className
10330                                + " origPrio: " + intent.getPriority());
10331                    }
10332                    intent.setPriority(0);
10333                    return;
10334                }
10335            }
10336
10337            // find matching authorities subsets
10338            final Iterator<IntentFilter.AuthorityEntry>
10339                    authoritiesIterator = intent.authoritiesIterator();
10340            if (authoritiesIterator != null) {
10341                getIntentListSubset(intentListCopy,
10342                        new AuthoritiesIterGenerator(),
10343                        authoritiesIterator);
10344                if (intentListCopy.size() == 0) {
10345                    // no more intents to match; we're not equivalent
10346                    if (DEBUG_FILTERS) {
10347                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10348                                + " package: " + applicationInfo.packageName
10349                                + " activity: " + intent.activity.className
10350                                + " origPrio: " + intent.getPriority());
10351                    }
10352                    intent.setPriority(0);
10353                    return;
10354                }
10355            }
10356
10357            // we found matching filter(s); app gets the max priority of all intents
10358            int cappedPriority = 0;
10359            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10360                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10361            }
10362            if (intent.getPriority() > cappedPriority) {
10363                if (DEBUG_FILTERS) {
10364                    Slog.i(TAG, "Found matching filter(s);"
10365                            + " cap priority to " + cappedPriority + ";"
10366                            + " package: " + applicationInfo.packageName
10367                            + " activity: " + intent.activity.className
10368                            + " origPrio: " + intent.getPriority());
10369                }
10370                intent.setPriority(cappedPriority);
10371                return;
10372            }
10373            // all this for nothing; the requested priority was <= what was on the system
10374        }
10375
10376        public final void addActivity(PackageParser.Activity a, String type) {
10377            mActivities.put(a.getComponentName(), a);
10378            if (DEBUG_SHOW_INFO)
10379                Log.v(
10380                TAG, "  " + type + " " +
10381                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10382            if (DEBUG_SHOW_INFO)
10383                Log.v(TAG, "    Class=" + a.info.name);
10384            final int NI = a.intents.size();
10385            for (int j=0; j<NI; j++) {
10386                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10387                if ("activity".equals(type)) {
10388                    final PackageSetting ps =
10389                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10390                    final List<PackageParser.Activity> systemActivities =
10391                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10392                    adjustPriority(systemActivities, intent);
10393                }
10394                if (DEBUG_SHOW_INFO) {
10395                    Log.v(TAG, "    IntentFilter:");
10396                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10397                }
10398                if (!intent.debugCheck()) {
10399                    Log.w(TAG, "==> For Activity " + a.info.name);
10400                }
10401                addFilter(intent);
10402            }
10403        }
10404
10405        public final void removeActivity(PackageParser.Activity a, String type) {
10406            mActivities.remove(a.getComponentName());
10407            if (DEBUG_SHOW_INFO) {
10408                Log.v(TAG, "  " + type + " "
10409                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10410                                : a.info.name) + ":");
10411                Log.v(TAG, "    Class=" + a.info.name);
10412            }
10413            final int NI = a.intents.size();
10414            for (int j=0; j<NI; j++) {
10415                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10416                if (DEBUG_SHOW_INFO) {
10417                    Log.v(TAG, "    IntentFilter:");
10418                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10419                }
10420                removeFilter(intent);
10421            }
10422        }
10423
10424        @Override
10425        protected boolean allowFilterResult(
10426                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10427            ActivityInfo filterAi = filter.activity.info;
10428            for (int i=dest.size()-1; i>=0; i--) {
10429                ActivityInfo destAi = dest.get(i).activityInfo;
10430                if (destAi.name == filterAi.name
10431                        && destAi.packageName == filterAi.packageName) {
10432                    return false;
10433                }
10434            }
10435            return true;
10436        }
10437
10438        @Override
10439        protected ActivityIntentInfo[] newArray(int size) {
10440            return new ActivityIntentInfo[size];
10441        }
10442
10443        @Override
10444        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10445            if (!sUserManager.exists(userId)) return true;
10446            PackageParser.Package p = filter.activity.owner;
10447            if (p != null) {
10448                PackageSetting ps = (PackageSetting)p.mExtras;
10449                if (ps != null) {
10450                    // System apps are never considered stopped for purposes of
10451                    // filtering, because there may be no way for the user to
10452                    // actually re-launch them.
10453                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10454                            && ps.getStopped(userId);
10455                }
10456            }
10457            return false;
10458        }
10459
10460        @Override
10461        protected boolean isPackageForFilter(String packageName,
10462                PackageParser.ActivityIntentInfo info) {
10463            return packageName.equals(info.activity.owner.packageName);
10464        }
10465
10466        @Override
10467        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10468                int match, int userId) {
10469            if (!sUserManager.exists(userId)) return null;
10470            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10471                return null;
10472            }
10473            final PackageParser.Activity activity = info.activity;
10474            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10475            if (ps == null) {
10476                return null;
10477            }
10478            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10479                    ps.readUserState(userId), userId);
10480            if (ai == null) {
10481                return null;
10482            }
10483            final ResolveInfo res = new ResolveInfo();
10484            res.activityInfo = ai;
10485            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10486                res.filter = info;
10487            }
10488            if (info != null) {
10489                res.handleAllWebDataURI = info.handleAllWebDataURI();
10490            }
10491            res.priority = info.getPriority();
10492            res.preferredOrder = activity.owner.mPreferredOrder;
10493            //System.out.println("Result: " + res.activityInfo.className +
10494            //                   " = " + res.priority);
10495            res.match = match;
10496            res.isDefault = info.hasDefault;
10497            res.labelRes = info.labelRes;
10498            res.nonLocalizedLabel = info.nonLocalizedLabel;
10499            if (userNeedsBadging(userId)) {
10500                res.noResourceId = true;
10501            } else {
10502                res.icon = info.icon;
10503            }
10504            res.iconResourceId = info.icon;
10505            res.system = res.activityInfo.applicationInfo.isSystemApp();
10506            return res;
10507        }
10508
10509        @Override
10510        protected void sortResults(List<ResolveInfo> results) {
10511            Collections.sort(results, mResolvePrioritySorter);
10512        }
10513
10514        @Override
10515        protected void dumpFilter(PrintWriter out, String prefix,
10516                PackageParser.ActivityIntentInfo filter) {
10517            out.print(prefix); out.print(
10518                    Integer.toHexString(System.identityHashCode(filter.activity)));
10519                    out.print(' ');
10520                    filter.activity.printComponentShortName(out);
10521                    out.print(" filter ");
10522                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10523        }
10524
10525        @Override
10526        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10527            return filter.activity;
10528        }
10529
10530        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10531            PackageParser.Activity activity = (PackageParser.Activity)label;
10532            out.print(prefix); out.print(
10533                    Integer.toHexString(System.identityHashCode(activity)));
10534                    out.print(' ');
10535                    activity.printComponentShortName(out);
10536            if (count > 1) {
10537                out.print(" ("); out.print(count); out.print(" filters)");
10538            }
10539            out.println();
10540        }
10541
10542        // Keys are String (activity class name), values are Activity.
10543        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10544                = new ArrayMap<ComponentName, PackageParser.Activity>();
10545        private int mFlags;
10546    }
10547
10548    private final class ServiceIntentResolver
10549            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10550        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10551                boolean defaultOnly, int userId) {
10552            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10553            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10554        }
10555
10556        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10557                int userId) {
10558            if (!sUserManager.exists(userId)) return null;
10559            mFlags = flags;
10560            return super.queryIntent(intent, resolvedType,
10561                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10562        }
10563
10564        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10565                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10566            if (!sUserManager.exists(userId)) return null;
10567            if (packageServices == null) {
10568                return null;
10569            }
10570            mFlags = flags;
10571            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10572            final int N = packageServices.size();
10573            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10574                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10575
10576            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10577            for (int i = 0; i < N; ++i) {
10578                intentFilters = packageServices.get(i).intents;
10579                if (intentFilters != null && intentFilters.size() > 0) {
10580                    PackageParser.ServiceIntentInfo[] array =
10581                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10582                    intentFilters.toArray(array);
10583                    listCut.add(array);
10584                }
10585            }
10586            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10587        }
10588
10589        public final void addService(PackageParser.Service s) {
10590            mServices.put(s.getComponentName(), s);
10591            if (DEBUG_SHOW_INFO) {
10592                Log.v(TAG, "  "
10593                        + (s.info.nonLocalizedLabel != null
10594                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10595                Log.v(TAG, "    Class=" + s.info.name);
10596            }
10597            final int NI = s.intents.size();
10598            int j;
10599            for (j=0; j<NI; j++) {
10600                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10601                if (DEBUG_SHOW_INFO) {
10602                    Log.v(TAG, "    IntentFilter:");
10603                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10604                }
10605                if (!intent.debugCheck()) {
10606                    Log.w(TAG, "==> For Service " + s.info.name);
10607                }
10608                addFilter(intent);
10609            }
10610        }
10611
10612        public final void removeService(PackageParser.Service s) {
10613            mServices.remove(s.getComponentName());
10614            if (DEBUG_SHOW_INFO) {
10615                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10616                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10617                Log.v(TAG, "    Class=" + s.info.name);
10618            }
10619            final int NI = s.intents.size();
10620            int j;
10621            for (j=0; j<NI; j++) {
10622                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10623                if (DEBUG_SHOW_INFO) {
10624                    Log.v(TAG, "    IntentFilter:");
10625                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10626                }
10627                removeFilter(intent);
10628            }
10629        }
10630
10631        @Override
10632        protected boolean allowFilterResult(
10633                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10634            ServiceInfo filterSi = filter.service.info;
10635            for (int i=dest.size()-1; i>=0; i--) {
10636                ServiceInfo destAi = dest.get(i).serviceInfo;
10637                if (destAi.name == filterSi.name
10638                        && destAi.packageName == filterSi.packageName) {
10639                    return false;
10640                }
10641            }
10642            return true;
10643        }
10644
10645        @Override
10646        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10647            return new PackageParser.ServiceIntentInfo[size];
10648        }
10649
10650        @Override
10651        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10652            if (!sUserManager.exists(userId)) return true;
10653            PackageParser.Package p = filter.service.owner;
10654            if (p != null) {
10655                PackageSetting ps = (PackageSetting)p.mExtras;
10656                if (ps != null) {
10657                    // System apps are never considered stopped for purposes of
10658                    // filtering, because there may be no way for the user to
10659                    // actually re-launch them.
10660                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10661                            && ps.getStopped(userId);
10662                }
10663            }
10664            return false;
10665        }
10666
10667        @Override
10668        protected boolean isPackageForFilter(String packageName,
10669                PackageParser.ServiceIntentInfo info) {
10670            return packageName.equals(info.service.owner.packageName);
10671        }
10672
10673        @Override
10674        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10675                int match, int userId) {
10676            if (!sUserManager.exists(userId)) return null;
10677            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10678            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10679                return null;
10680            }
10681            final PackageParser.Service service = info.service;
10682            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10683            if (ps == null) {
10684                return null;
10685            }
10686            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10687                    ps.readUserState(userId), userId);
10688            if (si == null) {
10689                return null;
10690            }
10691            final ResolveInfo res = new ResolveInfo();
10692            res.serviceInfo = si;
10693            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10694                res.filter = filter;
10695            }
10696            res.priority = info.getPriority();
10697            res.preferredOrder = service.owner.mPreferredOrder;
10698            res.match = match;
10699            res.isDefault = info.hasDefault;
10700            res.labelRes = info.labelRes;
10701            res.nonLocalizedLabel = info.nonLocalizedLabel;
10702            res.icon = info.icon;
10703            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10704            return res;
10705        }
10706
10707        @Override
10708        protected void sortResults(List<ResolveInfo> results) {
10709            Collections.sort(results, mResolvePrioritySorter);
10710        }
10711
10712        @Override
10713        protected void dumpFilter(PrintWriter out, String prefix,
10714                PackageParser.ServiceIntentInfo filter) {
10715            out.print(prefix); out.print(
10716                    Integer.toHexString(System.identityHashCode(filter.service)));
10717                    out.print(' ');
10718                    filter.service.printComponentShortName(out);
10719                    out.print(" filter ");
10720                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10721        }
10722
10723        @Override
10724        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10725            return filter.service;
10726        }
10727
10728        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10729            PackageParser.Service service = (PackageParser.Service)label;
10730            out.print(prefix); out.print(
10731                    Integer.toHexString(System.identityHashCode(service)));
10732                    out.print(' ');
10733                    service.printComponentShortName(out);
10734            if (count > 1) {
10735                out.print(" ("); out.print(count); out.print(" filters)");
10736            }
10737            out.println();
10738        }
10739
10740//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10741//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10742//            final List<ResolveInfo> retList = Lists.newArrayList();
10743//            while (i.hasNext()) {
10744//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10745//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10746//                    retList.add(resolveInfo);
10747//                }
10748//            }
10749//            return retList;
10750//        }
10751
10752        // Keys are String (activity class name), values are Activity.
10753        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10754                = new ArrayMap<ComponentName, PackageParser.Service>();
10755        private int mFlags;
10756    };
10757
10758    private final class ProviderIntentResolver
10759            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10760        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10761                boolean defaultOnly, int userId) {
10762            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10763            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10764        }
10765
10766        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10767                int userId) {
10768            if (!sUserManager.exists(userId))
10769                return null;
10770            mFlags = flags;
10771            return super.queryIntent(intent, resolvedType,
10772                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10773        }
10774
10775        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10776                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10777            if (!sUserManager.exists(userId))
10778                return null;
10779            if (packageProviders == null) {
10780                return null;
10781            }
10782            mFlags = flags;
10783            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10784            final int N = packageProviders.size();
10785            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10786                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10787
10788            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10789            for (int i = 0; i < N; ++i) {
10790                intentFilters = packageProviders.get(i).intents;
10791                if (intentFilters != null && intentFilters.size() > 0) {
10792                    PackageParser.ProviderIntentInfo[] array =
10793                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10794                    intentFilters.toArray(array);
10795                    listCut.add(array);
10796                }
10797            }
10798            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10799        }
10800
10801        public final void addProvider(PackageParser.Provider p) {
10802            if (mProviders.containsKey(p.getComponentName())) {
10803                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10804                return;
10805            }
10806
10807            mProviders.put(p.getComponentName(), p);
10808            if (DEBUG_SHOW_INFO) {
10809                Log.v(TAG, "  "
10810                        + (p.info.nonLocalizedLabel != null
10811                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10812                Log.v(TAG, "    Class=" + p.info.name);
10813            }
10814            final int NI = p.intents.size();
10815            int j;
10816            for (j = 0; j < NI; j++) {
10817                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10818                if (DEBUG_SHOW_INFO) {
10819                    Log.v(TAG, "    IntentFilter:");
10820                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10821                }
10822                if (!intent.debugCheck()) {
10823                    Log.w(TAG, "==> For Provider " + p.info.name);
10824                }
10825                addFilter(intent);
10826            }
10827        }
10828
10829        public final void removeProvider(PackageParser.Provider p) {
10830            mProviders.remove(p.getComponentName());
10831            if (DEBUG_SHOW_INFO) {
10832                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10833                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10834                Log.v(TAG, "    Class=" + p.info.name);
10835            }
10836            final int NI = p.intents.size();
10837            int j;
10838            for (j = 0; j < NI; j++) {
10839                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10840                if (DEBUG_SHOW_INFO) {
10841                    Log.v(TAG, "    IntentFilter:");
10842                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10843                }
10844                removeFilter(intent);
10845            }
10846        }
10847
10848        @Override
10849        protected boolean allowFilterResult(
10850                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10851            ProviderInfo filterPi = filter.provider.info;
10852            for (int i = dest.size() - 1; i >= 0; i--) {
10853                ProviderInfo destPi = dest.get(i).providerInfo;
10854                if (destPi.name == filterPi.name
10855                        && destPi.packageName == filterPi.packageName) {
10856                    return false;
10857                }
10858            }
10859            return true;
10860        }
10861
10862        @Override
10863        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10864            return new PackageParser.ProviderIntentInfo[size];
10865        }
10866
10867        @Override
10868        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10869            if (!sUserManager.exists(userId))
10870                return true;
10871            PackageParser.Package p = filter.provider.owner;
10872            if (p != null) {
10873                PackageSetting ps = (PackageSetting) p.mExtras;
10874                if (ps != null) {
10875                    // System apps are never considered stopped for purposes of
10876                    // filtering, because there may be no way for the user to
10877                    // actually re-launch them.
10878                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10879                            && ps.getStopped(userId);
10880                }
10881            }
10882            return false;
10883        }
10884
10885        @Override
10886        protected boolean isPackageForFilter(String packageName,
10887                PackageParser.ProviderIntentInfo info) {
10888            return packageName.equals(info.provider.owner.packageName);
10889        }
10890
10891        @Override
10892        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10893                int match, int userId) {
10894            if (!sUserManager.exists(userId))
10895                return null;
10896            final PackageParser.ProviderIntentInfo info = filter;
10897            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10898                return null;
10899            }
10900            final PackageParser.Provider provider = info.provider;
10901            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10902            if (ps == null) {
10903                return null;
10904            }
10905            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10906                    ps.readUserState(userId), userId);
10907            if (pi == null) {
10908                return null;
10909            }
10910            final ResolveInfo res = new ResolveInfo();
10911            res.providerInfo = pi;
10912            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10913                res.filter = filter;
10914            }
10915            res.priority = info.getPriority();
10916            res.preferredOrder = provider.owner.mPreferredOrder;
10917            res.match = match;
10918            res.isDefault = info.hasDefault;
10919            res.labelRes = info.labelRes;
10920            res.nonLocalizedLabel = info.nonLocalizedLabel;
10921            res.icon = info.icon;
10922            res.system = res.providerInfo.applicationInfo.isSystemApp();
10923            return res;
10924        }
10925
10926        @Override
10927        protected void sortResults(List<ResolveInfo> results) {
10928            Collections.sort(results, mResolvePrioritySorter);
10929        }
10930
10931        @Override
10932        protected void dumpFilter(PrintWriter out, String prefix,
10933                PackageParser.ProviderIntentInfo filter) {
10934            out.print(prefix);
10935            out.print(
10936                    Integer.toHexString(System.identityHashCode(filter.provider)));
10937            out.print(' ');
10938            filter.provider.printComponentShortName(out);
10939            out.print(" filter ");
10940            out.println(Integer.toHexString(System.identityHashCode(filter)));
10941        }
10942
10943        @Override
10944        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10945            return filter.provider;
10946        }
10947
10948        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10949            PackageParser.Provider provider = (PackageParser.Provider)label;
10950            out.print(prefix); out.print(
10951                    Integer.toHexString(System.identityHashCode(provider)));
10952                    out.print(' ');
10953                    provider.printComponentShortName(out);
10954            if (count > 1) {
10955                out.print(" ("); out.print(count); out.print(" filters)");
10956            }
10957            out.println();
10958        }
10959
10960        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10961                = new ArrayMap<ComponentName, PackageParser.Provider>();
10962        private int mFlags;
10963    }
10964
10965    private static final class EphemeralIntentResolver
10966            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10967        @Override
10968        protected EphemeralResolveIntentInfo[] newArray(int size) {
10969            return new EphemeralResolveIntentInfo[size];
10970        }
10971
10972        @Override
10973        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10974            return true;
10975        }
10976
10977        @Override
10978        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10979                int userId) {
10980            if (!sUserManager.exists(userId)) {
10981                return null;
10982            }
10983            return info.getEphemeralResolveInfo();
10984        }
10985    }
10986
10987    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10988            new Comparator<ResolveInfo>() {
10989        public int compare(ResolveInfo r1, ResolveInfo r2) {
10990            int v1 = r1.priority;
10991            int v2 = r2.priority;
10992            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10993            if (v1 != v2) {
10994                return (v1 > v2) ? -1 : 1;
10995            }
10996            v1 = r1.preferredOrder;
10997            v2 = r2.preferredOrder;
10998            if (v1 != v2) {
10999                return (v1 > v2) ? -1 : 1;
11000            }
11001            if (r1.isDefault != r2.isDefault) {
11002                return r1.isDefault ? -1 : 1;
11003            }
11004            v1 = r1.match;
11005            v2 = r2.match;
11006            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11007            if (v1 != v2) {
11008                return (v1 > v2) ? -1 : 1;
11009            }
11010            if (r1.system != r2.system) {
11011                return r1.system ? -1 : 1;
11012            }
11013            if (r1.activityInfo != null) {
11014                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11015            }
11016            if (r1.serviceInfo != null) {
11017                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11018            }
11019            if (r1.providerInfo != null) {
11020                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11021            }
11022            return 0;
11023        }
11024    };
11025
11026    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11027            new Comparator<ProviderInfo>() {
11028        public int compare(ProviderInfo p1, ProviderInfo p2) {
11029            final int v1 = p1.initOrder;
11030            final int v2 = p2.initOrder;
11031            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11032        }
11033    };
11034
11035    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11036            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11037            final int[] userIds) {
11038        mHandler.post(new Runnable() {
11039            @Override
11040            public void run() {
11041                try {
11042                    final IActivityManager am = ActivityManagerNative.getDefault();
11043                    if (am == null) return;
11044                    final int[] resolvedUserIds;
11045                    if (userIds == null) {
11046                        resolvedUserIds = am.getRunningUserIds();
11047                    } else {
11048                        resolvedUserIds = userIds;
11049                    }
11050                    for (int id : resolvedUserIds) {
11051                        final Intent intent = new Intent(action,
11052                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11053                        if (extras != null) {
11054                            intent.putExtras(extras);
11055                        }
11056                        if (targetPkg != null) {
11057                            intent.setPackage(targetPkg);
11058                        }
11059                        // Modify the UID when posting to other users
11060                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11061                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11062                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11063                            intent.putExtra(Intent.EXTRA_UID, uid);
11064                        }
11065                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11066                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11067                        if (DEBUG_BROADCASTS) {
11068                            RuntimeException here = new RuntimeException("here");
11069                            here.fillInStackTrace();
11070                            Slog.d(TAG, "Sending to user " + id + ": "
11071                                    + intent.toShortString(false, true, false, false)
11072                                    + " " + intent.getExtras(), here);
11073                        }
11074                        am.broadcastIntent(null, intent, null, finishedReceiver,
11075                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11076                                null, finishedReceiver != null, false, id);
11077                    }
11078                } catch (RemoteException ex) {
11079                }
11080            }
11081        });
11082    }
11083
11084    /**
11085     * Check if the external storage media is available. This is true if there
11086     * is a mounted external storage medium or if the external storage is
11087     * emulated.
11088     */
11089    private boolean isExternalMediaAvailable() {
11090        return mMediaMounted || Environment.isExternalStorageEmulated();
11091    }
11092
11093    @Override
11094    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11095        // writer
11096        synchronized (mPackages) {
11097            if (!isExternalMediaAvailable()) {
11098                // If the external storage is no longer mounted at this point,
11099                // the caller may not have been able to delete all of this
11100                // packages files and can not delete any more.  Bail.
11101                return null;
11102            }
11103            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11104            if (lastPackage != null) {
11105                pkgs.remove(lastPackage);
11106            }
11107            if (pkgs.size() > 0) {
11108                return pkgs.get(0);
11109            }
11110        }
11111        return null;
11112    }
11113
11114    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11115        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11116                userId, andCode ? 1 : 0, packageName);
11117        if (mSystemReady) {
11118            msg.sendToTarget();
11119        } else {
11120            if (mPostSystemReadyMessages == null) {
11121                mPostSystemReadyMessages = new ArrayList<>();
11122            }
11123            mPostSystemReadyMessages.add(msg);
11124        }
11125    }
11126
11127    void startCleaningPackages() {
11128        // reader
11129        if (!isExternalMediaAvailable()) {
11130            return;
11131        }
11132        synchronized (mPackages) {
11133            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11134                return;
11135            }
11136        }
11137        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11138        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11139        IActivityManager am = ActivityManagerNative.getDefault();
11140        if (am != null) {
11141            try {
11142                am.startService(null, intent, null, mContext.getOpPackageName(),
11143                        UserHandle.USER_SYSTEM);
11144            } catch (RemoteException e) {
11145            }
11146        }
11147    }
11148
11149    @Override
11150    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11151            int installFlags, String installerPackageName, int userId) {
11152        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11153
11154        final int callingUid = Binder.getCallingUid();
11155        enforceCrossUserPermission(callingUid, userId,
11156                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11157
11158        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11159            try {
11160                if (observer != null) {
11161                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11162                }
11163            } catch (RemoteException re) {
11164            }
11165            return;
11166        }
11167
11168        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11169            installFlags |= PackageManager.INSTALL_FROM_ADB;
11170
11171        } else {
11172            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11173            // about installerPackageName.
11174
11175            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11176            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11177        }
11178
11179        UserHandle user;
11180        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11181            user = UserHandle.ALL;
11182        } else {
11183            user = new UserHandle(userId);
11184        }
11185
11186        // Only system components can circumvent runtime permissions when installing.
11187        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11188                && mContext.checkCallingOrSelfPermission(Manifest.permission
11189                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11190            throw new SecurityException("You need the "
11191                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11192                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11193        }
11194
11195        final File originFile = new File(originPath);
11196        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11197
11198        final Message msg = mHandler.obtainMessage(INIT_COPY);
11199        final VerificationInfo verificationInfo = new VerificationInfo(
11200                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11201        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11202                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11203                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11204                null /*certificates*/);
11205        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11206        msg.obj = params;
11207
11208        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11209                System.identityHashCode(msg.obj));
11210        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11211                System.identityHashCode(msg.obj));
11212
11213        mHandler.sendMessage(msg);
11214    }
11215
11216    void installStage(String packageName, File stagedDir, String stagedCid,
11217            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11218            String installerPackageName, int installerUid, UserHandle user,
11219            Certificate[][] certificates) {
11220        if (DEBUG_EPHEMERAL) {
11221            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11222                Slog.d(TAG, "Ephemeral install of " + packageName);
11223            }
11224        }
11225        final VerificationInfo verificationInfo = new VerificationInfo(
11226                sessionParams.originatingUri, sessionParams.referrerUri,
11227                sessionParams.originatingUid, installerUid);
11228
11229        final OriginInfo origin;
11230        if (stagedDir != null) {
11231            origin = OriginInfo.fromStagedFile(stagedDir);
11232        } else {
11233            origin = OriginInfo.fromStagedContainer(stagedCid);
11234        }
11235
11236        final Message msg = mHandler.obtainMessage(INIT_COPY);
11237        final InstallParams params = new InstallParams(origin, null, observer,
11238                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11239                verificationInfo, user, sessionParams.abiOverride,
11240                sessionParams.grantedRuntimePermissions, certificates);
11241        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11242        msg.obj = params;
11243
11244        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11245                System.identityHashCode(msg.obj));
11246        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11247                System.identityHashCode(msg.obj));
11248
11249        mHandler.sendMessage(msg);
11250    }
11251
11252    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11253            int userId) {
11254        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11255        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11256    }
11257
11258    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11259            int appId, int userId) {
11260        Bundle extras = new Bundle(1);
11261        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11262
11263        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11264                packageName, extras, 0, null, null, new int[] {userId});
11265        try {
11266            IActivityManager am = ActivityManagerNative.getDefault();
11267            if (isSystem && am.isUserRunning(userId, 0)) {
11268                // The just-installed/enabled app is bundled on the system, so presumed
11269                // to be able to run automatically without needing an explicit launch.
11270                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11271                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11272                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11273                        .setPackage(packageName);
11274                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11275                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11276            }
11277        } catch (RemoteException e) {
11278            // shouldn't happen
11279            Slog.w(TAG, "Unable to bootstrap installed package", e);
11280        }
11281    }
11282
11283    @Override
11284    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11285            int userId) {
11286        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11287        PackageSetting pkgSetting;
11288        final int uid = Binder.getCallingUid();
11289        enforceCrossUserPermission(uid, userId,
11290                true /* requireFullPermission */, true /* checkShell */,
11291                "setApplicationHiddenSetting for user " + userId);
11292
11293        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11294            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11295            return false;
11296        }
11297
11298        long callingId = Binder.clearCallingIdentity();
11299        try {
11300            boolean sendAdded = false;
11301            boolean sendRemoved = false;
11302            // writer
11303            synchronized (mPackages) {
11304                pkgSetting = mSettings.mPackages.get(packageName);
11305                if (pkgSetting == null) {
11306                    return false;
11307                }
11308                if (pkgSetting.getHidden(userId) != hidden) {
11309                    pkgSetting.setHidden(hidden, userId);
11310                    mSettings.writePackageRestrictionsLPr(userId);
11311                    if (hidden) {
11312                        sendRemoved = true;
11313                    } else {
11314                        sendAdded = true;
11315                    }
11316                }
11317            }
11318            if (sendAdded) {
11319                sendPackageAddedForUser(packageName, pkgSetting, userId);
11320                return true;
11321            }
11322            if (sendRemoved) {
11323                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11324                        "hiding pkg");
11325                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11326                return true;
11327            }
11328        } finally {
11329            Binder.restoreCallingIdentity(callingId);
11330        }
11331        return false;
11332    }
11333
11334    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11335            int userId) {
11336        final PackageRemovedInfo info = new PackageRemovedInfo();
11337        info.removedPackage = packageName;
11338        info.removedUsers = new int[] {userId};
11339        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11340        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11341    }
11342
11343    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11344        if (pkgList.length > 0) {
11345            Bundle extras = new Bundle(1);
11346            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11347
11348            sendPackageBroadcast(
11349                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11350                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11351                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11352                    new int[] {userId});
11353        }
11354    }
11355
11356    /**
11357     * Returns true if application is not found or there was an error. Otherwise it returns
11358     * the hidden state of the package for the given user.
11359     */
11360    @Override
11361    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11362        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11363        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11364                true /* requireFullPermission */, false /* checkShell */,
11365                "getApplicationHidden for user " + userId);
11366        PackageSetting pkgSetting;
11367        long callingId = Binder.clearCallingIdentity();
11368        try {
11369            // writer
11370            synchronized (mPackages) {
11371                pkgSetting = mSettings.mPackages.get(packageName);
11372                if (pkgSetting == null) {
11373                    return true;
11374                }
11375                return pkgSetting.getHidden(userId);
11376            }
11377        } finally {
11378            Binder.restoreCallingIdentity(callingId);
11379        }
11380    }
11381
11382    /**
11383     * @hide
11384     */
11385    @Override
11386    public int installExistingPackageAsUser(String packageName, int userId) {
11387        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11388                null);
11389        PackageSetting pkgSetting;
11390        final int uid = Binder.getCallingUid();
11391        enforceCrossUserPermission(uid, userId,
11392                true /* requireFullPermission */, true /* checkShell */,
11393                "installExistingPackage for user " + userId);
11394        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11395            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11396        }
11397
11398        long callingId = Binder.clearCallingIdentity();
11399        try {
11400            boolean installed = false;
11401
11402            // writer
11403            synchronized (mPackages) {
11404                pkgSetting = mSettings.mPackages.get(packageName);
11405                if (pkgSetting == null) {
11406                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11407                }
11408                if (!pkgSetting.getInstalled(userId)) {
11409                    pkgSetting.setInstalled(true, userId);
11410                    pkgSetting.setHidden(false, userId);
11411                    mSettings.writePackageRestrictionsLPr(userId);
11412                    installed = true;
11413                }
11414            }
11415
11416            if (installed) {
11417                if (pkgSetting.pkg != null) {
11418                    synchronized (mInstallLock) {
11419                        // We don't need to freeze for a brand new install
11420                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11421                    }
11422                }
11423                sendPackageAddedForUser(packageName, pkgSetting, userId);
11424            }
11425        } finally {
11426            Binder.restoreCallingIdentity(callingId);
11427        }
11428
11429        return PackageManager.INSTALL_SUCCEEDED;
11430    }
11431
11432    boolean isUserRestricted(int userId, String restrictionKey) {
11433        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11434        if (restrictions.getBoolean(restrictionKey, false)) {
11435            Log.w(TAG, "User is restricted: " + restrictionKey);
11436            return true;
11437        }
11438        return false;
11439    }
11440
11441    @Override
11442    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11443            int userId) {
11444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11446                true /* requireFullPermission */, true /* checkShell */,
11447                "setPackagesSuspended for user " + userId);
11448
11449        if (ArrayUtils.isEmpty(packageNames)) {
11450            return packageNames;
11451        }
11452
11453        // List of package names for whom the suspended state has changed.
11454        List<String> changedPackages = new ArrayList<>(packageNames.length);
11455        // List of package names for whom the suspended state is not set as requested in this
11456        // method.
11457        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11458        for (int i = 0; i < packageNames.length; i++) {
11459            String packageName = packageNames[i];
11460            long callingId = Binder.clearCallingIdentity();
11461            try {
11462                boolean changed = false;
11463                final int appId;
11464                synchronized (mPackages) {
11465                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11466                    if (pkgSetting == null) {
11467                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11468                                + "\". Skipping suspending/un-suspending.");
11469                        unactionedPackages.add(packageName);
11470                        continue;
11471                    }
11472                    appId = pkgSetting.appId;
11473                    if (pkgSetting.getSuspended(userId) != suspended) {
11474                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11475                            unactionedPackages.add(packageName);
11476                            continue;
11477                        }
11478                        pkgSetting.setSuspended(suspended, userId);
11479                        mSettings.writePackageRestrictionsLPr(userId);
11480                        changed = true;
11481                        changedPackages.add(packageName);
11482                    }
11483                }
11484
11485                if (changed && suspended) {
11486                    killApplication(packageName, UserHandle.getUid(userId, appId),
11487                            "suspending package");
11488                }
11489            } finally {
11490                Binder.restoreCallingIdentity(callingId);
11491            }
11492        }
11493
11494        if (!changedPackages.isEmpty()) {
11495            sendPackagesSuspendedForUser(changedPackages.toArray(
11496                    new String[changedPackages.size()]), userId, suspended);
11497        }
11498
11499        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11500    }
11501
11502    @Override
11503    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11504        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11505                true /* requireFullPermission */, false /* checkShell */,
11506                "isPackageSuspendedForUser for user " + userId);
11507        synchronized (mPackages) {
11508            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11509            if (pkgSetting == null) {
11510                throw new IllegalArgumentException("Unknown target package: " + packageName);
11511            }
11512            return pkgSetting.getSuspended(userId);
11513        }
11514    }
11515
11516    /**
11517     * TODO: cache and disallow blocking the active dialer.
11518     *
11519     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11520     */
11521    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11522        if (isPackageDeviceAdmin(packageName, userId)) {
11523            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11524                    + "\": has an active device admin");
11525            return false;
11526        }
11527
11528        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11529        if (packageName.equals(activeLauncherPackageName)) {
11530            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11531                    + "\": contains the active launcher");
11532            return false;
11533        }
11534
11535        if (packageName.equals(mRequiredInstallerPackage)) {
11536            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11537                    + "\": required for package installation");
11538            return false;
11539        }
11540
11541        if (packageName.equals(mRequiredVerifierPackage)) {
11542            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11543                    + "\": required for package verification");
11544            return false;
11545        }
11546
11547        final PackageParser.Package pkg = mPackages.get(packageName);
11548        if (pkg != null && isPrivilegedApp(pkg)) {
11549            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11550                    + "\": is a privileged app");
11551            return false;
11552        }
11553
11554        return true;
11555    }
11556
11557    private String getActiveLauncherPackageName(int userId) {
11558        Intent intent = new Intent(Intent.ACTION_MAIN);
11559        intent.addCategory(Intent.CATEGORY_HOME);
11560        ResolveInfo resolveInfo = resolveIntent(
11561                intent,
11562                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11563                PackageManager.MATCH_DEFAULT_ONLY,
11564                userId);
11565
11566        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11567    }
11568
11569    @Override
11570    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11571        mContext.enforceCallingOrSelfPermission(
11572                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11573                "Only package verification agents can verify applications");
11574
11575        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11576        final PackageVerificationResponse response = new PackageVerificationResponse(
11577                verificationCode, Binder.getCallingUid());
11578        msg.arg1 = id;
11579        msg.obj = response;
11580        mHandler.sendMessage(msg);
11581    }
11582
11583    @Override
11584    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11585            long millisecondsToDelay) {
11586        mContext.enforceCallingOrSelfPermission(
11587                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11588                "Only package verification agents can extend verification timeouts");
11589
11590        final PackageVerificationState state = mPendingVerification.get(id);
11591        final PackageVerificationResponse response = new PackageVerificationResponse(
11592                verificationCodeAtTimeout, Binder.getCallingUid());
11593
11594        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11595            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11596        }
11597        if (millisecondsToDelay < 0) {
11598            millisecondsToDelay = 0;
11599        }
11600        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11601                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11602            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11603        }
11604
11605        if ((state != null) && !state.timeoutExtended()) {
11606            state.extendTimeout();
11607
11608            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11609            msg.arg1 = id;
11610            msg.obj = response;
11611            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11612        }
11613    }
11614
11615    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11616            int verificationCode, UserHandle user) {
11617        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11618        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11619        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11620        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11621        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11622
11623        mContext.sendBroadcastAsUser(intent, user,
11624                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11625    }
11626
11627    private ComponentName matchComponentForVerifier(String packageName,
11628            List<ResolveInfo> receivers) {
11629        ActivityInfo targetReceiver = null;
11630
11631        final int NR = receivers.size();
11632        for (int i = 0; i < NR; i++) {
11633            final ResolveInfo info = receivers.get(i);
11634            if (info.activityInfo == null) {
11635                continue;
11636            }
11637
11638            if (packageName.equals(info.activityInfo.packageName)) {
11639                targetReceiver = info.activityInfo;
11640                break;
11641            }
11642        }
11643
11644        if (targetReceiver == null) {
11645            return null;
11646        }
11647
11648        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11649    }
11650
11651    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11652            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11653        if (pkgInfo.verifiers.length == 0) {
11654            return null;
11655        }
11656
11657        final int N = pkgInfo.verifiers.length;
11658        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11659        for (int i = 0; i < N; i++) {
11660            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11661
11662            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11663                    receivers);
11664            if (comp == null) {
11665                continue;
11666            }
11667
11668            final int verifierUid = getUidForVerifier(verifierInfo);
11669            if (verifierUid == -1) {
11670                continue;
11671            }
11672
11673            if (DEBUG_VERIFY) {
11674                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11675                        + " with the correct signature");
11676            }
11677            sufficientVerifiers.add(comp);
11678            verificationState.addSufficientVerifier(verifierUid);
11679        }
11680
11681        return sufficientVerifiers;
11682    }
11683
11684    private int getUidForVerifier(VerifierInfo verifierInfo) {
11685        synchronized (mPackages) {
11686            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11687            if (pkg == null) {
11688                return -1;
11689            } else if (pkg.mSignatures.length != 1) {
11690                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11691                        + " has more than one signature; ignoring");
11692                return -1;
11693            }
11694
11695            /*
11696             * If the public key of the package's signature does not match
11697             * our expected public key, then this is a different package and
11698             * we should skip.
11699             */
11700
11701            final byte[] expectedPublicKey;
11702            try {
11703                final Signature verifierSig = pkg.mSignatures[0];
11704                final PublicKey publicKey = verifierSig.getPublicKey();
11705                expectedPublicKey = publicKey.getEncoded();
11706            } catch (CertificateException e) {
11707                return -1;
11708            }
11709
11710            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11711
11712            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11713                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11714                        + " does not have the expected public key; ignoring");
11715                return -1;
11716            }
11717
11718            return pkg.applicationInfo.uid;
11719        }
11720    }
11721
11722    @Override
11723    public void finishPackageInstall(int token, boolean didLaunch) {
11724        enforceSystemOrRoot("Only the system is allowed to finish installs");
11725
11726        if (DEBUG_INSTALL) {
11727            Slog.v(TAG, "BM finishing package install for " + token);
11728        }
11729        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11730
11731        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11732        mHandler.sendMessage(msg);
11733    }
11734
11735    /**
11736     * Get the verification agent timeout.
11737     *
11738     * @return verification timeout in milliseconds
11739     */
11740    private long getVerificationTimeout() {
11741        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11742                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11743                DEFAULT_VERIFICATION_TIMEOUT);
11744    }
11745
11746    /**
11747     * Get the default verification agent response code.
11748     *
11749     * @return default verification response code
11750     */
11751    private int getDefaultVerificationResponse() {
11752        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11753                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11754                DEFAULT_VERIFICATION_RESPONSE);
11755    }
11756
11757    /**
11758     * Check whether or not package verification has been enabled.
11759     *
11760     * @return true if verification should be performed
11761     */
11762    private boolean isVerificationEnabled(int userId, int installFlags) {
11763        if (!DEFAULT_VERIFY_ENABLE) {
11764            return false;
11765        }
11766        // Ephemeral apps don't get the full verification treatment
11767        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11768            if (DEBUG_EPHEMERAL) {
11769                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11770            }
11771            return false;
11772        }
11773
11774        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11775
11776        // Check if installing from ADB
11777        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11778            // Do not run verification in a test harness environment
11779            if (ActivityManager.isRunningInTestHarness()) {
11780                return false;
11781            }
11782            if (ensureVerifyAppsEnabled) {
11783                return true;
11784            }
11785            // Check if the developer does not want package verification for ADB installs
11786            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11787                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11788                return false;
11789            }
11790        }
11791
11792        if (ensureVerifyAppsEnabled) {
11793            return true;
11794        }
11795
11796        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11797                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11798    }
11799
11800    @Override
11801    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11802            throws RemoteException {
11803        mContext.enforceCallingOrSelfPermission(
11804                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11805                "Only intentfilter verification agents can verify applications");
11806
11807        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11808        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11809                Binder.getCallingUid(), verificationCode, failedDomains);
11810        msg.arg1 = id;
11811        msg.obj = response;
11812        mHandler.sendMessage(msg);
11813    }
11814
11815    @Override
11816    public int getIntentVerificationStatus(String packageName, int userId) {
11817        synchronized (mPackages) {
11818            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11819        }
11820    }
11821
11822    @Override
11823    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11824        mContext.enforceCallingOrSelfPermission(
11825                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11826
11827        boolean result = false;
11828        synchronized (mPackages) {
11829            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11830        }
11831        if (result) {
11832            scheduleWritePackageRestrictionsLocked(userId);
11833        }
11834        return result;
11835    }
11836
11837    @Override
11838    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11839            String packageName) {
11840        synchronized (mPackages) {
11841            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11842        }
11843    }
11844
11845    @Override
11846    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11847        if (TextUtils.isEmpty(packageName)) {
11848            return ParceledListSlice.emptyList();
11849        }
11850        synchronized (mPackages) {
11851            PackageParser.Package pkg = mPackages.get(packageName);
11852            if (pkg == null || pkg.activities == null) {
11853                return ParceledListSlice.emptyList();
11854            }
11855            final int count = pkg.activities.size();
11856            ArrayList<IntentFilter> result = new ArrayList<>();
11857            for (int n=0; n<count; n++) {
11858                PackageParser.Activity activity = pkg.activities.get(n);
11859                if (activity.intents != null && activity.intents.size() > 0) {
11860                    result.addAll(activity.intents);
11861                }
11862            }
11863            return new ParceledListSlice<>(result);
11864        }
11865    }
11866
11867    @Override
11868    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11869        mContext.enforceCallingOrSelfPermission(
11870                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11871
11872        synchronized (mPackages) {
11873            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11874            if (packageName != null) {
11875                result |= updateIntentVerificationStatus(packageName,
11876                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11877                        userId);
11878                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11879                        packageName, userId);
11880            }
11881            return result;
11882        }
11883    }
11884
11885    @Override
11886    public String getDefaultBrowserPackageName(int userId) {
11887        synchronized (mPackages) {
11888            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11889        }
11890    }
11891
11892    /**
11893     * Get the "allow unknown sources" setting.
11894     *
11895     * @return the current "allow unknown sources" setting
11896     */
11897    private int getUnknownSourcesSettings() {
11898        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11899                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11900                -1);
11901    }
11902
11903    @Override
11904    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11905        final int uid = Binder.getCallingUid();
11906        // writer
11907        synchronized (mPackages) {
11908            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11909            if (targetPackageSetting == null) {
11910                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11911            }
11912
11913            PackageSetting installerPackageSetting;
11914            if (installerPackageName != null) {
11915                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11916                if (installerPackageSetting == null) {
11917                    throw new IllegalArgumentException("Unknown installer package: "
11918                            + installerPackageName);
11919                }
11920            } else {
11921                installerPackageSetting = null;
11922            }
11923
11924            Signature[] callerSignature;
11925            Object obj = mSettings.getUserIdLPr(uid);
11926            if (obj != null) {
11927                if (obj instanceof SharedUserSetting) {
11928                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11929                } else if (obj instanceof PackageSetting) {
11930                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11931                } else {
11932                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11933                }
11934            } else {
11935                throw new SecurityException("Unknown calling UID: " + uid);
11936            }
11937
11938            // Verify: can't set installerPackageName to a package that is
11939            // not signed with the same cert as the caller.
11940            if (installerPackageSetting != null) {
11941                if (compareSignatures(callerSignature,
11942                        installerPackageSetting.signatures.mSignatures)
11943                        != PackageManager.SIGNATURE_MATCH) {
11944                    throw new SecurityException(
11945                            "Caller does not have same cert as new installer package "
11946                            + installerPackageName);
11947                }
11948            }
11949
11950            // Verify: if target already has an installer package, it must
11951            // be signed with the same cert as the caller.
11952            if (targetPackageSetting.installerPackageName != null) {
11953                PackageSetting setting = mSettings.mPackages.get(
11954                        targetPackageSetting.installerPackageName);
11955                // If the currently set package isn't valid, then it's always
11956                // okay to change it.
11957                if (setting != null) {
11958                    if (compareSignatures(callerSignature,
11959                            setting.signatures.mSignatures)
11960                            != PackageManager.SIGNATURE_MATCH) {
11961                        throw new SecurityException(
11962                                "Caller does not have same cert as old installer package "
11963                                + targetPackageSetting.installerPackageName);
11964                    }
11965                }
11966            }
11967
11968            // Okay!
11969            targetPackageSetting.installerPackageName = installerPackageName;
11970            if (installerPackageName != null) {
11971                mSettings.mInstallerPackages.add(installerPackageName);
11972            }
11973            scheduleWriteSettingsLocked();
11974        }
11975    }
11976
11977    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11978        // Queue up an async operation since the package installation may take a little while.
11979        mHandler.post(new Runnable() {
11980            public void run() {
11981                mHandler.removeCallbacks(this);
11982                 // Result object to be returned
11983                PackageInstalledInfo res = new PackageInstalledInfo();
11984                res.setReturnCode(currentStatus);
11985                res.uid = -1;
11986                res.pkg = null;
11987                res.removedInfo = null;
11988                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11989                    args.doPreInstall(res.returnCode);
11990                    synchronized (mInstallLock) {
11991                        installPackageTracedLI(args, res);
11992                    }
11993                    args.doPostInstall(res.returnCode, res.uid);
11994                }
11995
11996                // A restore should be performed at this point if (a) the install
11997                // succeeded, (b) the operation is not an update, and (c) the new
11998                // package has not opted out of backup participation.
11999                final boolean update = res.removedInfo != null
12000                        && res.removedInfo.removedPackage != null;
12001                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12002                boolean doRestore = !update
12003                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12004
12005                // Set up the post-install work request bookkeeping.  This will be used
12006                // and cleaned up by the post-install event handling regardless of whether
12007                // there's a restore pass performed.  Token values are >= 1.
12008                int token;
12009                if (mNextInstallToken < 0) mNextInstallToken = 1;
12010                token = mNextInstallToken++;
12011
12012                PostInstallData data = new PostInstallData(args, res);
12013                mRunningInstalls.put(token, data);
12014                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12015
12016                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12017                    // Pass responsibility to the Backup Manager.  It will perform a
12018                    // restore if appropriate, then pass responsibility back to the
12019                    // Package Manager to run the post-install observer callbacks
12020                    // and broadcasts.
12021                    IBackupManager bm = IBackupManager.Stub.asInterface(
12022                            ServiceManager.getService(Context.BACKUP_SERVICE));
12023                    if (bm != null) {
12024                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12025                                + " to BM for possible restore");
12026                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12027                        try {
12028                            // TODO: http://b/22388012
12029                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12030                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12031                            } else {
12032                                doRestore = false;
12033                            }
12034                        } catch (RemoteException e) {
12035                            // can't happen; the backup manager is local
12036                        } catch (Exception e) {
12037                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12038                            doRestore = false;
12039                        }
12040                    } else {
12041                        Slog.e(TAG, "Backup Manager not found!");
12042                        doRestore = false;
12043                    }
12044                }
12045
12046                if (!doRestore) {
12047                    // No restore possible, or the Backup Manager was mysteriously not
12048                    // available -- just fire the post-install work request directly.
12049                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12050
12051                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12052
12053                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12054                    mHandler.sendMessage(msg);
12055                }
12056            }
12057        });
12058    }
12059
12060    /**
12061     * Callback from PackageSettings whenever an app is first transitioned out of the
12062     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12063     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12064     * here whether the app is the target of an ongoing install, and only send the
12065     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12066     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12067     * handling.
12068     */
12069    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12070        // Serialize this with the rest of the install-process message chain.  In the
12071        // restore-at-install case, this Runnable will necessarily run before the
12072        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12073        // are coherent.  In the non-restore case, the app has already completed install
12074        // and been launched through some other means, so it is not in a problematic
12075        // state for observers to see the FIRST_LAUNCH signal.
12076        mHandler.post(new Runnable() {
12077            @Override
12078            public void run() {
12079                for (int i = 0; i < mRunningInstalls.size(); i++) {
12080                    final PostInstallData data = mRunningInstalls.valueAt(i);
12081                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12082                        // right package; but is it for the right user?
12083                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12084                            if (userId == data.res.newUsers[uIndex]) {
12085                                if (DEBUG_BACKUP) {
12086                                    Slog.i(TAG, "Package " + pkgName
12087                                            + " being restored so deferring FIRST_LAUNCH");
12088                                }
12089                                return;
12090                            }
12091                        }
12092                    }
12093                }
12094                // didn't find it, so not being restored
12095                if (DEBUG_BACKUP) {
12096                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12097                }
12098                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12099            }
12100        });
12101    }
12102
12103    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12104        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12105                installerPkg, null, userIds);
12106    }
12107
12108    private abstract class HandlerParams {
12109        private static final int MAX_RETRIES = 4;
12110
12111        /**
12112         * Number of times startCopy() has been attempted and had a non-fatal
12113         * error.
12114         */
12115        private int mRetries = 0;
12116
12117        /** User handle for the user requesting the information or installation. */
12118        private final UserHandle mUser;
12119        String traceMethod;
12120        int traceCookie;
12121
12122        HandlerParams(UserHandle user) {
12123            mUser = user;
12124        }
12125
12126        UserHandle getUser() {
12127            return mUser;
12128        }
12129
12130        HandlerParams setTraceMethod(String traceMethod) {
12131            this.traceMethod = traceMethod;
12132            return this;
12133        }
12134
12135        HandlerParams setTraceCookie(int traceCookie) {
12136            this.traceCookie = traceCookie;
12137            return this;
12138        }
12139
12140        final boolean startCopy() {
12141            boolean res;
12142            try {
12143                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12144
12145                if (++mRetries > MAX_RETRIES) {
12146                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12147                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12148                    handleServiceError();
12149                    return false;
12150                } else {
12151                    handleStartCopy();
12152                    res = true;
12153                }
12154            } catch (RemoteException e) {
12155                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12156                mHandler.sendEmptyMessage(MCS_RECONNECT);
12157                res = false;
12158            }
12159            handleReturnCode();
12160            return res;
12161        }
12162
12163        final void serviceError() {
12164            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12165            handleServiceError();
12166            handleReturnCode();
12167        }
12168
12169        abstract void handleStartCopy() throws RemoteException;
12170        abstract void handleServiceError();
12171        abstract void handleReturnCode();
12172    }
12173
12174    class MeasureParams extends HandlerParams {
12175        private final PackageStats mStats;
12176        private boolean mSuccess;
12177
12178        private final IPackageStatsObserver mObserver;
12179
12180        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12181            super(new UserHandle(stats.userHandle));
12182            mObserver = observer;
12183            mStats = stats;
12184        }
12185
12186        @Override
12187        public String toString() {
12188            return "MeasureParams{"
12189                + Integer.toHexString(System.identityHashCode(this))
12190                + " " + mStats.packageName + "}";
12191        }
12192
12193        @Override
12194        void handleStartCopy() throws RemoteException {
12195            synchronized (mInstallLock) {
12196                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12197            }
12198
12199            if (mSuccess) {
12200                final boolean mounted;
12201                if (Environment.isExternalStorageEmulated()) {
12202                    mounted = true;
12203                } else {
12204                    final String status = Environment.getExternalStorageState();
12205                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12206                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12207                }
12208
12209                if (mounted) {
12210                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12211
12212                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12213                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12214
12215                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12216                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12217
12218                    // Always subtract cache size, since it's a subdirectory
12219                    mStats.externalDataSize -= mStats.externalCacheSize;
12220
12221                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12222                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12223
12224                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12225                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12226                }
12227            }
12228        }
12229
12230        @Override
12231        void handleReturnCode() {
12232            if (mObserver != null) {
12233                try {
12234                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12235                } catch (RemoteException e) {
12236                    Slog.i(TAG, "Observer no longer exists.");
12237                }
12238            }
12239        }
12240
12241        @Override
12242        void handleServiceError() {
12243            Slog.e(TAG, "Could not measure application " + mStats.packageName
12244                            + " external storage");
12245        }
12246    }
12247
12248    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12249            throws RemoteException {
12250        long result = 0;
12251        for (File path : paths) {
12252            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12253        }
12254        return result;
12255    }
12256
12257    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12258        for (File path : paths) {
12259            try {
12260                mcs.clearDirectory(path.getAbsolutePath());
12261            } catch (RemoteException e) {
12262            }
12263        }
12264    }
12265
12266    static class OriginInfo {
12267        /**
12268         * Location where install is coming from, before it has been
12269         * copied/renamed into place. This could be a single monolithic APK
12270         * file, or a cluster directory. This location may be untrusted.
12271         */
12272        final File file;
12273        final String cid;
12274
12275        /**
12276         * Flag indicating that {@link #file} or {@link #cid} has already been
12277         * staged, meaning downstream users don't need to defensively copy the
12278         * contents.
12279         */
12280        final boolean staged;
12281
12282        /**
12283         * Flag indicating that {@link #file} or {@link #cid} is an already
12284         * installed app that is being moved.
12285         */
12286        final boolean existing;
12287
12288        final String resolvedPath;
12289        final File resolvedFile;
12290
12291        static OriginInfo fromNothing() {
12292            return new OriginInfo(null, null, false, false);
12293        }
12294
12295        static OriginInfo fromUntrustedFile(File file) {
12296            return new OriginInfo(file, null, false, false);
12297        }
12298
12299        static OriginInfo fromExistingFile(File file) {
12300            return new OriginInfo(file, null, false, true);
12301        }
12302
12303        static OriginInfo fromStagedFile(File file) {
12304            return new OriginInfo(file, null, true, false);
12305        }
12306
12307        static OriginInfo fromStagedContainer(String cid) {
12308            return new OriginInfo(null, cid, true, false);
12309        }
12310
12311        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12312            this.file = file;
12313            this.cid = cid;
12314            this.staged = staged;
12315            this.existing = existing;
12316
12317            if (cid != null) {
12318                resolvedPath = PackageHelper.getSdDir(cid);
12319                resolvedFile = new File(resolvedPath);
12320            } else if (file != null) {
12321                resolvedPath = file.getAbsolutePath();
12322                resolvedFile = file;
12323            } else {
12324                resolvedPath = null;
12325                resolvedFile = null;
12326            }
12327        }
12328    }
12329
12330    static class MoveInfo {
12331        final int moveId;
12332        final String fromUuid;
12333        final String toUuid;
12334        final String packageName;
12335        final String dataAppName;
12336        final int appId;
12337        final String seinfo;
12338        final int targetSdkVersion;
12339
12340        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12341                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12342            this.moveId = moveId;
12343            this.fromUuid = fromUuid;
12344            this.toUuid = toUuid;
12345            this.packageName = packageName;
12346            this.dataAppName = dataAppName;
12347            this.appId = appId;
12348            this.seinfo = seinfo;
12349            this.targetSdkVersion = targetSdkVersion;
12350        }
12351    }
12352
12353    static class VerificationInfo {
12354        /** A constant used to indicate that a uid value is not present. */
12355        public static final int NO_UID = -1;
12356
12357        /** URI referencing where the package was downloaded from. */
12358        final Uri originatingUri;
12359
12360        /** HTTP referrer URI associated with the originatingURI. */
12361        final Uri referrer;
12362
12363        /** UID of the application that the install request originated from. */
12364        final int originatingUid;
12365
12366        /** UID of application requesting the install */
12367        final int installerUid;
12368
12369        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12370            this.originatingUri = originatingUri;
12371            this.referrer = referrer;
12372            this.originatingUid = originatingUid;
12373            this.installerUid = installerUid;
12374        }
12375    }
12376
12377    class InstallParams extends HandlerParams {
12378        final OriginInfo origin;
12379        final MoveInfo move;
12380        final IPackageInstallObserver2 observer;
12381        int installFlags;
12382        final String installerPackageName;
12383        final String volumeUuid;
12384        private InstallArgs mArgs;
12385        private int mRet;
12386        final String packageAbiOverride;
12387        final String[] grantedRuntimePermissions;
12388        final VerificationInfo verificationInfo;
12389        final Certificate[][] certificates;
12390
12391        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12392                int installFlags, String installerPackageName, String volumeUuid,
12393                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12394                String[] grantedPermissions, Certificate[][] certificates) {
12395            super(user);
12396            this.origin = origin;
12397            this.move = move;
12398            this.observer = observer;
12399            this.installFlags = installFlags;
12400            this.installerPackageName = installerPackageName;
12401            this.volumeUuid = volumeUuid;
12402            this.verificationInfo = verificationInfo;
12403            this.packageAbiOverride = packageAbiOverride;
12404            this.grantedRuntimePermissions = grantedPermissions;
12405            this.certificates = certificates;
12406        }
12407
12408        @Override
12409        public String toString() {
12410            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12411                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12412        }
12413
12414        private int installLocationPolicy(PackageInfoLite pkgLite) {
12415            String packageName = pkgLite.packageName;
12416            int installLocation = pkgLite.installLocation;
12417            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12418            // reader
12419            synchronized (mPackages) {
12420                // Currently installed package which the new package is attempting to replace or
12421                // null if no such package is installed.
12422                PackageParser.Package installedPkg = mPackages.get(packageName);
12423                // Package which currently owns the data which the new package will own if installed.
12424                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12425                // will be null whereas dataOwnerPkg will contain information about the package
12426                // which was uninstalled while keeping its data.
12427                PackageParser.Package dataOwnerPkg = installedPkg;
12428                if (dataOwnerPkg  == null) {
12429                    PackageSetting ps = mSettings.mPackages.get(packageName);
12430                    if (ps != null) {
12431                        dataOwnerPkg = ps.pkg;
12432                    }
12433                }
12434
12435                if (dataOwnerPkg != null) {
12436                    // If installed, the package will get access to data left on the device by its
12437                    // predecessor. As a security measure, this is permited only if this is not a
12438                    // version downgrade or if the predecessor package is marked as debuggable and
12439                    // a downgrade is explicitly requested.
12440                    //
12441                    // On debuggable platform builds, downgrades are permitted even for
12442                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12443                    // not offer security guarantees and thus it's OK to disable some security
12444                    // mechanisms to make debugging/testing easier on those builds. However, even on
12445                    // debuggable builds downgrades of packages are permitted only if requested via
12446                    // installFlags. This is because we aim to keep the behavior of debuggable
12447                    // platform builds as close as possible to the behavior of non-debuggable
12448                    // platform builds.
12449                    final boolean downgradeRequested =
12450                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12451                    final boolean packageDebuggable =
12452                                (dataOwnerPkg.applicationInfo.flags
12453                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12454                    final boolean downgradePermitted =
12455                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12456                    if (!downgradePermitted) {
12457                        try {
12458                            checkDowngrade(dataOwnerPkg, pkgLite);
12459                        } catch (PackageManagerException e) {
12460                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12461                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12462                        }
12463                    }
12464                }
12465
12466                if (installedPkg != null) {
12467                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12468                        // Check for updated system application.
12469                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12470                            if (onSd) {
12471                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12472                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12473                            }
12474                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12475                        } else {
12476                            if (onSd) {
12477                                // Install flag overrides everything.
12478                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12479                            }
12480                            // If current upgrade specifies particular preference
12481                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12482                                // Application explicitly specified internal.
12483                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12484                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12485                                // App explictly prefers external. Let policy decide
12486                            } else {
12487                                // Prefer previous location
12488                                if (isExternal(installedPkg)) {
12489                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12490                                }
12491                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12492                            }
12493                        }
12494                    } else {
12495                        // Invalid install. Return error code
12496                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12497                    }
12498                }
12499            }
12500            // All the special cases have been taken care of.
12501            // Return result based on recommended install location.
12502            if (onSd) {
12503                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12504            }
12505            return pkgLite.recommendedInstallLocation;
12506        }
12507
12508        /*
12509         * Invoke remote method to get package information and install
12510         * location values. Override install location based on default
12511         * policy if needed and then create install arguments based
12512         * on the install location.
12513         */
12514        public void handleStartCopy() throws RemoteException {
12515            int ret = PackageManager.INSTALL_SUCCEEDED;
12516
12517            // If we're already staged, we've firmly committed to an install location
12518            if (origin.staged) {
12519                if (origin.file != null) {
12520                    installFlags |= PackageManager.INSTALL_INTERNAL;
12521                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12522                } else if (origin.cid != null) {
12523                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12524                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12525                } else {
12526                    throw new IllegalStateException("Invalid stage location");
12527                }
12528            }
12529
12530            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12531            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12532            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12533            PackageInfoLite pkgLite = null;
12534
12535            if (onInt && onSd) {
12536                // Check if both bits are set.
12537                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12538                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12539            } else if (onSd && ephemeral) {
12540                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12541                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12542            } else {
12543                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12544                        packageAbiOverride);
12545
12546                if (DEBUG_EPHEMERAL && ephemeral) {
12547                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12548                }
12549
12550                /*
12551                 * If we have too little free space, try to free cache
12552                 * before giving up.
12553                 */
12554                if (!origin.staged && pkgLite.recommendedInstallLocation
12555                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12556                    // TODO: focus freeing disk space on the target device
12557                    final StorageManager storage = StorageManager.from(mContext);
12558                    final long lowThreshold = storage.getStorageLowBytes(
12559                            Environment.getDataDirectory());
12560
12561                    final long sizeBytes = mContainerService.calculateInstalledSize(
12562                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12563
12564                    try {
12565                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12566                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12567                                installFlags, packageAbiOverride);
12568                    } catch (InstallerException e) {
12569                        Slog.w(TAG, "Failed to free cache", e);
12570                    }
12571
12572                    /*
12573                     * The cache free must have deleted the file we
12574                     * downloaded to install.
12575                     *
12576                     * TODO: fix the "freeCache" call to not delete
12577                     *       the file we care about.
12578                     */
12579                    if (pkgLite.recommendedInstallLocation
12580                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12581                        pkgLite.recommendedInstallLocation
12582                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12583                    }
12584                }
12585            }
12586
12587            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12588                int loc = pkgLite.recommendedInstallLocation;
12589                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12590                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12591                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12592                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12593                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12594                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12595                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12596                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12597                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12598                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12599                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12600                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12601                } else {
12602                    // Override with defaults if needed.
12603                    loc = installLocationPolicy(pkgLite);
12604                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12605                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12606                    } else if (!onSd && !onInt) {
12607                        // Override install location with flags
12608                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12609                            // Set the flag to install on external media.
12610                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12611                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12612                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12613                            if (DEBUG_EPHEMERAL) {
12614                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12615                            }
12616                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12617                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12618                                    |PackageManager.INSTALL_INTERNAL);
12619                        } else {
12620                            // Make sure the flag for installing on external
12621                            // media is unset
12622                            installFlags |= PackageManager.INSTALL_INTERNAL;
12623                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12624                        }
12625                    }
12626                }
12627            }
12628
12629            final InstallArgs args = createInstallArgs(this);
12630            mArgs = args;
12631
12632            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12633                // TODO: http://b/22976637
12634                // Apps installed for "all" users use the device owner to verify the app
12635                UserHandle verifierUser = getUser();
12636                if (verifierUser == UserHandle.ALL) {
12637                    verifierUser = UserHandle.SYSTEM;
12638                }
12639
12640                /*
12641                 * Determine if we have any installed package verifiers. If we
12642                 * do, then we'll defer to them to verify the packages.
12643                 */
12644                final int requiredUid = mRequiredVerifierPackage == null ? -1
12645                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12646                                verifierUser.getIdentifier());
12647                if (!origin.existing && requiredUid != -1
12648                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12649                    final Intent verification = new Intent(
12650                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12651                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12652                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12653                            PACKAGE_MIME_TYPE);
12654                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12655
12656                    // Query all live verifiers based on current user state
12657                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12658                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12659
12660                    if (DEBUG_VERIFY) {
12661                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12662                                + verification.toString() + " with " + pkgLite.verifiers.length
12663                                + " optional verifiers");
12664                    }
12665
12666                    final int verificationId = mPendingVerificationToken++;
12667
12668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12669
12670                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12671                            installerPackageName);
12672
12673                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12674                            installFlags);
12675
12676                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12677                            pkgLite.packageName);
12678
12679                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12680                            pkgLite.versionCode);
12681
12682                    if (verificationInfo != null) {
12683                        if (verificationInfo.originatingUri != null) {
12684                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12685                                    verificationInfo.originatingUri);
12686                        }
12687                        if (verificationInfo.referrer != null) {
12688                            verification.putExtra(Intent.EXTRA_REFERRER,
12689                                    verificationInfo.referrer);
12690                        }
12691                        if (verificationInfo.originatingUid >= 0) {
12692                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12693                                    verificationInfo.originatingUid);
12694                        }
12695                        if (verificationInfo.installerUid >= 0) {
12696                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12697                                    verificationInfo.installerUid);
12698                        }
12699                    }
12700
12701                    final PackageVerificationState verificationState = new PackageVerificationState(
12702                            requiredUid, args);
12703
12704                    mPendingVerification.append(verificationId, verificationState);
12705
12706                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12707                            receivers, verificationState);
12708
12709                    /*
12710                     * If any sufficient verifiers were listed in the package
12711                     * manifest, attempt to ask them.
12712                     */
12713                    if (sufficientVerifiers != null) {
12714                        final int N = sufficientVerifiers.size();
12715                        if (N == 0) {
12716                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12717                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12718                        } else {
12719                            for (int i = 0; i < N; i++) {
12720                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12721
12722                                final Intent sufficientIntent = new Intent(verification);
12723                                sufficientIntent.setComponent(verifierComponent);
12724                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12725                            }
12726                        }
12727                    }
12728
12729                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12730                            mRequiredVerifierPackage, receivers);
12731                    if (ret == PackageManager.INSTALL_SUCCEEDED
12732                            && mRequiredVerifierPackage != null) {
12733                        Trace.asyncTraceBegin(
12734                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12735                        /*
12736                         * Send the intent to the required verification agent,
12737                         * but only start the verification timeout after the
12738                         * target BroadcastReceivers have run.
12739                         */
12740                        verification.setComponent(requiredVerifierComponent);
12741                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12742                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12743                                new BroadcastReceiver() {
12744                                    @Override
12745                                    public void onReceive(Context context, Intent intent) {
12746                                        final Message msg = mHandler
12747                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12748                                        msg.arg1 = verificationId;
12749                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12750                                    }
12751                                }, null, 0, null, null);
12752
12753                        /*
12754                         * We don't want the copy to proceed until verification
12755                         * succeeds, so null out this field.
12756                         */
12757                        mArgs = null;
12758                    }
12759                } else {
12760                    /*
12761                     * No package verification is enabled, so immediately start
12762                     * the remote call to initiate copy using temporary file.
12763                     */
12764                    ret = args.copyApk(mContainerService, true);
12765                }
12766            }
12767
12768            mRet = ret;
12769        }
12770
12771        @Override
12772        void handleReturnCode() {
12773            // If mArgs is null, then MCS couldn't be reached. When it
12774            // reconnects, it will try again to install. At that point, this
12775            // will succeed.
12776            if (mArgs != null) {
12777                processPendingInstall(mArgs, mRet);
12778            }
12779        }
12780
12781        @Override
12782        void handleServiceError() {
12783            mArgs = createInstallArgs(this);
12784            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12785        }
12786
12787        public boolean isForwardLocked() {
12788            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12789        }
12790    }
12791
12792    /**
12793     * Used during creation of InstallArgs
12794     *
12795     * @param installFlags package installation flags
12796     * @return true if should be installed on external storage
12797     */
12798    private static boolean installOnExternalAsec(int installFlags) {
12799        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12800            return false;
12801        }
12802        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12803            return true;
12804        }
12805        return false;
12806    }
12807
12808    /**
12809     * Used during creation of InstallArgs
12810     *
12811     * @param installFlags package installation flags
12812     * @return true if should be installed as forward locked
12813     */
12814    private static boolean installForwardLocked(int installFlags) {
12815        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12816    }
12817
12818    private InstallArgs createInstallArgs(InstallParams params) {
12819        if (params.move != null) {
12820            return new MoveInstallArgs(params);
12821        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12822            return new AsecInstallArgs(params);
12823        } else {
12824            return new FileInstallArgs(params);
12825        }
12826    }
12827
12828    /**
12829     * Create args that describe an existing installed package. Typically used
12830     * when cleaning up old installs, or used as a move source.
12831     */
12832    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12833            String resourcePath, String[] instructionSets) {
12834        final boolean isInAsec;
12835        if (installOnExternalAsec(installFlags)) {
12836            /* Apps on SD card are always in ASEC containers. */
12837            isInAsec = true;
12838        } else if (installForwardLocked(installFlags)
12839                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12840            /*
12841             * Forward-locked apps are only in ASEC containers if they're the
12842             * new style
12843             */
12844            isInAsec = true;
12845        } else {
12846            isInAsec = false;
12847        }
12848
12849        if (isInAsec) {
12850            return new AsecInstallArgs(codePath, instructionSets,
12851                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12852        } else {
12853            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12854        }
12855    }
12856
12857    static abstract class InstallArgs {
12858        /** @see InstallParams#origin */
12859        final OriginInfo origin;
12860        /** @see InstallParams#move */
12861        final MoveInfo move;
12862
12863        final IPackageInstallObserver2 observer;
12864        // Always refers to PackageManager flags only
12865        final int installFlags;
12866        final String installerPackageName;
12867        final String volumeUuid;
12868        final UserHandle user;
12869        final String abiOverride;
12870        final String[] installGrantPermissions;
12871        /** If non-null, drop an async trace when the install completes */
12872        final String traceMethod;
12873        final int traceCookie;
12874        final Certificate[][] certificates;
12875
12876        // The list of instruction sets supported by this app. This is currently
12877        // only used during the rmdex() phase to clean up resources. We can get rid of this
12878        // if we move dex files under the common app path.
12879        /* nullable */ String[] instructionSets;
12880
12881        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12882                int installFlags, String installerPackageName, String volumeUuid,
12883                UserHandle user, String[] instructionSets,
12884                String abiOverride, String[] installGrantPermissions,
12885                String traceMethod, int traceCookie, Certificate[][] certificates) {
12886            this.origin = origin;
12887            this.move = move;
12888            this.installFlags = installFlags;
12889            this.observer = observer;
12890            this.installerPackageName = installerPackageName;
12891            this.volumeUuid = volumeUuid;
12892            this.user = user;
12893            this.instructionSets = instructionSets;
12894            this.abiOverride = abiOverride;
12895            this.installGrantPermissions = installGrantPermissions;
12896            this.traceMethod = traceMethod;
12897            this.traceCookie = traceCookie;
12898            this.certificates = certificates;
12899        }
12900
12901        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12902        abstract int doPreInstall(int status);
12903
12904        /**
12905         * Rename package into final resting place. All paths on the given
12906         * scanned package should be updated to reflect the rename.
12907         */
12908        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12909        abstract int doPostInstall(int status, int uid);
12910
12911        /** @see PackageSettingBase#codePathString */
12912        abstract String getCodePath();
12913        /** @see PackageSettingBase#resourcePathString */
12914        abstract String getResourcePath();
12915
12916        // Need installer lock especially for dex file removal.
12917        abstract void cleanUpResourcesLI();
12918        abstract boolean doPostDeleteLI(boolean delete);
12919
12920        /**
12921         * Called before the source arguments are copied. This is used mostly
12922         * for MoveParams when it needs to read the source file to put it in the
12923         * destination.
12924         */
12925        int doPreCopy() {
12926            return PackageManager.INSTALL_SUCCEEDED;
12927        }
12928
12929        /**
12930         * Called after the source arguments are copied. This is used mostly for
12931         * MoveParams when it needs to read the source file to put it in the
12932         * destination.
12933         */
12934        int doPostCopy(int uid) {
12935            return PackageManager.INSTALL_SUCCEEDED;
12936        }
12937
12938        protected boolean isFwdLocked() {
12939            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12940        }
12941
12942        protected boolean isExternalAsec() {
12943            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12944        }
12945
12946        protected boolean isEphemeral() {
12947            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12948        }
12949
12950        UserHandle getUser() {
12951            return user;
12952        }
12953    }
12954
12955    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12956        if (!allCodePaths.isEmpty()) {
12957            if (instructionSets == null) {
12958                throw new IllegalStateException("instructionSet == null");
12959            }
12960            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12961            for (String codePath : allCodePaths) {
12962                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12963                    try {
12964                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12965                    } catch (InstallerException ignored) {
12966                    }
12967                }
12968            }
12969        }
12970    }
12971
12972    /**
12973     * Logic to handle installation of non-ASEC applications, including copying
12974     * and renaming logic.
12975     */
12976    class FileInstallArgs extends InstallArgs {
12977        private File codeFile;
12978        private File resourceFile;
12979
12980        // Example topology:
12981        // /data/app/com.example/base.apk
12982        // /data/app/com.example/split_foo.apk
12983        // /data/app/com.example/lib/arm/libfoo.so
12984        // /data/app/com.example/lib/arm64/libfoo.so
12985        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12986
12987        /** New install */
12988        FileInstallArgs(InstallParams params) {
12989            super(params.origin, params.move, params.observer, params.installFlags,
12990                    params.installerPackageName, params.volumeUuid,
12991                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12992                    params.grantedRuntimePermissions,
12993                    params.traceMethod, params.traceCookie, params.certificates);
12994            if (isFwdLocked()) {
12995                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12996            }
12997        }
12998
12999        /** Existing install */
13000        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13001            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13002                    null, null, null, 0, null /*certificates*/);
13003            this.codeFile = (codePath != null) ? new File(codePath) : null;
13004            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13005        }
13006
13007        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13008            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13009            try {
13010                return doCopyApk(imcs, temp);
13011            } finally {
13012                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13013            }
13014        }
13015
13016        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13017            if (origin.staged) {
13018                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13019                codeFile = origin.file;
13020                resourceFile = origin.file;
13021                return PackageManager.INSTALL_SUCCEEDED;
13022            }
13023
13024            try {
13025                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13026                final File tempDir =
13027                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13028                codeFile = tempDir;
13029                resourceFile = tempDir;
13030            } catch (IOException e) {
13031                Slog.w(TAG, "Failed to create copy file: " + e);
13032                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13033            }
13034
13035            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13036                @Override
13037                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13038                    if (!FileUtils.isValidExtFilename(name)) {
13039                        throw new IllegalArgumentException("Invalid filename: " + name);
13040                    }
13041                    try {
13042                        final File file = new File(codeFile, name);
13043                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13044                                O_RDWR | O_CREAT, 0644);
13045                        Os.chmod(file.getAbsolutePath(), 0644);
13046                        return new ParcelFileDescriptor(fd);
13047                    } catch (ErrnoException e) {
13048                        throw new RemoteException("Failed to open: " + e.getMessage());
13049                    }
13050                }
13051            };
13052
13053            int ret = PackageManager.INSTALL_SUCCEEDED;
13054            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13055            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13056                Slog.e(TAG, "Failed to copy package");
13057                return ret;
13058            }
13059
13060            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13061            NativeLibraryHelper.Handle handle = null;
13062            try {
13063                handle = NativeLibraryHelper.Handle.create(codeFile);
13064                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13065                        abiOverride);
13066            } catch (IOException e) {
13067                Slog.e(TAG, "Copying native libraries failed", e);
13068                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13069            } finally {
13070                IoUtils.closeQuietly(handle);
13071            }
13072
13073            return ret;
13074        }
13075
13076        int doPreInstall(int status) {
13077            if (status != PackageManager.INSTALL_SUCCEEDED) {
13078                cleanUp();
13079            }
13080            return status;
13081        }
13082
13083        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13084            if (status != PackageManager.INSTALL_SUCCEEDED) {
13085                cleanUp();
13086                return false;
13087            }
13088
13089            final File targetDir = codeFile.getParentFile();
13090            final File beforeCodeFile = codeFile;
13091            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13092
13093            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13094            try {
13095                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13096            } catch (ErrnoException e) {
13097                Slog.w(TAG, "Failed to rename", e);
13098                return false;
13099            }
13100
13101            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13102                Slog.w(TAG, "Failed to restorecon");
13103                return false;
13104            }
13105
13106            // Reflect the rename internally
13107            codeFile = afterCodeFile;
13108            resourceFile = afterCodeFile;
13109
13110            // Reflect the rename in scanned details
13111            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13112            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13113                    afterCodeFile, pkg.baseCodePath));
13114            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13115                    afterCodeFile, pkg.splitCodePaths));
13116
13117            // Reflect the rename in app info
13118            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13119            pkg.setApplicationInfoCodePath(pkg.codePath);
13120            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13121            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13122            pkg.setApplicationInfoResourcePath(pkg.codePath);
13123            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13124            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13125
13126            return true;
13127        }
13128
13129        int doPostInstall(int status, int uid) {
13130            if (status != PackageManager.INSTALL_SUCCEEDED) {
13131                cleanUp();
13132            }
13133            return status;
13134        }
13135
13136        @Override
13137        String getCodePath() {
13138            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13139        }
13140
13141        @Override
13142        String getResourcePath() {
13143            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13144        }
13145
13146        private boolean cleanUp() {
13147            if (codeFile == null || !codeFile.exists()) {
13148                return false;
13149            }
13150
13151            removeCodePathLI(codeFile);
13152
13153            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13154                resourceFile.delete();
13155            }
13156
13157            return true;
13158        }
13159
13160        void cleanUpResourcesLI() {
13161            // Try enumerating all code paths before deleting
13162            List<String> allCodePaths = Collections.EMPTY_LIST;
13163            if (codeFile != null && codeFile.exists()) {
13164                try {
13165                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13166                    allCodePaths = pkg.getAllCodePaths();
13167                } catch (PackageParserException e) {
13168                    // Ignored; we tried our best
13169                }
13170            }
13171
13172            cleanUp();
13173            removeDexFiles(allCodePaths, instructionSets);
13174        }
13175
13176        boolean doPostDeleteLI(boolean delete) {
13177            // XXX err, shouldn't we respect the delete flag?
13178            cleanUpResourcesLI();
13179            return true;
13180        }
13181    }
13182
13183    private boolean isAsecExternal(String cid) {
13184        final String asecPath = PackageHelper.getSdFilesystem(cid);
13185        return !asecPath.startsWith(mAsecInternalPath);
13186    }
13187
13188    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13189            PackageManagerException {
13190        if (copyRet < 0) {
13191            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13192                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13193                throw new PackageManagerException(copyRet, message);
13194            }
13195        }
13196    }
13197
13198    /**
13199     * Extract the MountService "container ID" from the full code path of an
13200     * .apk.
13201     */
13202    static String cidFromCodePath(String fullCodePath) {
13203        int eidx = fullCodePath.lastIndexOf("/");
13204        String subStr1 = fullCodePath.substring(0, eidx);
13205        int sidx = subStr1.lastIndexOf("/");
13206        return subStr1.substring(sidx+1, eidx);
13207    }
13208
13209    /**
13210     * Logic to handle installation of ASEC applications, including copying and
13211     * renaming logic.
13212     */
13213    class AsecInstallArgs extends InstallArgs {
13214        static final String RES_FILE_NAME = "pkg.apk";
13215        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13216
13217        String cid;
13218        String packagePath;
13219        String resourcePath;
13220
13221        /** New install */
13222        AsecInstallArgs(InstallParams params) {
13223            super(params.origin, params.move, params.observer, params.installFlags,
13224                    params.installerPackageName, params.volumeUuid,
13225                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13226                    params.grantedRuntimePermissions,
13227                    params.traceMethod, params.traceCookie, params.certificates);
13228        }
13229
13230        /** Existing install */
13231        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13232                        boolean isExternal, boolean isForwardLocked) {
13233            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13234              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13235                    instructionSets, null, null, null, 0, null /*certificates*/);
13236            // Hackily pretend we're still looking at a full code path
13237            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13238                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13239            }
13240
13241            // Extract cid from fullCodePath
13242            int eidx = fullCodePath.lastIndexOf("/");
13243            String subStr1 = fullCodePath.substring(0, eidx);
13244            int sidx = subStr1.lastIndexOf("/");
13245            cid = subStr1.substring(sidx+1, eidx);
13246            setMountPath(subStr1);
13247        }
13248
13249        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13250            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13251              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13252                    instructionSets, null, null, null, 0, null /*certificates*/);
13253            this.cid = cid;
13254            setMountPath(PackageHelper.getSdDir(cid));
13255        }
13256
13257        void createCopyFile() {
13258            cid = mInstallerService.allocateExternalStageCidLegacy();
13259        }
13260
13261        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13262            if (origin.staged && origin.cid != null) {
13263                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13264                cid = origin.cid;
13265                setMountPath(PackageHelper.getSdDir(cid));
13266                return PackageManager.INSTALL_SUCCEEDED;
13267            }
13268
13269            if (temp) {
13270                createCopyFile();
13271            } else {
13272                /*
13273                 * Pre-emptively destroy the container since it's destroyed if
13274                 * copying fails due to it existing anyway.
13275                 */
13276                PackageHelper.destroySdDir(cid);
13277            }
13278
13279            final String newMountPath = imcs.copyPackageToContainer(
13280                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13281                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13282
13283            if (newMountPath != null) {
13284                setMountPath(newMountPath);
13285                return PackageManager.INSTALL_SUCCEEDED;
13286            } else {
13287                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13288            }
13289        }
13290
13291        @Override
13292        String getCodePath() {
13293            return packagePath;
13294        }
13295
13296        @Override
13297        String getResourcePath() {
13298            return resourcePath;
13299        }
13300
13301        int doPreInstall(int status) {
13302            if (status != PackageManager.INSTALL_SUCCEEDED) {
13303                // Destroy container
13304                PackageHelper.destroySdDir(cid);
13305            } else {
13306                boolean mounted = PackageHelper.isContainerMounted(cid);
13307                if (!mounted) {
13308                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13309                            Process.SYSTEM_UID);
13310                    if (newMountPath != null) {
13311                        setMountPath(newMountPath);
13312                    } else {
13313                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13314                    }
13315                }
13316            }
13317            return status;
13318        }
13319
13320        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13321            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13322            String newMountPath = null;
13323            if (PackageHelper.isContainerMounted(cid)) {
13324                // Unmount the container
13325                if (!PackageHelper.unMountSdDir(cid)) {
13326                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13327                    return false;
13328                }
13329            }
13330            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13331                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13332                        " which might be stale. Will try to clean up.");
13333                // Clean up the stale container and proceed to recreate.
13334                if (!PackageHelper.destroySdDir(newCacheId)) {
13335                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13336                    return false;
13337                }
13338                // Successfully cleaned up stale container. Try to rename again.
13339                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13340                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13341                            + " inspite of cleaning it up.");
13342                    return false;
13343                }
13344            }
13345            if (!PackageHelper.isContainerMounted(newCacheId)) {
13346                Slog.w(TAG, "Mounting container " + newCacheId);
13347                newMountPath = PackageHelper.mountSdDir(newCacheId,
13348                        getEncryptKey(), Process.SYSTEM_UID);
13349            } else {
13350                newMountPath = PackageHelper.getSdDir(newCacheId);
13351            }
13352            if (newMountPath == null) {
13353                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13354                return false;
13355            }
13356            Log.i(TAG, "Succesfully renamed " + cid +
13357                    " to " + newCacheId +
13358                    " at new path: " + newMountPath);
13359            cid = newCacheId;
13360
13361            final File beforeCodeFile = new File(packagePath);
13362            setMountPath(newMountPath);
13363            final File afterCodeFile = new File(packagePath);
13364
13365            // Reflect the rename in scanned details
13366            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13367            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13368                    afterCodeFile, pkg.baseCodePath));
13369            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13370                    afterCodeFile, pkg.splitCodePaths));
13371
13372            // Reflect the rename in app info
13373            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13374            pkg.setApplicationInfoCodePath(pkg.codePath);
13375            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13376            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13377            pkg.setApplicationInfoResourcePath(pkg.codePath);
13378            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13379            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13380
13381            return true;
13382        }
13383
13384        private void setMountPath(String mountPath) {
13385            final File mountFile = new File(mountPath);
13386
13387            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13388            if (monolithicFile.exists()) {
13389                packagePath = monolithicFile.getAbsolutePath();
13390                if (isFwdLocked()) {
13391                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13392                } else {
13393                    resourcePath = packagePath;
13394                }
13395            } else {
13396                packagePath = mountFile.getAbsolutePath();
13397                resourcePath = packagePath;
13398            }
13399        }
13400
13401        int doPostInstall(int status, int uid) {
13402            if (status != PackageManager.INSTALL_SUCCEEDED) {
13403                cleanUp();
13404            } else {
13405                final int groupOwner;
13406                final String protectedFile;
13407                if (isFwdLocked()) {
13408                    groupOwner = UserHandle.getSharedAppGid(uid);
13409                    protectedFile = RES_FILE_NAME;
13410                } else {
13411                    groupOwner = -1;
13412                    protectedFile = null;
13413                }
13414
13415                if (uid < Process.FIRST_APPLICATION_UID
13416                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13417                    Slog.e(TAG, "Failed to finalize " + cid);
13418                    PackageHelper.destroySdDir(cid);
13419                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13420                }
13421
13422                boolean mounted = PackageHelper.isContainerMounted(cid);
13423                if (!mounted) {
13424                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13425                }
13426            }
13427            return status;
13428        }
13429
13430        private void cleanUp() {
13431            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13432
13433            // Destroy secure container
13434            PackageHelper.destroySdDir(cid);
13435        }
13436
13437        private List<String> getAllCodePaths() {
13438            final File codeFile = new File(getCodePath());
13439            if (codeFile != null && codeFile.exists()) {
13440                try {
13441                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13442                    return pkg.getAllCodePaths();
13443                } catch (PackageParserException e) {
13444                    // Ignored; we tried our best
13445                }
13446            }
13447            return Collections.EMPTY_LIST;
13448        }
13449
13450        void cleanUpResourcesLI() {
13451            // Enumerate all code paths before deleting
13452            cleanUpResourcesLI(getAllCodePaths());
13453        }
13454
13455        private void cleanUpResourcesLI(List<String> allCodePaths) {
13456            cleanUp();
13457            removeDexFiles(allCodePaths, instructionSets);
13458        }
13459
13460        String getPackageName() {
13461            return getAsecPackageName(cid);
13462        }
13463
13464        boolean doPostDeleteLI(boolean delete) {
13465            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13466            final List<String> allCodePaths = getAllCodePaths();
13467            boolean mounted = PackageHelper.isContainerMounted(cid);
13468            if (mounted) {
13469                // Unmount first
13470                if (PackageHelper.unMountSdDir(cid)) {
13471                    mounted = false;
13472                }
13473            }
13474            if (!mounted && delete) {
13475                cleanUpResourcesLI(allCodePaths);
13476            }
13477            return !mounted;
13478        }
13479
13480        @Override
13481        int doPreCopy() {
13482            if (isFwdLocked()) {
13483                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13484                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13485                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13486                }
13487            }
13488
13489            return PackageManager.INSTALL_SUCCEEDED;
13490        }
13491
13492        @Override
13493        int doPostCopy(int uid) {
13494            if (isFwdLocked()) {
13495                if (uid < Process.FIRST_APPLICATION_UID
13496                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13497                                RES_FILE_NAME)) {
13498                    Slog.e(TAG, "Failed to finalize " + cid);
13499                    PackageHelper.destroySdDir(cid);
13500                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13501                }
13502            }
13503
13504            return PackageManager.INSTALL_SUCCEEDED;
13505        }
13506    }
13507
13508    /**
13509     * Logic to handle movement of existing installed applications.
13510     */
13511    class MoveInstallArgs extends InstallArgs {
13512        private File codeFile;
13513        private File resourceFile;
13514
13515        /** New install */
13516        MoveInstallArgs(InstallParams params) {
13517            super(params.origin, params.move, params.observer, params.installFlags,
13518                    params.installerPackageName, params.volumeUuid,
13519                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13520                    params.grantedRuntimePermissions,
13521                    params.traceMethod, params.traceCookie, params.certificates);
13522        }
13523
13524        int copyApk(IMediaContainerService imcs, boolean temp) {
13525            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13526                    + move.fromUuid + " to " + move.toUuid);
13527            synchronized (mInstaller) {
13528                try {
13529                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13530                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13531                } catch (InstallerException e) {
13532                    Slog.w(TAG, "Failed to move app", e);
13533                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13534                }
13535            }
13536
13537            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13538            resourceFile = codeFile;
13539            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13540
13541            return PackageManager.INSTALL_SUCCEEDED;
13542        }
13543
13544        int doPreInstall(int status) {
13545            if (status != PackageManager.INSTALL_SUCCEEDED) {
13546                cleanUp(move.toUuid);
13547            }
13548            return status;
13549        }
13550
13551        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13552            if (status != PackageManager.INSTALL_SUCCEEDED) {
13553                cleanUp(move.toUuid);
13554                return false;
13555            }
13556
13557            // Reflect the move in app info
13558            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13559            pkg.setApplicationInfoCodePath(pkg.codePath);
13560            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13561            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13562            pkg.setApplicationInfoResourcePath(pkg.codePath);
13563            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13564            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13565
13566            return true;
13567        }
13568
13569        int doPostInstall(int status, int uid) {
13570            if (status == PackageManager.INSTALL_SUCCEEDED) {
13571                cleanUp(move.fromUuid);
13572            } else {
13573                cleanUp(move.toUuid);
13574            }
13575            return status;
13576        }
13577
13578        @Override
13579        String getCodePath() {
13580            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13581        }
13582
13583        @Override
13584        String getResourcePath() {
13585            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13586        }
13587
13588        private boolean cleanUp(String volumeUuid) {
13589            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13590                    move.dataAppName);
13591            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13592            final int[] userIds = sUserManager.getUserIds();
13593            synchronized (mInstallLock) {
13594                // Clean up both app data and code
13595                // All package moves are frozen until finished
13596                for (int userId : userIds) {
13597                    try {
13598                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13599                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13600                    } catch (InstallerException e) {
13601                        Slog.w(TAG, String.valueOf(e));
13602                    }
13603                }
13604                removeCodePathLI(codeFile);
13605            }
13606            return true;
13607        }
13608
13609        void cleanUpResourcesLI() {
13610            throw new UnsupportedOperationException();
13611        }
13612
13613        boolean doPostDeleteLI(boolean delete) {
13614            throw new UnsupportedOperationException();
13615        }
13616    }
13617
13618    static String getAsecPackageName(String packageCid) {
13619        int idx = packageCid.lastIndexOf("-");
13620        if (idx == -1) {
13621            return packageCid;
13622        }
13623        return packageCid.substring(0, idx);
13624    }
13625
13626    // Utility method used to create code paths based on package name and available index.
13627    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13628        String idxStr = "";
13629        int idx = 1;
13630        // Fall back to default value of idx=1 if prefix is not
13631        // part of oldCodePath
13632        if (oldCodePath != null) {
13633            String subStr = oldCodePath;
13634            // Drop the suffix right away
13635            if (suffix != null && subStr.endsWith(suffix)) {
13636                subStr = subStr.substring(0, subStr.length() - suffix.length());
13637            }
13638            // If oldCodePath already contains prefix find out the
13639            // ending index to either increment or decrement.
13640            int sidx = subStr.lastIndexOf(prefix);
13641            if (sidx != -1) {
13642                subStr = subStr.substring(sidx + prefix.length());
13643                if (subStr != null) {
13644                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13645                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13646                    }
13647                    try {
13648                        idx = Integer.parseInt(subStr);
13649                        if (idx <= 1) {
13650                            idx++;
13651                        } else {
13652                            idx--;
13653                        }
13654                    } catch(NumberFormatException e) {
13655                    }
13656                }
13657            }
13658        }
13659        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13660        return prefix + idxStr;
13661    }
13662
13663    private File getNextCodePath(File targetDir, String packageName) {
13664        int suffix = 1;
13665        File result;
13666        do {
13667            result = new File(targetDir, packageName + "-" + suffix);
13668            suffix++;
13669        } while (result.exists());
13670        return result;
13671    }
13672
13673    // Utility method that returns the relative package path with respect
13674    // to the installation directory. Like say for /data/data/com.test-1.apk
13675    // string com.test-1 is returned.
13676    static String deriveCodePathName(String codePath) {
13677        if (codePath == null) {
13678            return null;
13679        }
13680        final File codeFile = new File(codePath);
13681        final String name = codeFile.getName();
13682        if (codeFile.isDirectory()) {
13683            return name;
13684        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13685            final int lastDot = name.lastIndexOf('.');
13686            return name.substring(0, lastDot);
13687        } else {
13688            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13689            return null;
13690        }
13691    }
13692
13693    static class PackageInstalledInfo {
13694        String name;
13695        int uid;
13696        // The set of users that originally had this package installed.
13697        int[] origUsers;
13698        // The set of users that now have this package installed.
13699        int[] newUsers;
13700        PackageParser.Package pkg;
13701        int returnCode;
13702        String returnMsg;
13703        PackageRemovedInfo removedInfo;
13704        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13705
13706        public void setError(int code, String msg) {
13707            setReturnCode(code);
13708            setReturnMessage(msg);
13709            Slog.w(TAG, msg);
13710        }
13711
13712        public void setError(String msg, PackageParserException e) {
13713            setReturnCode(e.error);
13714            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13715            Slog.w(TAG, msg, e);
13716        }
13717
13718        public void setError(String msg, PackageManagerException e) {
13719            returnCode = e.error;
13720            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13721            Slog.w(TAG, msg, e);
13722        }
13723
13724        public void setReturnCode(int returnCode) {
13725            this.returnCode = returnCode;
13726            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13727            for (int i = 0; i < childCount; i++) {
13728                addedChildPackages.valueAt(i).returnCode = returnCode;
13729            }
13730        }
13731
13732        private void setReturnMessage(String returnMsg) {
13733            this.returnMsg = returnMsg;
13734            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13735            for (int i = 0; i < childCount; i++) {
13736                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13737            }
13738        }
13739
13740        // In some error cases we want to convey more info back to the observer
13741        String origPackage;
13742        String origPermission;
13743    }
13744
13745    /*
13746     * Install a non-existing package.
13747     */
13748    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13749            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13750            PackageInstalledInfo res) {
13751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13752
13753        // Remember this for later, in case we need to rollback this install
13754        String pkgName = pkg.packageName;
13755
13756        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13757
13758        synchronized(mPackages) {
13759            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13760                // A package with the same name is already installed, though
13761                // it has been renamed to an older name.  The package we
13762                // are trying to install should be installed as an update to
13763                // the existing one, but that has not been requested, so bail.
13764                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13765                        + " without first uninstalling package running as "
13766                        + mSettings.mRenamedPackages.get(pkgName));
13767                return;
13768            }
13769            if (mPackages.containsKey(pkgName)) {
13770                // Don't allow installation over an existing package with the same name.
13771                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13772                        + " without first uninstalling.");
13773                return;
13774            }
13775        }
13776
13777        try {
13778            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13779                    System.currentTimeMillis(), user);
13780
13781            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13782
13783            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13784                prepareAppDataAfterInstallLIF(newPackage);
13785
13786            } else {
13787                // Remove package from internal structures, but keep around any
13788                // data that might have already existed
13789                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13790                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13791            }
13792        } catch (PackageManagerException e) {
13793            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13794        }
13795
13796        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13797    }
13798
13799    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13800        // Can't rotate keys during boot or if sharedUser.
13801        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13802                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13803            return false;
13804        }
13805        // app is using upgradeKeySets; make sure all are valid
13806        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13807        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13808        for (int i = 0; i < upgradeKeySets.length; i++) {
13809            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13810                Slog.wtf(TAG, "Package "
13811                         + (oldPs.name != null ? oldPs.name : "<null>")
13812                         + " contains upgrade-key-set reference to unknown key-set: "
13813                         + upgradeKeySets[i]
13814                         + " reverting to signatures check.");
13815                return false;
13816            }
13817        }
13818        return true;
13819    }
13820
13821    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13822        // Upgrade keysets are being used.  Determine if new package has a superset of the
13823        // required keys.
13824        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13825        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13826        for (int i = 0; i < upgradeKeySets.length; i++) {
13827            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13828            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13829                return true;
13830            }
13831        }
13832        return false;
13833    }
13834
13835    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13836            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13837        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13838
13839        final PackageParser.Package oldPackage;
13840        final String pkgName = pkg.packageName;
13841        final int[] allUsers;
13842        final int[] installedUsers;
13843
13844        synchronized(mPackages) {
13845            oldPackage = mPackages.get(pkgName);
13846            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13847
13848            // don't allow upgrade to target a release SDK from a pre-release SDK
13849            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13850                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13851            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13852                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13853            if (oldTargetsPreRelease
13854                    && !newTargetsPreRelease
13855                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13856                Slog.w(TAG, "Can't install package targeting released sdk");
13857                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13858                return;
13859            }
13860
13861            // don't allow an upgrade from full to ephemeral
13862            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13863            if (isEphemeral && !oldIsEphemeral) {
13864                // can't downgrade from full to ephemeral
13865                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13866                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13867                return;
13868            }
13869
13870            // verify signatures are valid
13871            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13872            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13873                if (!checkUpgradeKeySetLP(ps, pkg)) {
13874                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13875                            "New package not signed by keys specified by upgrade-keysets: "
13876                                    + pkgName);
13877                    return;
13878                }
13879            } else {
13880                // default to original signature matching
13881                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13882                        != PackageManager.SIGNATURE_MATCH) {
13883                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13884                            "New package has a different signature: " + pkgName);
13885                    return;
13886                }
13887            }
13888
13889            // Check for shared user id changes
13890            String invalidPackageName =
13891                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13892            if (invalidPackageName != null) {
13893                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13894                        "Package " + invalidPackageName + " tried to change user "
13895                                + oldPackage.mSharedUserId);
13896                return;
13897            }
13898
13899            // In case of rollback, remember per-user/profile install state
13900            allUsers = sUserManager.getUserIds();
13901            installedUsers = ps.queryInstalledUsers(allUsers, true);
13902        }
13903
13904        // Update what is removed
13905        res.removedInfo = new PackageRemovedInfo();
13906        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13907        res.removedInfo.removedPackage = oldPackage.packageName;
13908        res.removedInfo.isUpdate = true;
13909        res.removedInfo.origUsers = installedUsers;
13910        final int childCount = (oldPackage.childPackages != null)
13911                ? oldPackage.childPackages.size() : 0;
13912        for (int i = 0; i < childCount; i++) {
13913            boolean childPackageUpdated = false;
13914            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13915            if (res.addedChildPackages != null) {
13916                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13917                if (childRes != null) {
13918                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13919                    childRes.removedInfo.removedPackage = childPkg.packageName;
13920                    childRes.removedInfo.isUpdate = true;
13921                    childPackageUpdated = true;
13922                }
13923            }
13924            if (!childPackageUpdated) {
13925                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13926                childRemovedRes.removedPackage = childPkg.packageName;
13927                childRemovedRes.isUpdate = false;
13928                childRemovedRes.dataRemoved = true;
13929                synchronized (mPackages) {
13930                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13931                    if (childPs != null) {
13932                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13933                    }
13934                }
13935                if (res.removedInfo.removedChildPackages == null) {
13936                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13937                }
13938                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13939            }
13940        }
13941
13942        boolean sysPkg = (isSystemApp(oldPackage));
13943        if (sysPkg) {
13944            // Set the system/privileged flags as needed
13945            final boolean privileged =
13946                    (oldPackage.applicationInfo.privateFlags
13947                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13948            final int systemPolicyFlags = policyFlags
13949                    | PackageParser.PARSE_IS_SYSTEM
13950                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13951
13952            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13953                    user, allUsers, installerPackageName, res);
13954        } else {
13955            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13956                    user, allUsers, installerPackageName, res);
13957        }
13958    }
13959
13960    public List<String> getPreviousCodePaths(String packageName) {
13961        final PackageSetting ps = mSettings.mPackages.get(packageName);
13962        final List<String> result = new ArrayList<String>();
13963        if (ps != null && ps.oldCodePaths != null) {
13964            result.addAll(ps.oldCodePaths);
13965        }
13966        return result;
13967    }
13968
13969    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13970            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13971            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13972        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13973                + deletedPackage);
13974
13975        String pkgName = deletedPackage.packageName;
13976        boolean deletedPkg = true;
13977        boolean addedPkg = false;
13978        boolean updatedSettings = false;
13979        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13980        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13981                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13982
13983        final long origUpdateTime = (pkg.mExtras != null)
13984                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13985
13986        // First delete the existing package while retaining the data directory
13987        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13988                res.removedInfo, true, pkg)) {
13989            // If the existing package wasn't successfully deleted
13990            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13991            deletedPkg = false;
13992        } else {
13993            // Successfully deleted the old package; proceed with replace.
13994
13995            // If deleted package lived in a container, give users a chance to
13996            // relinquish resources before killing.
13997            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13998                if (DEBUG_INSTALL) {
13999                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14000                }
14001                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14002                final ArrayList<String> pkgList = new ArrayList<String>(1);
14003                pkgList.add(deletedPackage.applicationInfo.packageName);
14004                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14005            }
14006
14007            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14008                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14009            clearAppProfilesLIF(pkg);
14010
14011            try {
14012                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14013                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14014                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14015
14016                // Update the in-memory copy of the previous code paths.
14017                PackageSetting ps = mSettings.mPackages.get(pkgName);
14018                if (!killApp) {
14019                    if (ps.oldCodePaths == null) {
14020                        ps.oldCodePaths = new ArraySet<>();
14021                    }
14022                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14023                    if (deletedPackage.splitCodePaths != null) {
14024                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14025                    }
14026                } else {
14027                    ps.oldCodePaths = null;
14028                }
14029                if (ps.childPackageNames != null) {
14030                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14031                        final String childPkgName = ps.childPackageNames.get(i);
14032                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14033                        childPs.oldCodePaths = ps.oldCodePaths;
14034                    }
14035                }
14036                prepareAppDataAfterInstallLIF(newPackage);
14037                addedPkg = true;
14038            } catch (PackageManagerException e) {
14039                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14040            }
14041        }
14042
14043        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14044            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14045
14046            // Revert all internal state mutations and added folders for the failed install
14047            if (addedPkg) {
14048                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14049                        res.removedInfo, true, null);
14050            }
14051
14052            // Restore the old package
14053            if (deletedPkg) {
14054                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14055                File restoreFile = new File(deletedPackage.codePath);
14056                // Parse old package
14057                boolean oldExternal = isExternal(deletedPackage);
14058                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14059                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14060                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14061                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14062                try {
14063                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14064                            null);
14065                } catch (PackageManagerException e) {
14066                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14067                            + e.getMessage());
14068                    return;
14069                }
14070
14071                synchronized (mPackages) {
14072                    // Ensure the installer package name up to date
14073                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14074
14075                    // Update permissions for restored package
14076                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14077
14078                    mSettings.writeLPr();
14079                }
14080
14081                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14082            }
14083        } else {
14084            synchronized (mPackages) {
14085                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14086                if (ps != null) {
14087                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14088                    if (res.removedInfo.removedChildPackages != null) {
14089                        final int childCount = res.removedInfo.removedChildPackages.size();
14090                        // Iterate in reverse as we may modify the collection
14091                        for (int i = childCount - 1; i >= 0; i--) {
14092                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14093                            if (res.addedChildPackages.containsKey(childPackageName)) {
14094                                res.removedInfo.removedChildPackages.removeAt(i);
14095                            } else {
14096                                PackageRemovedInfo childInfo = res.removedInfo
14097                                        .removedChildPackages.valueAt(i);
14098                                childInfo.removedForAllUsers = mPackages.get(
14099                                        childInfo.removedPackage) == null;
14100                            }
14101                        }
14102                    }
14103                }
14104            }
14105        }
14106    }
14107
14108    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14109            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14110            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14111        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14112                + ", old=" + deletedPackage);
14113
14114        final boolean disabledSystem;
14115
14116        // Remove existing system package
14117        removePackageLI(deletedPackage, true);
14118
14119        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14120        if (!disabledSystem) {
14121            // We didn't need to disable the .apk as a current system package,
14122            // which means we are replacing another update that is already
14123            // installed.  We need to make sure to delete the older one's .apk.
14124            res.removedInfo.args = createInstallArgsForExisting(0,
14125                    deletedPackage.applicationInfo.getCodePath(),
14126                    deletedPackage.applicationInfo.getResourcePath(),
14127                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14128        } else {
14129            res.removedInfo.args = null;
14130        }
14131
14132        // Successfully disabled the old package. Now proceed with re-installation
14133        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14134                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14135        clearAppProfilesLIF(pkg);
14136
14137        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14138        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14139                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14140
14141        PackageParser.Package newPackage = null;
14142        try {
14143            // Add the package to the internal data structures
14144            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14145
14146            // Set the update and install times
14147            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14148            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14149                    System.currentTimeMillis());
14150
14151            // Update the package dynamic state if succeeded
14152            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14153                // Now that the install succeeded make sure we remove data
14154                // directories for any child package the update removed.
14155                final int deletedChildCount = (deletedPackage.childPackages != null)
14156                        ? deletedPackage.childPackages.size() : 0;
14157                final int newChildCount = (newPackage.childPackages != null)
14158                        ? newPackage.childPackages.size() : 0;
14159                for (int i = 0; i < deletedChildCount; i++) {
14160                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14161                    boolean childPackageDeleted = true;
14162                    for (int j = 0; j < newChildCount; j++) {
14163                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14164                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14165                            childPackageDeleted = false;
14166                            break;
14167                        }
14168                    }
14169                    if (childPackageDeleted) {
14170                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14171                                deletedChildPkg.packageName);
14172                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14173                            PackageRemovedInfo removedChildRes = res.removedInfo
14174                                    .removedChildPackages.get(deletedChildPkg.packageName);
14175                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14176                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14177                        }
14178                    }
14179                }
14180
14181                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14182                prepareAppDataAfterInstallLIF(newPackage);
14183            }
14184        } catch (PackageManagerException e) {
14185            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14186            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14187        }
14188
14189        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14190            // Re installation failed. Restore old information
14191            // Remove new pkg information
14192            if (newPackage != null) {
14193                removeInstalledPackageLI(newPackage, true);
14194            }
14195            // Add back the old system package
14196            try {
14197                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14198            } catch (PackageManagerException e) {
14199                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14200            }
14201
14202            synchronized (mPackages) {
14203                if (disabledSystem) {
14204                    enableSystemPackageLPw(deletedPackage);
14205                }
14206
14207                // Ensure the installer package name up to date
14208                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14209
14210                // Update permissions for restored package
14211                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14212
14213                mSettings.writeLPr();
14214            }
14215
14216            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14217                    + " after failed upgrade");
14218        }
14219    }
14220
14221    /**
14222     * Checks whether the parent or any of the child packages have a change shared
14223     * user. For a package to be a valid update the shred users of the parent and
14224     * the children should match. We may later support changing child shared users.
14225     * @param oldPkg The updated package.
14226     * @param newPkg The update package.
14227     * @return The shared user that change between the versions.
14228     */
14229    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14230            PackageParser.Package newPkg) {
14231        // Check parent shared user
14232        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14233            return newPkg.packageName;
14234        }
14235        // Check child shared users
14236        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14237        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14238        for (int i = 0; i < newChildCount; i++) {
14239            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14240            // If this child was present, did it have the same shared user?
14241            for (int j = 0; j < oldChildCount; j++) {
14242                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14243                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14244                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14245                    return newChildPkg.packageName;
14246                }
14247            }
14248        }
14249        return null;
14250    }
14251
14252    private void removeNativeBinariesLI(PackageSetting ps) {
14253        // Remove the lib path for the parent package
14254        if (ps != null) {
14255            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14256            // Remove the lib path for the child packages
14257            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14258            for (int i = 0; i < childCount; i++) {
14259                PackageSetting childPs = null;
14260                synchronized (mPackages) {
14261                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14262                }
14263                if (childPs != null) {
14264                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14265                            .legacyNativeLibraryPathString);
14266                }
14267            }
14268        }
14269    }
14270
14271    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14272        // Enable the parent package
14273        mSettings.enableSystemPackageLPw(pkg.packageName);
14274        // Enable the child packages
14275        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14276        for (int i = 0; i < childCount; i++) {
14277            PackageParser.Package childPkg = pkg.childPackages.get(i);
14278            mSettings.enableSystemPackageLPw(childPkg.packageName);
14279        }
14280    }
14281
14282    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14283            PackageParser.Package newPkg) {
14284        // Disable the parent package (parent always replaced)
14285        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14286        // Disable the child packages
14287        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14288        for (int i = 0; i < childCount; i++) {
14289            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14290            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14291            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14292        }
14293        return disabled;
14294    }
14295
14296    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14297            String installerPackageName) {
14298        // Enable the parent package
14299        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14300        // Enable the child packages
14301        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14302        for (int i = 0; i < childCount; i++) {
14303            PackageParser.Package childPkg = pkg.childPackages.get(i);
14304            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14305        }
14306    }
14307
14308    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14309        // Collect all used permissions in the UID
14310        ArraySet<String> usedPermissions = new ArraySet<>();
14311        final int packageCount = su.packages.size();
14312        for (int i = 0; i < packageCount; i++) {
14313            PackageSetting ps = su.packages.valueAt(i);
14314            if (ps.pkg == null) {
14315                continue;
14316            }
14317            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14318            for (int j = 0; j < requestedPermCount; j++) {
14319                String permission = ps.pkg.requestedPermissions.get(j);
14320                BasePermission bp = mSettings.mPermissions.get(permission);
14321                if (bp != null) {
14322                    usedPermissions.add(permission);
14323                }
14324            }
14325        }
14326
14327        PermissionsState permissionsState = su.getPermissionsState();
14328        // Prune install permissions
14329        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14330        final int installPermCount = installPermStates.size();
14331        for (int i = installPermCount - 1; i >= 0;  i--) {
14332            PermissionState permissionState = installPermStates.get(i);
14333            if (!usedPermissions.contains(permissionState.getName())) {
14334                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14335                if (bp != null) {
14336                    permissionsState.revokeInstallPermission(bp);
14337                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14338                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14339                }
14340            }
14341        }
14342
14343        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14344
14345        // Prune runtime permissions
14346        for (int userId : allUserIds) {
14347            List<PermissionState> runtimePermStates = permissionsState
14348                    .getRuntimePermissionStates(userId);
14349            final int runtimePermCount = runtimePermStates.size();
14350            for (int i = runtimePermCount - 1; i >= 0; i--) {
14351                PermissionState permissionState = runtimePermStates.get(i);
14352                if (!usedPermissions.contains(permissionState.getName())) {
14353                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14354                    if (bp != null) {
14355                        permissionsState.revokeRuntimePermission(bp, userId);
14356                        permissionsState.updatePermissionFlags(bp, userId,
14357                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14358                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14359                                runtimePermissionChangedUserIds, userId);
14360                    }
14361                }
14362            }
14363        }
14364
14365        return runtimePermissionChangedUserIds;
14366    }
14367
14368    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14369            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14370        // Update the parent package setting
14371        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14372                res, user);
14373        // Update the child packages setting
14374        final int childCount = (newPackage.childPackages != null)
14375                ? newPackage.childPackages.size() : 0;
14376        for (int i = 0; i < childCount; i++) {
14377            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14378            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14379            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14380                    childRes.origUsers, childRes, user);
14381        }
14382    }
14383
14384    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14385            String installerPackageName, int[] allUsers, int[] installedForUsers,
14386            PackageInstalledInfo res, UserHandle user) {
14387        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14388
14389        String pkgName = newPackage.packageName;
14390        synchronized (mPackages) {
14391            //write settings. the installStatus will be incomplete at this stage.
14392            //note that the new package setting would have already been
14393            //added to mPackages. It hasn't been persisted yet.
14394            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14395            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14396            mSettings.writeLPr();
14397            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14398        }
14399
14400        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14401        synchronized (mPackages) {
14402            updatePermissionsLPw(newPackage.packageName, newPackage,
14403                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14404                            ? UPDATE_PERMISSIONS_ALL : 0));
14405            // For system-bundled packages, we assume that installing an upgraded version
14406            // of the package implies that the user actually wants to run that new code,
14407            // so we enable the package.
14408            PackageSetting ps = mSettings.mPackages.get(pkgName);
14409            final int userId = user.getIdentifier();
14410            if (ps != null) {
14411                if (isSystemApp(newPackage)) {
14412                    if (DEBUG_INSTALL) {
14413                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14414                    }
14415                    // Enable system package for requested users
14416                    if (res.origUsers != null) {
14417                        for (int origUserId : res.origUsers) {
14418                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14419                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14420                                        origUserId, installerPackageName);
14421                            }
14422                        }
14423                    }
14424                    // Also convey the prior install/uninstall state
14425                    if (allUsers != null && installedForUsers != null) {
14426                        for (int currentUserId : allUsers) {
14427                            final boolean installed = ArrayUtils.contains(
14428                                    installedForUsers, currentUserId);
14429                            if (DEBUG_INSTALL) {
14430                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14431                            }
14432                            ps.setInstalled(installed, currentUserId);
14433                        }
14434                        // these install state changes will be persisted in the
14435                        // upcoming call to mSettings.writeLPr().
14436                    }
14437                }
14438                // It's implied that when a user requests installation, they want the app to be
14439                // installed and enabled.
14440                if (userId != UserHandle.USER_ALL) {
14441                    ps.setInstalled(true, userId);
14442                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14443                }
14444            }
14445            res.name = pkgName;
14446            res.uid = newPackage.applicationInfo.uid;
14447            res.pkg = newPackage;
14448            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14449            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14450            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14451            //to update install status
14452            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14453            mSettings.writeLPr();
14454            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14455        }
14456
14457        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14458    }
14459
14460    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14461        try {
14462            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14463            installPackageLI(args, res);
14464        } finally {
14465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14466        }
14467    }
14468
14469    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14470        final int installFlags = args.installFlags;
14471        final String installerPackageName = args.installerPackageName;
14472        final String volumeUuid = args.volumeUuid;
14473        final File tmpPackageFile = new File(args.getCodePath());
14474        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14475        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14476                || (args.volumeUuid != null));
14477        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14478        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14479        boolean replace = false;
14480        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14481        if (args.move != null) {
14482            // moving a complete application; perform an initial scan on the new install location
14483            scanFlags |= SCAN_INITIAL;
14484        }
14485        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14486            scanFlags |= SCAN_DONT_KILL_APP;
14487        }
14488
14489        // Result object to be returned
14490        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14491
14492        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14493
14494        // Sanity check
14495        if (ephemeral && (forwardLocked || onExternal)) {
14496            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14497                    + " external=" + onExternal);
14498            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14499            return;
14500        }
14501
14502        // Retrieve PackageSettings and parse package
14503        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14504                | PackageParser.PARSE_ENFORCE_CODE
14505                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14506                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14507                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14508                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14509        PackageParser pp = new PackageParser();
14510        pp.setSeparateProcesses(mSeparateProcesses);
14511        pp.setDisplayMetrics(mMetrics);
14512
14513        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14514        final PackageParser.Package pkg;
14515        try {
14516            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14517        } catch (PackageParserException e) {
14518            res.setError("Failed parse during installPackageLI", e);
14519            return;
14520        } finally {
14521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14522        }
14523
14524        // If we are installing a clustered package add results for the children
14525        if (pkg.childPackages != null) {
14526            synchronized (mPackages) {
14527                final int childCount = pkg.childPackages.size();
14528                for (int i = 0; i < childCount; i++) {
14529                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14530                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14531                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14532                    childRes.pkg = childPkg;
14533                    childRes.name = childPkg.packageName;
14534                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14535                    if (childPs != null) {
14536                        childRes.origUsers = childPs.queryInstalledUsers(
14537                                sUserManager.getUserIds(), true);
14538                    }
14539                    if ((mPackages.containsKey(childPkg.packageName))) {
14540                        childRes.removedInfo = new PackageRemovedInfo();
14541                        childRes.removedInfo.removedPackage = childPkg.packageName;
14542                    }
14543                    if (res.addedChildPackages == null) {
14544                        res.addedChildPackages = new ArrayMap<>();
14545                    }
14546                    res.addedChildPackages.put(childPkg.packageName, childRes);
14547                }
14548            }
14549        }
14550
14551        // If package doesn't declare API override, mark that we have an install
14552        // time CPU ABI override.
14553        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14554            pkg.cpuAbiOverride = args.abiOverride;
14555        }
14556
14557        String pkgName = res.name = pkg.packageName;
14558        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14559            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14560                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14561                return;
14562            }
14563        }
14564
14565        try {
14566            // either use what we've been given or parse directly from the APK
14567            if (args.certificates != null) {
14568                try {
14569                    PackageParser.populateCertificates(pkg, args.certificates);
14570                } catch (PackageParserException e) {
14571                    // there was something wrong with the certificates we were given;
14572                    // try to pull them from the APK
14573                    PackageParser.collectCertificates(pkg, parseFlags);
14574                }
14575            } else {
14576                PackageParser.collectCertificates(pkg, parseFlags);
14577            }
14578        } catch (PackageParserException e) {
14579            res.setError("Failed collect during installPackageLI", e);
14580            return;
14581        }
14582
14583        // Get rid of all references to package scan path via parser.
14584        pp = null;
14585        String oldCodePath = null;
14586        boolean systemApp = false;
14587        synchronized (mPackages) {
14588            // Check if installing already existing package
14589            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14590                String oldName = mSettings.mRenamedPackages.get(pkgName);
14591                if (pkg.mOriginalPackages != null
14592                        && pkg.mOriginalPackages.contains(oldName)
14593                        && mPackages.containsKey(oldName)) {
14594                    // This package is derived from an original package,
14595                    // and this device has been updating from that original
14596                    // name.  We must continue using the original name, so
14597                    // rename the new package here.
14598                    pkg.setPackageName(oldName);
14599                    pkgName = pkg.packageName;
14600                    replace = true;
14601                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14602                            + oldName + " pkgName=" + pkgName);
14603                } else if (mPackages.containsKey(pkgName)) {
14604                    // This package, under its official name, already exists
14605                    // on the device; we should replace it.
14606                    replace = true;
14607                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14608                }
14609
14610                // Child packages are installed through the parent package
14611                if (pkg.parentPackage != null) {
14612                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14613                            "Package " + pkg.packageName + " is child of package "
14614                                    + pkg.parentPackage.parentPackage + ". Child packages "
14615                                    + "can be updated only through the parent package.");
14616                    return;
14617                }
14618
14619                if (replace) {
14620                    // Prevent apps opting out from runtime permissions
14621                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14622                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14623                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14624                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14625                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14626                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14627                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14628                                        + " doesn't support runtime permissions but the old"
14629                                        + " target SDK " + oldTargetSdk + " does.");
14630                        return;
14631                    }
14632
14633                    // Prevent installing of child packages
14634                    if (oldPackage.parentPackage != null) {
14635                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14636                                "Package " + pkg.packageName + " is child of package "
14637                                        + oldPackage.parentPackage + ". Child packages "
14638                                        + "can be updated only through the parent package.");
14639                        return;
14640                    }
14641                }
14642            }
14643
14644            PackageSetting ps = mSettings.mPackages.get(pkgName);
14645            if (ps != null) {
14646                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14647
14648                // Quick sanity check that we're signed correctly if updating;
14649                // we'll check this again later when scanning, but we want to
14650                // bail early here before tripping over redefined permissions.
14651                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14652                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14653                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14654                                + pkg.packageName + " upgrade keys do not match the "
14655                                + "previously installed version");
14656                        return;
14657                    }
14658                } else {
14659                    try {
14660                        verifySignaturesLP(ps, pkg);
14661                    } catch (PackageManagerException e) {
14662                        res.setError(e.error, e.getMessage());
14663                        return;
14664                    }
14665                }
14666
14667                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14668                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14669                    systemApp = (ps.pkg.applicationInfo.flags &
14670                            ApplicationInfo.FLAG_SYSTEM) != 0;
14671                }
14672                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14673            }
14674
14675            // Check whether the newly-scanned package wants to define an already-defined perm
14676            int N = pkg.permissions.size();
14677            for (int i = N-1; i >= 0; i--) {
14678                PackageParser.Permission perm = pkg.permissions.get(i);
14679                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14680                if (bp != null) {
14681                    // If the defining package is signed with our cert, it's okay.  This
14682                    // also includes the "updating the same package" case, of course.
14683                    // "updating same package" could also involve key-rotation.
14684                    final boolean sigsOk;
14685                    if (bp.sourcePackage.equals(pkg.packageName)
14686                            && (bp.packageSetting instanceof PackageSetting)
14687                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14688                                    scanFlags))) {
14689                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14690                    } else {
14691                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14692                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14693                    }
14694                    if (!sigsOk) {
14695                        // If the owning package is the system itself, we log but allow
14696                        // install to proceed; we fail the install on all other permission
14697                        // redefinitions.
14698                        if (!bp.sourcePackage.equals("android")) {
14699                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14700                                    + pkg.packageName + " attempting to redeclare permission "
14701                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14702                            res.origPermission = perm.info.name;
14703                            res.origPackage = bp.sourcePackage;
14704                            return;
14705                        } else {
14706                            Slog.w(TAG, "Package " + pkg.packageName
14707                                    + " attempting to redeclare system permission "
14708                                    + perm.info.name + "; ignoring new declaration");
14709                            pkg.permissions.remove(i);
14710                        }
14711                    }
14712                }
14713            }
14714        }
14715
14716        if (systemApp) {
14717            if (onExternal) {
14718                // Abort update; system app can't be replaced with app on sdcard
14719                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14720                        "Cannot install updates to system apps on sdcard");
14721                return;
14722            } else if (ephemeral) {
14723                // Abort update; system app can't be replaced with an ephemeral app
14724                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14725                        "Cannot update a system app with an ephemeral app");
14726                return;
14727            }
14728        }
14729
14730        if (args.move != null) {
14731            // We did an in-place move, so dex is ready to roll
14732            scanFlags |= SCAN_NO_DEX;
14733            scanFlags |= SCAN_MOVE;
14734
14735            synchronized (mPackages) {
14736                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14737                if (ps == null) {
14738                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14739                            "Missing settings for moved package " + pkgName);
14740                }
14741
14742                // We moved the entire application as-is, so bring over the
14743                // previously derived ABI information.
14744                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14745                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14746            }
14747
14748        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14749            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14750            scanFlags |= SCAN_NO_DEX;
14751
14752            try {
14753                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14754                    args.abiOverride : pkg.cpuAbiOverride);
14755                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14756                        true /* extract libs */);
14757            } catch (PackageManagerException pme) {
14758                Slog.e(TAG, "Error deriving application ABI", pme);
14759                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14760                return;
14761            }
14762
14763            // Shared libraries for the package need to be updated.
14764            synchronized (mPackages) {
14765                try {
14766                    updateSharedLibrariesLPw(pkg, null);
14767                } catch (PackageManagerException e) {
14768                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14769                }
14770            }
14771            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14772            // Do not run PackageDexOptimizer through the local performDexOpt
14773            // method because `pkg` is not in `mPackages` yet.
14774            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14775                    null /* instructionSets */, false /* checkProfiles */,
14776                    getCompilerFilterForReason(REASON_INSTALL));
14777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14778            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14779                String msg = "Extracting package failed for " + pkgName;
14780                res.setError(INSTALL_FAILED_DEXOPT, msg);
14781                return;
14782            }
14783
14784            // Notify BackgroundDexOptService that the package has been changed.
14785            // If this is an update of a package which used to fail to compile,
14786            // BDOS will remove it from its blacklist.
14787            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14788        }
14789
14790        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14791            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14792            return;
14793        }
14794
14795        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14796
14797        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14798                "installPackageLI")) {
14799            if (replace) {
14800                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14801                        installerPackageName, res);
14802            } else {
14803                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14804                        args.user, installerPackageName, volumeUuid, res);
14805            }
14806        }
14807        synchronized (mPackages) {
14808            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14809            if (ps != null) {
14810                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14811            }
14812
14813            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14814            for (int i = 0; i < childCount; i++) {
14815                PackageParser.Package childPkg = pkg.childPackages.get(i);
14816                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14817                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14818                if (childPs != null) {
14819                    childRes.newUsers = childPs.queryInstalledUsers(
14820                            sUserManager.getUserIds(), true);
14821                }
14822            }
14823        }
14824    }
14825
14826    private void startIntentFilterVerifications(int userId, boolean replacing,
14827            PackageParser.Package pkg) {
14828        if (mIntentFilterVerifierComponent == null) {
14829            Slog.w(TAG, "No IntentFilter verification will not be done as "
14830                    + "there is no IntentFilterVerifier available!");
14831            return;
14832        }
14833
14834        final int verifierUid = getPackageUid(
14835                mIntentFilterVerifierComponent.getPackageName(),
14836                MATCH_DEBUG_TRIAGED_MISSING,
14837                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14838
14839        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14840        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14841        mHandler.sendMessage(msg);
14842
14843        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14844        for (int i = 0; i < childCount; i++) {
14845            PackageParser.Package childPkg = pkg.childPackages.get(i);
14846            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14847            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14848            mHandler.sendMessage(msg);
14849        }
14850    }
14851
14852    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14853            PackageParser.Package pkg) {
14854        int size = pkg.activities.size();
14855        if (size == 0) {
14856            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14857                    "No activity, so no need to verify any IntentFilter!");
14858            return;
14859        }
14860
14861        final boolean hasDomainURLs = hasDomainURLs(pkg);
14862        if (!hasDomainURLs) {
14863            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14864                    "No domain URLs, so no need to verify any IntentFilter!");
14865            return;
14866        }
14867
14868        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14869                + " if any IntentFilter from the " + size
14870                + " Activities needs verification ...");
14871
14872        int count = 0;
14873        final String packageName = pkg.packageName;
14874
14875        synchronized (mPackages) {
14876            // If this is a new install and we see that we've already run verification for this
14877            // package, we have nothing to do: it means the state was restored from backup.
14878            if (!replacing) {
14879                IntentFilterVerificationInfo ivi =
14880                        mSettings.getIntentFilterVerificationLPr(packageName);
14881                if (ivi != null) {
14882                    if (DEBUG_DOMAIN_VERIFICATION) {
14883                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14884                                + ivi.getStatusString());
14885                    }
14886                    return;
14887                }
14888            }
14889
14890            // If any filters need to be verified, then all need to be.
14891            boolean needToVerify = false;
14892            for (PackageParser.Activity a : pkg.activities) {
14893                for (ActivityIntentInfo filter : a.intents) {
14894                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14895                        if (DEBUG_DOMAIN_VERIFICATION) {
14896                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14897                        }
14898                        needToVerify = true;
14899                        break;
14900                    }
14901                }
14902            }
14903
14904            if (needToVerify) {
14905                final int verificationId = mIntentFilterVerificationToken++;
14906                for (PackageParser.Activity a : pkg.activities) {
14907                    for (ActivityIntentInfo filter : a.intents) {
14908                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14909                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14910                                    "Verification needed for IntentFilter:" + filter.toString());
14911                            mIntentFilterVerifier.addOneIntentFilterVerification(
14912                                    verifierUid, userId, verificationId, filter, packageName);
14913                            count++;
14914                        }
14915                    }
14916                }
14917            }
14918        }
14919
14920        if (count > 0) {
14921            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14922                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14923                    +  " for userId:" + userId);
14924            mIntentFilterVerifier.startVerifications(userId);
14925        } else {
14926            if (DEBUG_DOMAIN_VERIFICATION) {
14927                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14928            }
14929        }
14930    }
14931
14932    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14933        final ComponentName cn  = filter.activity.getComponentName();
14934        final String packageName = cn.getPackageName();
14935
14936        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14937                packageName);
14938        if (ivi == null) {
14939            return true;
14940        }
14941        int status = ivi.getStatus();
14942        switch (status) {
14943            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14944            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14945                return true;
14946
14947            default:
14948                // Nothing to do
14949                return false;
14950        }
14951    }
14952
14953    private static boolean isMultiArch(ApplicationInfo info) {
14954        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14955    }
14956
14957    private static boolean isExternal(PackageParser.Package pkg) {
14958        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14959    }
14960
14961    private static boolean isExternal(PackageSetting ps) {
14962        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14963    }
14964
14965    private static boolean isEphemeral(PackageParser.Package pkg) {
14966        return pkg.applicationInfo.isEphemeralApp();
14967    }
14968
14969    private static boolean isEphemeral(PackageSetting ps) {
14970        return ps.pkg != null && isEphemeral(ps.pkg);
14971    }
14972
14973    private static boolean isSystemApp(PackageParser.Package pkg) {
14974        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14975    }
14976
14977    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14978        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14979    }
14980
14981    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14982        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14983    }
14984
14985    private static boolean isSystemApp(PackageSetting ps) {
14986        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14987    }
14988
14989    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14990        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14991    }
14992
14993    private int packageFlagsToInstallFlags(PackageSetting ps) {
14994        int installFlags = 0;
14995        if (isEphemeral(ps)) {
14996            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14997        }
14998        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14999            // This existing package was an external ASEC install when we have
15000            // the external flag without a UUID
15001            installFlags |= PackageManager.INSTALL_EXTERNAL;
15002        }
15003        if (ps.isForwardLocked()) {
15004            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15005        }
15006        return installFlags;
15007    }
15008
15009    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15010        if (isExternal(pkg)) {
15011            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15012                return StorageManager.UUID_PRIMARY_PHYSICAL;
15013            } else {
15014                return pkg.volumeUuid;
15015            }
15016        } else {
15017            return StorageManager.UUID_PRIVATE_INTERNAL;
15018        }
15019    }
15020
15021    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15022        if (isExternal(pkg)) {
15023            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15024                return mSettings.getExternalVersion();
15025            } else {
15026                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15027            }
15028        } else {
15029            return mSettings.getInternalVersion();
15030        }
15031    }
15032
15033    private void deleteTempPackageFiles() {
15034        final FilenameFilter filter = new FilenameFilter() {
15035            public boolean accept(File dir, String name) {
15036                return name.startsWith("vmdl") && name.endsWith(".tmp");
15037            }
15038        };
15039        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15040            file.delete();
15041        }
15042    }
15043
15044    @Override
15045    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15046            int flags) {
15047        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15048                flags);
15049    }
15050
15051    @Override
15052    public void deletePackage(final String packageName,
15053            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15054        mContext.enforceCallingOrSelfPermission(
15055                android.Manifest.permission.DELETE_PACKAGES, null);
15056        Preconditions.checkNotNull(packageName);
15057        Preconditions.checkNotNull(observer);
15058        final int uid = Binder.getCallingUid();
15059        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15060        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15061        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15062            mContext.enforceCallingOrSelfPermission(
15063                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15064                    "deletePackage for user " + userId);
15065        }
15066
15067        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15068            try {
15069                observer.onPackageDeleted(packageName,
15070                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15071            } catch (RemoteException re) {
15072            }
15073            return;
15074        }
15075
15076        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15077            try {
15078                observer.onPackageDeleted(packageName,
15079                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15080            } catch (RemoteException re) {
15081            }
15082            return;
15083        }
15084
15085        if (DEBUG_REMOVE) {
15086            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15087                    + " deleteAllUsers: " + deleteAllUsers );
15088        }
15089        // Queue up an async operation since the package deletion may take a little while.
15090        mHandler.post(new Runnable() {
15091            public void run() {
15092                mHandler.removeCallbacks(this);
15093                int returnCode;
15094                if (!deleteAllUsers) {
15095                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15096                } else {
15097                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15098                    // If nobody is blocking uninstall, proceed with delete for all users
15099                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15100                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15101                    } else {
15102                        // Otherwise uninstall individually for users with blockUninstalls=false
15103                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15104                        for (int userId : users) {
15105                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15106                                returnCode = deletePackageX(packageName, userId, userFlags);
15107                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15108                                    Slog.w(TAG, "Package delete failed for user " + userId
15109                                            + ", returnCode " + returnCode);
15110                                }
15111                            }
15112                        }
15113                        // The app has only been marked uninstalled for certain users.
15114                        // We still need to report that delete was blocked
15115                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15116                    }
15117                }
15118                try {
15119                    observer.onPackageDeleted(packageName, returnCode, null);
15120                } catch (RemoteException e) {
15121                    Log.i(TAG, "Observer no longer exists.");
15122                } //end catch
15123            } //end run
15124        });
15125    }
15126
15127    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15128        int[] result = EMPTY_INT_ARRAY;
15129        for (int userId : userIds) {
15130            if (getBlockUninstallForUser(packageName, userId)) {
15131                result = ArrayUtils.appendInt(result, userId);
15132            }
15133        }
15134        return result;
15135    }
15136
15137    @Override
15138    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15139        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15140    }
15141
15142    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15143        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15144                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15145        try {
15146            if (dpm != null) {
15147                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15148                        /* callingUserOnly =*/ false);
15149                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15150                        : deviceOwnerComponentName.getPackageName();
15151                // Does the package contains the device owner?
15152                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15153                // this check is probably not needed, since DO should be registered as a device
15154                // admin on some user too. (Original bug for this: b/17657954)
15155                if (packageName.equals(deviceOwnerPackageName)) {
15156                    return true;
15157                }
15158                // Does it contain a device admin for any user?
15159                int[] users;
15160                if (userId == UserHandle.USER_ALL) {
15161                    users = sUserManager.getUserIds();
15162                } else {
15163                    users = new int[]{userId};
15164                }
15165                for (int i = 0; i < users.length; ++i) {
15166                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15167                        return true;
15168                    }
15169                }
15170            }
15171        } catch (RemoteException e) {
15172        }
15173        return false;
15174    }
15175
15176    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15177        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15178    }
15179
15180    /**
15181     *  This method is an internal method that could be get invoked either
15182     *  to delete an installed package or to clean up a failed installation.
15183     *  After deleting an installed package, a broadcast is sent to notify any
15184     *  listeners that the package has been removed. For cleaning up a failed
15185     *  installation, the broadcast is not necessary since the package's
15186     *  installation wouldn't have sent the initial broadcast either
15187     *  The key steps in deleting a package are
15188     *  deleting the package information in internal structures like mPackages,
15189     *  deleting the packages base directories through installd
15190     *  updating mSettings to reflect current status
15191     *  persisting settings for later use
15192     *  sending a broadcast if necessary
15193     */
15194    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15195        final PackageRemovedInfo info = new PackageRemovedInfo();
15196        final boolean res;
15197
15198        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15199                ? UserHandle.ALL : new UserHandle(userId);
15200
15201        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15202            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15203            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15204        }
15205
15206        PackageSetting uninstalledPs = null;
15207
15208        // for the uninstall-updates case and restricted profiles, remember the per-
15209        // user handle installed state
15210        int[] allUsers;
15211        synchronized (mPackages) {
15212            uninstalledPs = mSettings.mPackages.get(packageName);
15213            if (uninstalledPs == null) {
15214                Slog.w(TAG, "Not removing non-existent package " + packageName);
15215                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15216            }
15217            allUsers = sUserManager.getUserIds();
15218            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15219        }
15220
15221        synchronized (mInstallLock) {
15222            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15223            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15224                    "deletePackageX")) {
15225                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15226                        deleteFlags | REMOVE_CHATTY, info, true, null);
15227            }
15228            synchronized (mPackages) {
15229                if (res) {
15230                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15231                }
15232            }
15233        }
15234
15235        if (res) {
15236            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15237            info.sendPackageRemovedBroadcasts(killApp);
15238            info.sendSystemPackageUpdatedBroadcasts();
15239            info.sendSystemPackageAppearedBroadcasts();
15240        }
15241        // Force a gc here.
15242        Runtime.getRuntime().gc();
15243        // Delete the resources here after sending the broadcast to let
15244        // other processes clean up before deleting resources.
15245        if (info.args != null) {
15246            synchronized (mInstallLock) {
15247                info.args.doPostDeleteLI(true);
15248            }
15249        }
15250
15251        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15252    }
15253
15254    class PackageRemovedInfo {
15255        String removedPackage;
15256        int uid = -1;
15257        int removedAppId = -1;
15258        int[] origUsers;
15259        int[] removedUsers = null;
15260        boolean isRemovedPackageSystemUpdate = false;
15261        boolean isUpdate;
15262        boolean dataRemoved;
15263        boolean removedForAllUsers;
15264        // Clean up resources deleted packages.
15265        InstallArgs args = null;
15266        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15267        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15268
15269        void sendPackageRemovedBroadcasts(boolean killApp) {
15270            sendPackageRemovedBroadcastInternal(killApp);
15271            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15272            for (int i = 0; i < childCount; i++) {
15273                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15274                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15275            }
15276        }
15277
15278        void sendSystemPackageUpdatedBroadcasts() {
15279            if (isRemovedPackageSystemUpdate) {
15280                sendSystemPackageUpdatedBroadcastsInternal();
15281                final int childCount = (removedChildPackages != null)
15282                        ? removedChildPackages.size() : 0;
15283                for (int i = 0; i < childCount; i++) {
15284                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15285                    if (childInfo.isRemovedPackageSystemUpdate) {
15286                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15287                    }
15288                }
15289            }
15290        }
15291
15292        void sendSystemPackageAppearedBroadcasts() {
15293            final int packageCount = (appearedChildPackages != null)
15294                    ? appearedChildPackages.size() : 0;
15295            for (int i = 0; i < packageCount; i++) {
15296                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15297                for (int userId : installedInfo.newUsers) {
15298                    sendPackageAddedForUser(installedInfo.name, true,
15299                            UserHandle.getAppId(installedInfo.uid), userId);
15300                }
15301            }
15302        }
15303
15304        private void sendSystemPackageUpdatedBroadcastsInternal() {
15305            Bundle extras = new Bundle(2);
15306            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15307            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15308            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15309                    extras, 0, null, null, null);
15310            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15311                    extras, 0, null, null, null);
15312            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15313                    null, 0, removedPackage, null, null);
15314        }
15315
15316        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15317            Bundle extras = new Bundle(2);
15318            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15319            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15320            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15321            if (isUpdate || isRemovedPackageSystemUpdate) {
15322                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15323            }
15324            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15325            if (removedPackage != null) {
15326                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15327                        extras, 0, null, null, removedUsers);
15328                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15329                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15330                            removedPackage, extras, 0, null, null, removedUsers);
15331                }
15332            }
15333            if (removedAppId >= 0) {
15334                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15335                        removedUsers);
15336            }
15337        }
15338    }
15339
15340    /*
15341     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15342     * flag is not set, the data directory is removed as well.
15343     * make sure this flag is set for partially installed apps. If not its meaningless to
15344     * delete a partially installed application.
15345     */
15346    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15347            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15348        String packageName = ps.name;
15349        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15350        // Retrieve object to delete permissions for shared user later on
15351        final PackageParser.Package deletedPkg;
15352        final PackageSetting deletedPs;
15353        // reader
15354        synchronized (mPackages) {
15355            deletedPkg = mPackages.get(packageName);
15356            deletedPs = mSettings.mPackages.get(packageName);
15357            if (outInfo != null) {
15358                outInfo.removedPackage = packageName;
15359                outInfo.removedUsers = deletedPs != null
15360                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15361                        : null;
15362            }
15363        }
15364
15365        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15366
15367        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15368            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15369                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15370            destroyAppProfilesLIF(deletedPkg);
15371            if (outInfo != null) {
15372                outInfo.dataRemoved = true;
15373            }
15374            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15375        }
15376
15377        // writer
15378        synchronized (mPackages) {
15379            if (deletedPs != null) {
15380                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15381                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15382                    clearDefaultBrowserIfNeeded(packageName);
15383                    if (outInfo != null) {
15384                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15385                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15386                    }
15387                    updatePermissionsLPw(deletedPs.name, null, 0);
15388                    if (deletedPs.sharedUser != null) {
15389                        // Remove permissions associated with package. Since runtime
15390                        // permissions are per user we have to kill the removed package
15391                        // or packages running under the shared user of the removed
15392                        // package if revoking the permissions requested only by the removed
15393                        // package is successful and this causes a change in gids.
15394                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15395                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15396                                    userId);
15397                            if (userIdToKill == UserHandle.USER_ALL
15398                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15399                                // If gids changed for this user, kill all affected packages.
15400                                mHandler.post(new Runnable() {
15401                                    @Override
15402                                    public void run() {
15403                                        // This has to happen with no lock held.
15404                                        killApplication(deletedPs.name, deletedPs.appId,
15405                                                KILL_APP_REASON_GIDS_CHANGED);
15406                                    }
15407                                });
15408                                break;
15409                            }
15410                        }
15411                    }
15412                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15413                }
15414                // make sure to preserve per-user disabled state if this removal was just
15415                // a downgrade of a system app to the factory package
15416                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15417                    if (DEBUG_REMOVE) {
15418                        Slog.d(TAG, "Propagating install state across downgrade");
15419                    }
15420                    for (int userId : allUserHandles) {
15421                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15422                        if (DEBUG_REMOVE) {
15423                            Slog.d(TAG, "    user " + userId + " => " + installed);
15424                        }
15425                        ps.setInstalled(installed, userId);
15426                    }
15427                }
15428            }
15429            // can downgrade to reader
15430            if (writeSettings) {
15431                // Save settings now
15432                mSettings.writeLPr();
15433            }
15434        }
15435        if (outInfo != null) {
15436            // A user ID was deleted here. Go through all users and remove it
15437            // from KeyStore.
15438            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15439        }
15440    }
15441
15442    static boolean locationIsPrivileged(File path) {
15443        try {
15444            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15445                    .getCanonicalPath();
15446            return path.getCanonicalPath().startsWith(privilegedAppDir);
15447        } catch (IOException e) {
15448            Slog.e(TAG, "Unable to access code path " + path);
15449        }
15450        return false;
15451    }
15452
15453    /*
15454     * Tries to delete system package.
15455     */
15456    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15457            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15458            boolean writeSettings) {
15459        if (deletedPs.parentPackageName != null) {
15460            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15461            return false;
15462        }
15463
15464        final boolean applyUserRestrictions
15465                = (allUserHandles != null) && (outInfo.origUsers != null);
15466        final PackageSetting disabledPs;
15467        // Confirm if the system package has been updated
15468        // An updated system app can be deleted. This will also have to restore
15469        // the system pkg from system partition
15470        // reader
15471        synchronized (mPackages) {
15472            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15473        }
15474
15475        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15476                + " disabledPs=" + disabledPs);
15477
15478        if (disabledPs == null) {
15479            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15480            return false;
15481        } else if (DEBUG_REMOVE) {
15482            Slog.d(TAG, "Deleting system pkg from data partition");
15483        }
15484
15485        if (DEBUG_REMOVE) {
15486            if (applyUserRestrictions) {
15487                Slog.d(TAG, "Remembering install states:");
15488                for (int userId : allUserHandles) {
15489                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15490                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15491                }
15492            }
15493        }
15494
15495        // Delete the updated package
15496        outInfo.isRemovedPackageSystemUpdate = true;
15497        if (outInfo.removedChildPackages != null) {
15498            final int childCount = (deletedPs.childPackageNames != null)
15499                    ? deletedPs.childPackageNames.size() : 0;
15500            for (int i = 0; i < childCount; i++) {
15501                String childPackageName = deletedPs.childPackageNames.get(i);
15502                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15503                        .contains(childPackageName)) {
15504                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15505                            childPackageName);
15506                    if (childInfo != null) {
15507                        childInfo.isRemovedPackageSystemUpdate = true;
15508                    }
15509                }
15510            }
15511        }
15512
15513        if (disabledPs.versionCode < deletedPs.versionCode) {
15514            // Delete data for downgrades
15515            flags &= ~PackageManager.DELETE_KEEP_DATA;
15516        } else {
15517            // Preserve data by setting flag
15518            flags |= PackageManager.DELETE_KEEP_DATA;
15519        }
15520
15521        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15522                outInfo, writeSettings, disabledPs.pkg);
15523        if (!ret) {
15524            return false;
15525        }
15526
15527        // writer
15528        synchronized (mPackages) {
15529            // Reinstate the old system package
15530            enableSystemPackageLPw(disabledPs.pkg);
15531            // Remove any native libraries from the upgraded package.
15532            removeNativeBinariesLI(deletedPs);
15533        }
15534
15535        // Install the system package
15536        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15537        int parseFlags = mDefParseFlags
15538                | PackageParser.PARSE_MUST_BE_APK
15539                | PackageParser.PARSE_IS_SYSTEM
15540                | PackageParser.PARSE_IS_SYSTEM_DIR;
15541        if (locationIsPrivileged(disabledPs.codePath)) {
15542            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15543        }
15544
15545        final PackageParser.Package newPkg;
15546        try {
15547            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15548        } catch (PackageManagerException e) {
15549            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15550                    + e.getMessage());
15551            return false;
15552        }
15553
15554        prepareAppDataAfterInstallLIF(newPkg);
15555
15556        // writer
15557        synchronized (mPackages) {
15558            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15559
15560            // Propagate the permissions state as we do not want to drop on the floor
15561            // runtime permissions. The update permissions method below will take
15562            // care of removing obsolete permissions and grant install permissions.
15563            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15564            updatePermissionsLPw(newPkg.packageName, newPkg,
15565                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15566
15567            if (applyUserRestrictions) {
15568                if (DEBUG_REMOVE) {
15569                    Slog.d(TAG, "Propagating install state across reinstall");
15570                }
15571                for (int userId : allUserHandles) {
15572                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15573                    if (DEBUG_REMOVE) {
15574                        Slog.d(TAG, "    user " + userId + " => " + installed);
15575                    }
15576                    ps.setInstalled(installed, userId);
15577
15578                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15579                }
15580                // Regardless of writeSettings we need to ensure that this restriction
15581                // state propagation is persisted
15582                mSettings.writeAllUsersPackageRestrictionsLPr();
15583            }
15584            // can downgrade to reader here
15585            if (writeSettings) {
15586                mSettings.writeLPr();
15587            }
15588        }
15589        return true;
15590    }
15591
15592    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15593            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15594            PackageRemovedInfo outInfo, boolean writeSettings,
15595            PackageParser.Package replacingPackage) {
15596        synchronized (mPackages) {
15597            if (outInfo != null) {
15598                outInfo.uid = ps.appId;
15599            }
15600
15601            if (outInfo != null && outInfo.removedChildPackages != null) {
15602                final int childCount = (ps.childPackageNames != null)
15603                        ? ps.childPackageNames.size() : 0;
15604                for (int i = 0; i < childCount; i++) {
15605                    String childPackageName = ps.childPackageNames.get(i);
15606                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15607                    if (childPs == null) {
15608                        return false;
15609                    }
15610                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15611                            childPackageName);
15612                    if (childInfo != null) {
15613                        childInfo.uid = childPs.appId;
15614                    }
15615                }
15616            }
15617        }
15618
15619        // Delete package data from internal structures and also remove data if flag is set
15620        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15621
15622        // Delete the child packages data
15623        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15624        for (int i = 0; i < childCount; i++) {
15625            PackageSetting childPs;
15626            synchronized (mPackages) {
15627                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15628            }
15629            if (childPs != null) {
15630                PackageRemovedInfo childOutInfo = (outInfo != null
15631                        && outInfo.removedChildPackages != null)
15632                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15633                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15634                        && (replacingPackage != null
15635                        && !replacingPackage.hasChildPackage(childPs.name))
15636                        ? flags & ~DELETE_KEEP_DATA : flags;
15637                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15638                        deleteFlags, writeSettings);
15639            }
15640        }
15641
15642        // Delete application code and resources only for parent packages
15643        if (ps.parentPackageName == null) {
15644            if (deleteCodeAndResources && (outInfo != null)) {
15645                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15646                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15647                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15648            }
15649        }
15650
15651        return true;
15652    }
15653
15654    @Override
15655    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15656            int userId) {
15657        mContext.enforceCallingOrSelfPermission(
15658                android.Manifest.permission.DELETE_PACKAGES, null);
15659        synchronized (mPackages) {
15660            PackageSetting ps = mSettings.mPackages.get(packageName);
15661            if (ps == null) {
15662                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15663                return false;
15664            }
15665            if (!ps.getInstalled(userId)) {
15666                // Can't block uninstall for an app that is not installed or enabled.
15667                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15668                return false;
15669            }
15670            ps.setBlockUninstall(blockUninstall, userId);
15671            mSettings.writePackageRestrictionsLPr(userId);
15672        }
15673        return true;
15674    }
15675
15676    @Override
15677    public boolean getBlockUninstallForUser(String packageName, int userId) {
15678        synchronized (mPackages) {
15679            PackageSetting ps = mSettings.mPackages.get(packageName);
15680            if (ps == null) {
15681                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15682                return false;
15683            }
15684            return ps.getBlockUninstall(userId);
15685        }
15686    }
15687
15688    @Override
15689    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15690        int callingUid = Binder.getCallingUid();
15691        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15692            throw new SecurityException(
15693                    "setRequiredForSystemUser can only be run by the system or root");
15694        }
15695        synchronized (mPackages) {
15696            PackageSetting ps = mSettings.mPackages.get(packageName);
15697            if (ps == null) {
15698                Log.w(TAG, "Package doesn't exist: " + packageName);
15699                return false;
15700            }
15701            if (systemUserApp) {
15702                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15703            } else {
15704                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15705            }
15706            mSettings.writeLPr();
15707        }
15708        return true;
15709    }
15710
15711    /*
15712     * This method handles package deletion in general
15713     */
15714    private boolean deletePackageLIF(String packageName, UserHandle user,
15715            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15716            PackageRemovedInfo outInfo, boolean writeSettings,
15717            PackageParser.Package replacingPackage) {
15718        if (packageName == null) {
15719            Slog.w(TAG, "Attempt to delete null packageName.");
15720            return false;
15721        }
15722
15723        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15724
15725        PackageSetting ps;
15726
15727        synchronized (mPackages) {
15728            ps = mSettings.mPackages.get(packageName);
15729            if (ps == null) {
15730                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15731                return false;
15732            }
15733
15734            if (ps.parentPackageName != null && (!isSystemApp(ps)
15735                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15736                if (DEBUG_REMOVE) {
15737                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15738                            + ((user == null) ? UserHandle.USER_ALL : user));
15739                }
15740                final int removedUserId = (user != null) ? user.getIdentifier()
15741                        : UserHandle.USER_ALL;
15742                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15743                    return false;
15744                }
15745                markPackageUninstalledForUserLPw(ps, user);
15746                scheduleWritePackageRestrictionsLocked(user);
15747                return true;
15748            }
15749        }
15750
15751        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15752                && user.getIdentifier() != UserHandle.USER_ALL)) {
15753            // The caller is asking that the package only be deleted for a single
15754            // user.  To do this, we just mark its uninstalled state and delete
15755            // its data. If this is a system app, we only allow this to happen if
15756            // they have set the special DELETE_SYSTEM_APP which requests different
15757            // semantics than normal for uninstalling system apps.
15758            markPackageUninstalledForUserLPw(ps, user);
15759
15760            if (!isSystemApp(ps)) {
15761                // Do not uninstall the APK if an app should be cached
15762                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15763                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15764                    // Other user still have this package installed, so all
15765                    // we need to do is clear this user's data and save that
15766                    // it is uninstalled.
15767                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15768                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15769                        return false;
15770                    }
15771                    scheduleWritePackageRestrictionsLocked(user);
15772                    return true;
15773                } else {
15774                    // We need to set it back to 'installed' so the uninstall
15775                    // broadcasts will be sent correctly.
15776                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15777                    ps.setInstalled(true, user.getIdentifier());
15778                }
15779            } else {
15780                // This is a system app, so we assume that the
15781                // other users still have this package installed, so all
15782                // we need to do is clear this user's data and save that
15783                // it is uninstalled.
15784                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15785                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15786                    return false;
15787                }
15788                scheduleWritePackageRestrictionsLocked(user);
15789                return true;
15790            }
15791        }
15792
15793        // If we are deleting a composite package for all users, keep track
15794        // of result for each child.
15795        if (ps.childPackageNames != null && outInfo != null) {
15796            synchronized (mPackages) {
15797                final int childCount = ps.childPackageNames.size();
15798                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15799                for (int i = 0; i < childCount; i++) {
15800                    String childPackageName = ps.childPackageNames.get(i);
15801                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15802                    childInfo.removedPackage = childPackageName;
15803                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15804                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15805                    if (childPs != null) {
15806                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15807                    }
15808                }
15809            }
15810        }
15811
15812        boolean ret = false;
15813        if (isSystemApp(ps)) {
15814            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15815            // When an updated system application is deleted we delete the existing resources
15816            // as well and fall back to existing code in system partition
15817            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15818        } else {
15819            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15820            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15821                    outInfo, writeSettings, replacingPackage);
15822        }
15823
15824        // Take a note whether we deleted the package for all users
15825        if (outInfo != null) {
15826            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15827            if (outInfo.removedChildPackages != null) {
15828                synchronized (mPackages) {
15829                    final int childCount = outInfo.removedChildPackages.size();
15830                    for (int i = 0; i < childCount; i++) {
15831                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15832                        if (childInfo != null) {
15833                            childInfo.removedForAllUsers = mPackages.get(
15834                                    childInfo.removedPackage) == null;
15835                        }
15836                    }
15837                }
15838            }
15839            // If we uninstalled an update to a system app there may be some
15840            // child packages that appeared as they are declared in the system
15841            // app but were not declared in the update.
15842            if (isSystemApp(ps)) {
15843                synchronized (mPackages) {
15844                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15845                    final int childCount = (updatedPs.childPackageNames != null)
15846                            ? updatedPs.childPackageNames.size() : 0;
15847                    for (int i = 0; i < childCount; i++) {
15848                        String childPackageName = updatedPs.childPackageNames.get(i);
15849                        if (outInfo.removedChildPackages == null
15850                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15851                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15852                            if (childPs == null) {
15853                                continue;
15854                            }
15855                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15856                            installRes.name = childPackageName;
15857                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15858                            installRes.pkg = mPackages.get(childPackageName);
15859                            installRes.uid = childPs.pkg.applicationInfo.uid;
15860                            if (outInfo.appearedChildPackages == null) {
15861                                outInfo.appearedChildPackages = new ArrayMap<>();
15862                            }
15863                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15864                        }
15865                    }
15866                }
15867            }
15868        }
15869
15870        return ret;
15871    }
15872
15873    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15874        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15875                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15876        for (int nextUserId : userIds) {
15877            if (DEBUG_REMOVE) {
15878                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15879            }
15880            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15881                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15882                    false /*hidden*/, false /*suspended*/, null, null, null,
15883                    false /*blockUninstall*/,
15884                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15885        }
15886    }
15887
15888    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15889            PackageRemovedInfo outInfo) {
15890        final PackageParser.Package pkg;
15891        synchronized (mPackages) {
15892            pkg = mPackages.get(ps.name);
15893        }
15894
15895        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15896                : new int[] {userId};
15897        for (int nextUserId : userIds) {
15898            if (DEBUG_REMOVE) {
15899                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15900                        + nextUserId);
15901            }
15902
15903            destroyAppDataLIF(pkg, userId,
15904                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15905            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15906            schedulePackageCleaning(ps.name, nextUserId, false);
15907            synchronized (mPackages) {
15908                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15909                    scheduleWritePackageRestrictionsLocked(nextUserId);
15910                }
15911                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15912            }
15913        }
15914
15915        if (outInfo != null) {
15916            outInfo.removedPackage = ps.name;
15917            outInfo.removedAppId = ps.appId;
15918            outInfo.removedUsers = userIds;
15919        }
15920
15921        return true;
15922    }
15923
15924    private final class ClearStorageConnection implements ServiceConnection {
15925        IMediaContainerService mContainerService;
15926
15927        @Override
15928        public void onServiceConnected(ComponentName name, IBinder service) {
15929            synchronized (this) {
15930                mContainerService = IMediaContainerService.Stub.asInterface(service);
15931                notifyAll();
15932            }
15933        }
15934
15935        @Override
15936        public void onServiceDisconnected(ComponentName name) {
15937        }
15938    }
15939
15940    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15941        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15942
15943        final boolean mounted;
15944        if (Environment.isExternalStorageEmulated()) {
15945            mounted = true;
15946        } else {
15947            final String status = Environment.getExternalStorageState();
15948
15949            mounted = status.equals(Environment.MEDIA_MOUNTED)
15950                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15951        }
15952
15953        if (!mounted) {
15954            return;
15955        }
15956
15957        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15958        int[] users;
15959        if (userId == UserHandle.USER_ALL) {
15960            users = sUserManager.getUserIds();
15961        } else {
15962            users = new int[] { userId };
15963        }
15964        final ClearStorageConnection conn = new ClearStorageConnection();
15965        if (mContext.bindServiceAsUser(
15966                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15967            try {
15968                for (int curUser : users) {
15969                    long timeout = SystemClock.uptimeMillis() + 5000;
15970                    synchronized (conn) {
15971                        long now = SystemClock.uptimeMillis();
15972                        while (conn.mContainerService == null && now < timeout) {
15973                            try {
15974                                conn.wait(timeout - now);
15975                            } catch (InterruptedException e) {
15976                            }
15977                        }
15978                    }
15979                    if (conn.mContainerService == null) {
15980                        return;
15981                    }
15982
15983                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15984                    clearDirectory(conn.mContainerService,
15985                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15986                    if (allData) {
15987                        clearDirectory(conn.mContainerService,
15988                                userEnv.buildExternalStorageAppDataDirs(packageName));
15989                        clearDirectory(conn.mContainerService,
15990                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15991                    }
15992                }
15993            } finally {
15994                mContext.unbindService(conn);
15995            }
15996        }
15997    }
15998
15999    @Override
16000    public void clearApplicationProfileData(String packageName) {
16001        enforceSystemOrRoot("Only the system can clear all profile data");
16002
16003        final PackageParser.Package pkg;
16004        synchronized (mPackages) {
16005            pkg = mPackages.get(packageName);
16006        }
16007
16008        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16009            synchronized (mInstallLock) {
16010                clearAppProfilesLIF(pkg);
16011            }
16012        }
16013    }
16014
16015    @Override
16016    public void clearApplicationUserData(final String packageName,
16017            final IPackageDataObserver observer, final int userId) {
16018        mContext.enforceCallingOrSelfPermission(
16019                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16020
16021        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16022                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16023
16024        final DevicePolicyManagerInternal dpmi = LocalServices
16025                .getService(DevicePolicyManagerInternal.class);
16026        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16027            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16028        }
16029        // Queue up an async operation since the package deletion may take a little while.
16030        mHandler.post(new Runnable() {
16031            public void run() {
16032                mHandler.removeCallbacks(this);
16033                final boolean succeeded;
16034                try (PackageFreezer freezer = freezePackage(packageName,
16035                        "clearApplicationUserData")) {
16036                    synchronized (mInstallLock) {
16037                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16038                    }
16039                    clearExternalStorageDataSync(packageName, userId, true);
16040                }
16041                if (succeeded) {
16042                    // invoke DeviceStorageMonitor's update method to clear any notifications
16043                    DeviceStorageMonitorInternal dsm = LocalServices
16044                            .getService(DeviceStorageMonitorInternal.class);
16045                    if (dsm != null) {
16046                        dsm.checkMemory();
16047                    }
16048                }
16049                if(observer != null) {
16050                    try {
16051                        observer.onRemoveCompleted(packageName, succeeded);
16052                    } catch (RemoteException e) {
16053                        Log.i(TAG, "Observer no longer exists.");
16054                    }
16055                } //end if observer
16056            } //end run
16057        });
16058    }
16059
16060    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16061        if (packageName == null) {
16062            Slog.w(TAG, "Attempt to delete null packageName.");
16063            return false;
16064        }
16065
16066        // Try finding details about the requested package
16067        PackageParser.Package pkg;
16068        synchronized (mPackages) {
16069            pkg = mPackages.get(packageName);
16070            if (pkg == null) {
16071                final PackageSetting ps = mSettings.mPackages.get(packageName);
16072                if (ps != null) {
16073                    pkg = ps.pkg;
16074                }
16075            }
16076
16077            if (pkg == null) {
16078                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16079                return false;
16080            }
16081
16082            PackageSetting ps = (PackageSetting) pkg.mExtras;
16083            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16084        }
16085
16086        clearAppDataLIF(pkg, userId,
16087                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16088
16089        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16090        removeKeystoreDataIfNeeded(userId, appId);
16091
16092        final UserManager um = mContext.getSystemService(UserManager.class);
16093        final int flags;
16094        if (um.isUserUnlockingOrUnlocked(userId)) {
16095            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16096        } else if (um.isUserRunning(userId)) {
16097            flags = StorageManager.FLAG_STORAGE_DE;
16098        } else {
16099            flags = 0;
16100        }
16101        prepareAppDataContentsLIF(pkg, userId, flags);
16102
16103        return true;
16104    }
16105
16106    /**
16107     * Reverts user permission state changes (permissions and flags) in
16108     * all packages for a given user.
16109     *
16110     * @param userId The device user for which to do a reset.
16111     */
16112    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16113        final int packageCount = mPackages.size();
16114        for (int i = 0; i < packageCount; i++) {
16115            PackageParser.Package pkg = mPackages.valueAt(i);
16116            PackageSetting ps = (PackageSetting) pkg.mExtras;
16117            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16118        }
16119    }
16120
16121    /**
16122     * Reverts user permission state changes (permissions and flags).
16123     *
16124     * @param ps The package for which to reset.
16125     * @param userId The device user for which to do a reset.
16126     */
16127    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16128            final PackageSetting ps, final int userId) {
16129        if (ps.pkg == null) {
16130            return;
16131        }
16132
16133        // These are flags that can change base on user actions.
16134        final int userSettableMask = FLAG_PERMISSION_USER_SET
16135                | FLAG_PERMISSION_USER_FIXED
16136                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16137                | FLAG_PERMISSION_REVIEW_REQUIRED;
16138
16139        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16140                | FLAG_PERMISSION_POLICY_FIXED;
16141
16142        boolean writeInstallPermissions = false;
16143        boolean writeRuntimePermissions = false;
16144
16145        final int permissionCount = ps.pkg.requestedPermissions.size();
16146        for (int i = 0; i < permissionCount; i++) {
16147            String permission = ps.pkg.requestedPermissions.get(i);
16148
16149            BasePermission bp = mSettings.mPermissions.get(permission);
16150            if (bp == null) {
16151                continue;
16152            }
16153
16154            // If shared user we just reset the state to which only this app contributed.
16155            if (ps.sharedUser != null) {
16156                boolean used = false;
16157                final int packageCount = ps.sharedUser.packages.size();
16158                for (int j = 0; j < packageCount; j++) {
16159                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16160                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16161                            && pkg.pkg.requestedPermissions.contains(permission)) {
16162                        used = true;
16163                        break;
16164                    }
16165                }
16166                if (used) {
16167                    continue;
16168                }
16169            }
16170
16171            PermissionsState permissionsState = ps.getPermissionsState();
16172
16173            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16174
16175            // Always clear the user settable flags.
16176            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16177                    bp.name) != null;
16178            // If permission review is enabled and this is a legacy app, mark the
16179            // permission as requiring a review as this is the initial state.
16180            int flags = 0;
16181            if (Build.PERMISSIONS_REVIEW_REQUIRED
16182                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16183                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16184            }
16185            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16186                if (hasInstallState) {
16187                    writeInstallPermissions = true;
16188                } else {
16189                    writeRuntimePermissions = true;
16190                }
16191            }
16192
16193            // Below is only runtime permission handling.
16194            if (!bp.isRuntime()) {
16195                continue;
16196            }
16197
16198            // Never clobber system or policy.
16199            if ((oldFlags & policyOrSystemFlags) != 0) {
16200                continue;
16201            }
16202
16203            // If this permission was granted by default, make sure it is.
16204            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16205                if (permissionsState.grantRuntimePermission(bp, userId)
16206                        != PERMISSION_OPERATION_FAILURE) {
16207                    writeRuntimePermissions = true;
16208                }
16209            // If permission review is enabled the permissions for a legacy apps
16210            // are represented as constantly granted runtime ones, so don't revoke.
16211            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16212                // Otherwise, reset the permission.
16213                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16214                switch (revokeResult) {
16215                    case PERMISSION_OPERATION_SUCCESS:
16216                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16217                        writeRuntimePermissions = true;
16218                        final int appId = ps.appId;
16219                        mHandler.post(new Runnable() {
16220                            @Override
16221                            public void run() {
16222                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16223                            }
16224                        });
16225                    } break;
16226                }
16227            }
16228        }
16229
16230        // Synchronously write as we are taking permissions away.
16231        if (writeRuntimePermissions) {
16232            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16233        }
16234
16235        // Synchronously write as we are taking permissions away.
16236        if (writeInstallPermissions) {
16237            mSettings.writeLPr();
16238        }
16239    }
16240
16241    /**
16242     * Remove entries from the keystore daemon. Will only remove it if the
16243     * {@code appId} is valid.
16244     */
16245    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16246        if (appId < 0) {
16247            return;
16248        }
16249
16250        final KeyStore keyStore = KeyStore.getInstance();
16251        if (keyStore != null) {
16252            if (userId == UserHandle.USER_ALL) {
16253                for (final int individual : sUserManager.getUserIds()) {
16254                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16255                }
16256            } else {
16257                keyStore.clearUid(UserHandle.getUid(userId, appId));
16258            }
16259        } else {
16260            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16261        }
16262    }
16263
16264    @Override
16265    public void deleteApplicationCacheFiles(final String packageName,
16266            final IPackageDataObserver observer) {
16267        final int userId = UserHandle.getCallingUserId();
16268        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16269    }
16270
16271    @Override
16272    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16273            final IPackageDataObserver observer) {
16274        mContext.enforceCallingOrSelfPermission(
16275                android.Manifest.permission.DELETE_CACHE_FILES, null);
16276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16277                /* requireFullPermission= */ true, /* checkShell= */ false,
16278                "delete application cache files");
16279
16280        final PackageParser.Package pkg;
16281        synchronized (mPackages) {
16282            pkg = mPackages.get(packageName);
16283        }
16284
16285        // Queue up an async operation since the package deletion may take a little while.
16286        mHandler.post(new Runnable() {
16287            public void run() {
16288                synchronized (mInstallLock) {
16289                    final int flags = StorageManager.FLAG_STORAGE_DE
16290                            | StorageManager.FLAG_STORAGE_CE;
16291                    // We're only clearing cache files, so we don't care if the
16292                    // app is unfrozen and still able to run
16293                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16294                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16295                }
16296                clearExternalStorageDataSync(packageName, userId, false);
16297                if (observer != null) {
16298                    try {
16299                        observer.onRemoveCompleted(packageName, true);
16300                    } catch (RemoteException e) {
16301                        Log.i(TAG, "Observer no longer exists.");
16302                    }
16303                }
16304            }
16305        });
16306    }
16307
16308    @Override
16309    public void getPackageSizeInfo(final String packageName, int userHandle,
16310            final IPackageStatsObserver observer) {
16311        mContext.enforceCallingOrSelfPermission(
16312                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16313        if (packageName == null) {
16314            throw new IllegalArgumentException("Attempt to get size of null packageName");
16315        }
16316
16317        PackageStats stats = new PackageStats(packageName, userHandle);
16318
16319        /*
16320         * Queue up an async operation since the package measurement may take a
16321         * little while.
16322         */
16323        Message msg = mHandler.obtainMessage(INIT_COPY);
16324        msg.obj = new MeasureParams(stats, observer);
16325        mHandler.sendMessage(msg);
16326    }
16327
16328    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16329        final PackageSetting ps;
16330        synchronized (mPackages) {
16331            ps = mSettings.mPackages.get(packageName);
16332            if (ps == null) {
16333                Slog.w(TAG, "Failed to find settings for " + packageName);
16334                return false;
16335            }
16336        }
16337        try {
16338            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16339                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16340                    ps.getCeDataInode(userId), ps.codePathString, stats);
16341        } catch (InstallerException e) {
16342            Slog.w(TAG, String.valueOf(e));
16343            return false;
16344        }
16345
16346        // For now, ignore code size of packages on system partition
16347        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16348            stats.codeSize = 0;
16349        }
16350
16351        return true;
16352    }
16353
16354    private int getUidTargetSdkVersionLockedLPr(int uid) {
16355        Object obj = mSettings.getUserIdLPr(uid);
16356        if (obj instanceof SharedUserSetting) {
16357            final SharedUserSetting sus = (SharedUserSetting) obj;
16358            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16359            final Iterator<PackageSetting> it = sus.packages.iterator();
16360            while (it.hasNext()) {
16361                final PackageSetting ps = it.next();
16362                if (ps.pkg != null) {
16363                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16364                    if (v < vers) vers = v;
16365                }
16366            }
16367            return vers;
16368        } else if (obj instanceof PackageSetting) {
16369            final PackageSetting ps = (PackageSetting) obj;
16370            if (ps.pkg != null) {
16371                return ps.pkg.applicationInfo.targetSdkVersion;
16372            }
16373        }
16374        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16375    }
16376
16377    @Override
16378    public void addPreferredActivity(IntentFilter filter, int match,
16379            ComponentName[] set, ComponentName activity, int userId) {
16380        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16381                "Adding preferred");
16382    }
16383
16384    private void addPreferredActivityInternal(IntentFilter filter, int match,
16385            ComponentName[] set, ComponentName activity, boolean always, int userId,
16386            String opname) {
16387        // writer
16388        int callingUid = Binder.getCallingUid();
16389        enforceCrossUserPermission(callingUid, userId,
16390                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16391        if (filter.countActions() == 0) {
16392            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16393            return;
16394        }
16395        synchronized (mPackages) {
16396            if (mContext.checkCallingOrSelfPermission(
16397                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16398                    != PackageManager.PERMISSION_GRANTED) {
16399                if (getUidTargetSdkVersionLockedLPr(callingUid)
16400                        < Build.VERSION_CODES.FROYO) {
16401                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16402                            + callingUid);
16403                    return;
16404                }
16405                mContext.enforceCallingOrSelfPermission(
16406                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16407            }
16408
16409            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16410            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16411                    + userId + ":");
16412            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16413            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16414            scheduleWritePackageRestrictionsLocked(userId);
16415        }
16416    }
16417
16418    @Override
16419    public void replacePreferredActivity(IntentFilter filter, int match,
16420            ComponentName[] set, ComponentName activity, int userId) {
16421        if (filter.countActions() != 1) {
16422            throw new IllegalArgumentException(
16423                    "replacePreferredActivity expects filter to have only 1 action.");
16424        }
16425        if (filter.countDataAuthorities() != 0
16426                || filter.countDataPaths() != 0
16427                || filter.countDataSchemes() > 1
16428                || filter.countDataTypes() != 0) {
16429            throw new IllegalArgumentException(
16430                    "replacePreferredActivity expects filter to have no data authorities, " +
16431                    "paths, or types; and at most one scheme.");
16432        }
16433
16434        final int callingUid = Binder.getCallingUid();
16435        enforceCrossUserPermission(callingUid, userId,
16436                true /* requireFullPermission */, false /* checkShell */,
16437                "replace preferred activity");
16438        synchronized (mPackages) {
16439            if (mContext.checkCallingOrSelfPermission(
16440                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16441                    != PackageManager.PERMISSION_GRANTED) {
16442                if (getUidTargetSdkVersionLockedLPr(callingUid)
16443                        < Build.VERSION_CODES.FROYO) {
16444                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16445                            + Binder.getCallingUid());
16446                    return;
16447                }
16448                mContext.enforceCallingOrSelfPermission(
16449                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16450            }
16451
16452            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16453            if (pir != null) {
16454                // Get all of the existing entries that exactly match this filter.
16455                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16456                if (existing != null && existing.size() == 1) {
16457                    PreferredActivity cur = existing.get(0);
16458                    if (DEBUG_PREFERRED) {
16459                        Slog.i(TAG, "Checking replace of preferred:");
16460                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16461                        if (!cur.mPref.mAlways) {
16462                            Slog.i(TAG, "  -- CUR; not mAlways!");
16463                        } else {
16464                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16465                            Slog.i(TAG, "  -- CUR: mSet="
16466                                    + Arrays.toString(cur.mPref.mSetComponents));
16467                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16468                            Slog.i(TAG, "  -- NEW: mMatch="
16469                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16470                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16471                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16472                        }
16473                    }
16474                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16475                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16476                            && cur.mPref.sameSet(set)) {
16477                        // Setting the preferred activity to what it happens to be already
16478                        if (DEBUG_PREFERRED) {
16479                            Slog.i(TAG, "Replacing with same preferred activity "
16480                                    + cur.mPref.mShortComponent + " for user "
16481                                    + userId + ":");
16482                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16483                        }
16484                        return;
16485                    }
16486                }
16487
16488                if (existing != null) {
16489                    if (DEBUG_PREFERRED) {
16490                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16491                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16492                    }
16493                    for (int i = 0; i < existing.size(); i++) {
16494                        PreferredActivity pa = existing.get(i);
16495                        if (DEBUG_PREFERRED) {
16496                            Slog.i(TAG, "Removing existing preferred activity "
16497                                    + pa.mPref.mComponent + ":");
16498                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16499                        }
16500                        pir.removeFilter(pa);
16501                    }
16502                }
16503            }
16504            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16505                    "Replacing preferred");
16506        }
16507    }
16508
16509    @Override
16510    public void clearPackagePreferredActivities(String packageName) {
16511        final int uid = Binder.getCallingUid();
16512        // writer
16513        synchronized (mPackages) {
16514            PackageParser.Package pkg = mPackages.get(packageName);
16515            if (pkg == null || pkg.applicationInfo.uid != uid) {
16516                if (mContext.checkCallingOrSelfPermission(
16517                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16518                        != PackageManager.PERMISSION_GRANTED) {
16519                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16520                            < Build.VERSION_CODES.FROYO) {
16521                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16522                                + Binder.getCallingUid());
16523                        return;
16524                    }
16525                    mContext.enforceCallingOrSelfPermission(
16526                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16527                }
16528            }
16529
16530            int user = UserHandle.getCallingUserId();
16531            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16532                scheduleWritePackageRestrictionsLocked(user);
16533            }
16534        }
16535    }
16536
16537    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16538    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16539        ArrayList<PreferredActivity> removed = null;
16540        boolean changed = false;
16541        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16542            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16543            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16544            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16545                continue;
16546            }
16547            Iterator<PreferredActivity> it = pir.filterIterator();
16548            while (it.hasNext()) {
16549                PreferredActivity pa = it.next();
16550                // Mark entry for removal only if it matches the package name
16551                // and the entry is of type "always".
16552                if (packageName == null ||
16553                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16554                                && pa.mPref.mAlways)) {
16555                    if (removed == null) {
16556                        removed = new ArrayList<PreferredActivity>();
16557                    }
16558                    removed.add(pa);
16559                }
16560            }
16561            if (removed != null) {
16562                for (int j=0; j<removed.size(); j++) {
16563                    PreferredActivity pa = removed.get(j);
16564                    pir.removeFilter(pa);
16565                }
16566                changed = true;
16567            }
16568        }
16569        return changed;
16570    }
16571
16572    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16573    private void clearIntentFilterVerificationsLPw(int userId) {
16574        final int packageCount = mPackages.size();
16575        for (int i = 0; i < packageCount; i++) {
16576            PackageParser.Package pkg = mPackages.valueAt(i);
16577            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16578        }
16579    }
16580
16581    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16582    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16583        if (userId == UserHandle.USER_ALL) {
16584            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16585                    sUserManager.getUserIds())) {
16586                for (int oneUserId : sUserManager.getUserIds()) {
16587                    scheduleWritePackageRestrictionsLocked(oneUserId);
16588                }
16589            }
16590        } else {
16591            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16592                scheduleWritePackageRestrictionsLocked(userId);
16593            }
16594        }
16595    }
16596
16597    void clearDefaultBrowserIfNeeded(String packageName) {
16598        for (int oneUserId : sUserManager.getUserIds()) {
16599            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16600            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16601            if (packageName.equals(defaultBrowserPackageName)) {
16602                setDefaultBrowserPackageName(null, oneUserId);
16603            }
16604        }
16605    }
16606
16607    @Override
16608    public void resetApplicationPreferences(int userId) {
16609        mContext.enforceCallingOrSelfPermission(
16610                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16611        // writer
16612        synchronized (mPackages) {
16613            final long identity = Binder.clearCallingIdentity();
16614            try {
16615                clearPackagePreferredActivitiesLPw(null, userId);
16616                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16617                // TODO: We have to reset the default SMS and Phone. This requires
16618                // significant refactoring to keep all default apps in the package
16619                // manager (cleaner but more work) or have the services provide
16620                // callbacks to the package manager to request a default app reset.
16621                applyFactoryDefaultBrowserLPw(userId);
16622                clearIntentFilterVerificationsLPw(userId);
16623                primeDomainVerificationsLPw(userId);
16624                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16625                scheduleWritePackageRestrictionsLocked(userId);
16626            } finally {
16627                Binder.restoreCallingIdentity(identity);
16628            }
16629        }
16630    }
16631
16632    @Override
16633    public int getPreferredActivities(List<IntentFilter> outFilters,
16634            List<ComponentName> outActivities, String packageName) {
16635
16636        int num = 0;
16637        final int userId = UserHandle.getCallingUserId();
16638        // reader
16639        synchronized (mPackages) {
16640            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16641            if (pir != null) {
16642                final Iterator<PreferredActivity> it = pir.filterIterator();
16643                while (it.hasNext()) {
16644                    final PreferredActivity pa = it.next();
16645                    if (packageName == null
16646                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16647                                    && pa.mPref.mAlways)) {
16648                        if (outFilters != null) {
16649                            outFilters.add(new IntentFilter(pa));
16650                        }
16651                        if (outActivities != null) {
16652                            outActivities.add(pa.mPref.mComponent);
16653                        }
16654                    }
16655                }
16656            }
16657        }
16658
16659        return num;
16660    }
16661
16662    @Override
16663    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16664            int userId) {
16665        int callingUid = Binder.getCallingUid();
16666        if (callingUid != Process.SYSTEM_UID) {
16667            throw new SecurityException(
16668                    "addPersistentPreferredActivity can only be run by the system");
16669        }
16670        if (filter.countActions() == 0) {
16671            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16672            return;
16673        }
16674        synchronized (mPackages) {
16675            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16676                    ":");
16677            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16678            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16679                    new PersistentPreferredActivity(filter, activity));
16680            scheduleWritePackageRestrictionsLocked(userId);
16681        }
16682    }
16683
16684    @Override
16685    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16686        int callingUid = Binder.getCallingUid();
16687        if (callingUid != Process.SYSTEM_UID) {
16688            throw new SecurityException(
16689                    "clearPackagePersistentPreferredActivities can only be run by the system");
16690        }
16691        ArrayList<PersistentPreferredActivity> removed = null;
16692        boolean changed = false;
16693        synchronized (mPackages) {
16694            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16695                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16696                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16697                        .valueAt(i);
16698                if (userId != thisUserId) {
16699                    continue;
16700                }
16701                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16702                while (it.hasNext()) {
16703                    PersistentPreferredActivity ppa = it.next();
16704                    // Mark entry for removal only if it matches the package name.
16705                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16706                        if (removed == null) {
16707                            removed = new ArrayList<PersistentPreferredActivity>();
16708                        }
16709                        removed.add(ppa);
16710                    }
16711                }
16712                if (removed != null) {
16713                    for (int j=0; j<removed.size(); j++) {
16714                        PersistentPreferredActivity ppa = removed.get(j);
16715                        ppir.removeFilter(ppa);
16716                    }
16717                    changed = true;
16718                }
16719            }
16720
16721            if (changed) {
16722                scheduleWritePackageRestrictionsLocked(userId);
16723            }
16724        }
16725    }
16726
16727    /**
16728     * Common machinery for picking apart a restored XML blob and passing
16729     * it to a caller-supplied functor to be applied to the running system.
16730     */
16731    private void restoreFromXml(XmlPullParser parser, int userId,
16732            String expectedStartTag, BlobXmlRestorer functor)
16733            throws IOException, XmlPullParserException {
16734        int type;
16735        while ((type = parser.next()) != XmlPullParser.START_TAG
16736                && type != XmlPullParser.END_DOCUMENT) {
16737        }
16738        if (type != XmlPullParser.START_TAG) {
16739            // oops didn't find a start tag?!
16740            if (DEBUG_BACKUP) {
16741                Slog.e(TAG, "Didn't find start tag during restore");
16742            }
16743            return;
16744        }
16745Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16746        // this is supposed to be TAG_PREFERRED_BACKUP
16747        if (!expectedStartTag.equals(parser.getName())) {
16748            if (DEBUG_BACKUP) {
16749                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16750            }
16751            return;
16752        }
16753
16754        // skip interfering stuff, then we're aligned with the backing implementation
16755        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16756Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16757        functor.apply(parser, userId);
16758    }
16759
16760    private interface BlobXmlRestorer {
16761        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16762    }
16763
16764    /**
16765     * Non-Binder method, support for the backup/restore mechanism: write the
16766     * full set of preferred activities in its canonical XML format.  Returns the
16767     * XML output as a byte array, or null if there is none.
16768     */
16769    @Override
16770    public byte[] getPreferredActivityBackup(int userId) {
16771        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16772            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16773        }
16774
16775        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16776        try {
16777            final XmlSerializer serializer = new FastXmlSerializer();
16778            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16779            serializer.startDocument(null, true);
16780            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16781
16782            synchronized (mPackages) {
16783                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16784            }
16785
16786            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16787            serializer.endDocument();
16788            serializer.flush();
16789        } catch (Exception e) {
16790            if (DEBUG_BACKUP) {
16791                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16792            }
16793            return null;
16794        }
16795
16796        return dataStream.toByteArray();
16797    }
16798
16799    @Override
16800    public void restorePreferredActivities(byte[] backup, int userId) {
16801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16802            throw new SecurityException("Only the system may call restorePreferredActivities()");
16803        }
16804
16805        try {
16806            final XmlPullParser parser = Xml.newPullParser();
16807            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16808            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16809                    new BlobXmlRestorer() {
16810                        @Override
16811                        public void apply(XmlPullParser parser, int userId)
16812                                throws XmlPullParserException, IOException {
16813                            synchronized (mPackages) {
16814                                mSettings.readPreferredActivitiesLPw(parser, userId);
16815                            }
16816                        }
16817                    } );
16818        } catch (Exception e) {
16819            if (DEBUG_BACKUP) {
16820                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16821            }
16822        }
16823    }
16824
16825    /**
16826     * Non-Binder method, support for the backup/restore mechanism: write the
16827     * default browser (etc) settings in its canonical XML format.  Returns the default
16828     * browser XML representation as a byte array, or null if there is none.
16829     */
16830    @Override
16831    public byte[] getDefaultAppsBackup(int userId) {
16832        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16833            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16834        }
16835
16836        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16837        try {
16838            final XmlSerializer serializer = new FastXmlSerializer();
16839            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16840            serializer.startDocument(null, true);
16841            serializer.startTag(null, TAG_DEFAULT_APPS);
16842
16843            synchronized (mPackages) {
16844                mSettings.writeDefaultAppsLPr(serializer, userId);
16845            }
16846
16847            serializer.endTag(null, TAG_DEFAULT_APPS);
16848            serializer.endDocument();
16849            serializer.flush();
16850        } catch (Exception e) {
16851            if (DEBUG_BACKUP) {
16852                Slog.e(TAG, "Unable to write default apps for backup", e);
16853            }
16854            return null;
16855        }
16856
16857        return dataStream.toByteArray();
16858    }
16859
16860    @Override
16861    public void restoreDefaultApps(byte[] backup, int userId) {
16862        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16863            throw new SecurityException("Only the system may call restoreDefaultApps()");
16864        }
16865
16866        try {
16867            final XmlPullParser parser = Xml.newPullParser();
16868            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16869            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16870                    new BlobXmlRestorer() {
16871                        @Override
16872                        public void apply(XmlPullParser parser, int userId)
16873                                throws XmlPullParserException, IOException {
16874                            synchronized (mPackages) {
16875                                mSettings.readDefaultAppsLPw(parser, userId);
16876                            }
16877                        }
16878                    } );
16879        } catch (Exception e) {
16880            if (DEBUG_BACKUP) {
16881                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16882            }
16883        }
16884    }
16885
16886    @Override
16887    public byte[] getIntentFilterVerificationBackup(int userId) {
16888        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16889            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16890        }
16891
16892        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16893        try {
16894            final XmlSerializer serializer = new FastXmlSerializer();
16895            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16896            serializer.startDocument(null, true);
16897            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16898
16899            synchronized (mPackages) {
16900                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16901            }
16902
16903            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16904            serializer.endDocument();
16905            serializer.flush();
16906        } catch (Exception e) {
16907            if (DEBUG_BACKUP) {
16908                Slog.e(TAG, "Unable to write default apps for backup", e);
16909            }
16910            return null;
16911        }
16912
16913        return dataStream.toByteArray();
16914    }
16915
16916    @Override
16917    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16918        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16919            throw new SecurityException("Only the system may call restorePreferredActivities()");
16920        }
16921
16922        try {
16923            final XmlPullParser parser = Xml.newPullParser();
16924            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16925            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16926                    new BlobXmlRestorer() {
16927                        @Override
16928                        public void apply(XmlPullParser parser, int userId)
16929                                throws XmlPullParserException, IOException {
16930                            synchronized (mPackages) {
16931                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16932                                mSettings.writeLPr();
16933                            }
16934                        }
16935                    } );
16936        } catch (Exception e) {
16937            if (DEBUG_BACKUP) {
16938                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16939            }
16940        }
16941    }
16942
16943    @Override
16944    public byte[] getPermissionGrantBackup(int userId) {
16945        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16946            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16947        }
16948
16949        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16950        try {
16951            final XmlSerializer serializer = new FastXmlSerializer();
16952            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16953            serializer.startDocument(null, true);
16954            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16955
16956            synchronized (mPackages) {
16957                serializeRuntimePermissionGrantsLPr(serializer, userId);
16958            }
16959
16960            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16961            serializer.endDocument();
16962            serializer.flush();
16963        } catch (Exception e) {
16964            if (DEBUG_BACKUP) {
16965                Slog.e(TAG, "Unable to write default apps for backup", e);
16966            }
16967            return null;
16968        }
16969
16970        return dataStream.toByteArray();
16971    }
16972
16973    @Override
16974    public void restorePermissionGrants(byte[] backup, int userId) {
16975        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16976            throw new SecurityException("Only the system may call restorePermissionGrants()");
16977        }
16978
16979        try {
16980            final XmlPullParser parser = Xml.newPullParser();
16981            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16982            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16983                    new BlobXmlRestorer() {
16984                        @Override
16985                        public void apply(XmlPullParser parser, int userId)
16986                                throws XmlPullParserException, IOException {
16987                            synchronized (mPackages) {
16988                                processRestoredPermissionGrantsLPr(parser, userId);
16989                            }
16990                        }
16991                    } );
16992        } catch (Exception e) {
16993            if (DEBUG_BACKUP) {
16994                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16995            }
16996        }
16997    }
16998
16999    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17000            throws IOException {
17001        serializer.startTag(null, TAG_ALL_GRANTS);
17002
17003        final int N = mSettings.mPackages.size();
17004        for (int i = 0; i < N; i++) {
17005            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17006            boolean pkgGrantsKnown = false;
17007
17008            PermissionsState packagePerms = ps.getPermissionsState();
17009
17010            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17011                final int grantFlags = state.getFlags();
17012                // only look at grants that are not system/policy fixed
17013                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17014                    final boolean isGranted = state.isGranted();
17015                    // And only back up the user-twiddled state bits
17016                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17017                        final String packageName = mSettings.mPackages.keyAt(i);
17018                        if (!pkgGrantsKnown) {
17019                            serializer.startTag(null, TAG_GRANT);
17020                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17021                            pkgGrantsKnown = true;
17022                        }
17023
17024                        final boolean userSet =
17025                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17026                        final boolean userFixed =
17027                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17028                        final boolean revoke =
17029                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17030
17031                        serializer.startTag(null, TAG_PERMISSION);
17032                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17033                        if (isGranted) {
17034                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17035                        }
17036                        if (userSet) {
17037                            serializer.attribute(null, ATTR_USER_SET, "true");
17038                        }
17039                        if (userFixed) {
17040                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17041                        }
17042                        if (revoke) {
17043                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17044                        }
17045                        serializer.endTag(null, TAG_PERMISSION);
17046                    }
17047                }
17048            }
17049
17050            if (pkgGrantsKnown) {
17051                serializer.endTag(null, TAG_GRANT);
17052            }
17053        }
17054
17055        serializer.endTag(null, TAG_ALL_GRANTS);
17056    }
17057
17058    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17059            throws XmlPullParserException, IOException {
17060        String pkgName = null;
17061        int outerDepth = parser.getDepth();
17062        int type;
17063        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17064                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17065            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17066                continue;
17067            }
17068
17069            final String tagName = parser.getName();
17070            if (tagName.equals(TAG_GRANT)) {
17071                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17072                if (DEBUG_BACKUP) {
17073                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17074                }
17075            } else if (tagName.equals(TAG_PERMISSION)) {
17076
17077                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17078                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17079
17080                int newFlagSet = 0;
17081                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17082                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17083                }
17084                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17085                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17086                }
17087                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17088                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17089                }
17090                if (DEBUG_BACKUP) {
17091                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17092                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17093                }
17094                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17095                if (ps != null) {
17096                    // Already installed so we apply the grant immediately
17097                    if (DEBUG_BACKUP) {
17098                        Slog.v(TAG, "        + already installed; applying");
17099                    }
17100                    PermissionsState perms = ps.getPermissionsState();
17101                    BasePermission bp = mSettings.mPermissions.get(permName);
17102                    if (bp != null) {
17103                        if (isGranted) {
17104                            perms.grantRuntimePermission(bp, userId);
17105                        }
17106                        if (newFlagSet != 0) {
17107                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17108                        }
17109                    }
17110                } else {
17111                    // Need to wait for post-restore install to apply the grant
17112                    if (DEBUG_BACKUP) {
17113                        Slog.v(TAG, "        - not yet installed; saving for later");
17114                    }
17115                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17116                            isGranted, newFlagSet, userId);
17117                }
17118            } else {
17119                PackageManagerService.reportSettingsProblem(Log.WARN,
17120                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17121                XmlUtils.skipCurrentTag(parser);
17122            }
17123        }
17124
17125        scheduleWriteSettingsLocked();
17126        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17127    }
17128
17129    @Override
17130    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17131            int sourceUserId, int targetUserId, int flags) {
17132        mContext.enforceCallingOrSelfPermission(
17133                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17134        int callingUid = Binder.getCallingUid();
17135        enforceOwnerRights(ownerPackage, callingUid);
17136        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17137        if (intentFilter.countActions() == 0) {
17138            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17139            return;
17140        }
17141        synchronized (mPackages) {
17142            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17143                    ownerPackage, targetUserId, flags);
17144            CrossProfileIntentResolver resolver =
17145                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17146            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17147            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17148            if (existing != null) {
17149                int size = existing.size();
17150                for (int i = 0; i < size; i++) {
17151                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17152                        return;
17153                    }
17154                }
17155            }
17156            resolver.addFilter(newFilter);
17157            scheduleWritePackageRestrictionsLocked(sourceUserId);
17158        }
17159    }
17160
17161    @Override
17162    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17163        mContext.enforceCallingOrSelfPermission(
17164                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17165        int callingUid = Binder.getCallingUid();
17166        enforceOwnerRights(ownerPackage, callingUid);
17167        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17168        synchronized (mPackages) {
17169            CrossProfileIntentResolver resolver =
17170                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17171            ArraySet<CrossProfileIntentFilter> set =
17172                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17173            for (CrossProfileIntentFilter filter : set) {
17174                if (filter.getOwnerPackage().equals(ownerPackage)) {
17175                    resolver.removeFilter(filter);
17176                }
17177            }
17178            scheduleWritePackageRestrictionsLocked(sourceUserId);
17179        }
17180    }
17181
17182    // Enforcing that callingUid is owning pkg on userId
17183    private void enforceOwnerRights(String pkg, int callingUid) {
17184        // The system owns everything.
17185        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17186            return;
17187        }
17188        int callingUserId = UserHandle.getUserId(callingUid);
17189        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17190        if (pi == null) {
17191            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17192                    + callingUserId);
17193        }
17194        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17195            throw new SecurityException("Calling uid " + callingUid
17196                    + " does not own package " + pkg);
17197        }
17198    }
17199
17200    @Override
17201    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17202        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17203    }
17204
17205    private Intent getHomeIntent() {
17206        Intent intent = new Intent(Intent.ACTION_MAIN);
17207        intent.addCategory(Intent.CATEGORY_HOME);
17208        return intent;
17209    }
17210
17211    private IntentFilter getHomeFilter() {
17212        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17213        filter.addCategory(Intent.CATEGORY_HOME);
17214        filter.addCategory(Intent.CATEGORY_DEFAULT);
17215        return filter;
17216    }
17217
17218    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17219            int userId) {
17220        Intent intent  = getHomeIntent();
17221        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17222                PackageManager.GET_META_DATA, userId);
17223        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17224                true, false, false, userId);
17225
17226        allHomeCandidates.clear();
17227        if (list != null) {
17228            for (ResolveInfo ri : list) {
17229                allHomeCandidates.add(ri);
17230            }
17231        }
17232        return (preferred == null || preferred.activityInfo == null)
17233                ? null
17234                : new ComponentName(preferred.activityInfo.packageName,
17235                        preferred.activityInfo.name);
17236    }
17237
17238    @Override
17239    public void setHomeActivity(ComponentName comp, int userId) {
17240        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17241        getHomeActivitiesAsUser(homeActivities, userId);
17242
17243        boolean found = false;
17244
17245        final int size = homeActivities.size();
17246        final ComponentName[] set = new ComponentName[size];
17247        for (int i = 0; i < size; i++) {
17248            final ResolveInfo candidate = homeActivities.get(i);
17249            final ActivityInfo info = candidate.activityInfo;
17250            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17251            set[i] = activityName;
17252            if (!found && activityName.equals(comp)) {
17253                found = true;
17254            }
17255        }
17256        if (!found) {
17257            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17258                    + userId);
17259        }
17260        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17261                set, comp, userId);
17262    }
17263
17264    private @Nullable String getSetupWizardPackageName() {
17265        final Intent intent = new Intent(Intent.ACTION_MAIN);
17266        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17267
17268        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17269                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17270                        | MATCH_DISABLED_COMPONENTS,
17271                UserHandle.myUserId());
17272        if (matches.size() == 1) {
17273            return matches.get(0).getComponentInfo().packageName;
17274        } else {
17275            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17276                    + ": matches=" + matches);
17277            return null;
17278        }
17279    }
17280
17281    @Override
17282    public void setApplicationEnabledSetting(String appPackageName,
17283            int newState, int flags, int userId, String callingPackage) {
17284        if (!sUserManager.exists(userId)) return;
17285        if (callingPackage == null) {
17286            callingPackage = Integer.toString(Binder.getCallingUid());
17287        }
17288        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17289    }
17290
17291    @Override
17292    public void setComponentEnabledSetting(ComponentName componentName,
17293            int newState, int flags, int userId) {
17294        if (!sUserManager.exists(userId)) return;
17295        setEnabledSetting(componentName.getPackageName(),
17296                componentName.getClassName(), newState, flags, userId, null);
17297    }
17298
17299    private void setEnabledSetting(final String packageName, String className, int newState,
17300            final int flags, int userId, String callingPackage) {
17301        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17302              || newState == COMPONENT_ENABLED_STATE_ENABLED
17303              || newState == COMPONENT_ENABLED_STATE_DISABLED
17304              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17305              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17306            throw new IllegalArgumentException("Invalid new component state: "
17307                    + newState);
17308        }
17309        PackageSetting pkgSetting;
17310        final int uid = Binder.getCallingUid();
17311        final int permission;
17312        if (uid == Process.SYSTEM_UID) {
17313            permission = PackageManager.PERMISSION_GRANTED;
17314        } else {
17315            permission = mContext.checkCallingOrSelfPermission(
17316                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17317        }
17318        enforceCrossUserPermission(uid, userId,
17319                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17320        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17321        boolean sendNow = false;
17322        boolean isApp = (className == null);
17323        String componentName = isApp ? packageName : className;
17324        int packageUid = -1;
17325        ArrayList<String> components;
17326
17327        // writer
17328        synchronized (mPackages) {
17329            pkgSetting = mSettings.mPackages.get(packageName);
17330            if (pkgSetting == null) {
17331                if (className == null) {
17332                    throw new IllegalArgumentException("Unknown package: " + packageName);
17333                }
17334                throw new IllegalArgumentException(
17335                        "Unknown component: " + packageName + "/" + className);
17336            }
17337            // Allow root and verify that userId is not being specified by a different user
17338            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17339                throw new SecurityException(
17340                        "Permission Denial: attempt to change component state from pid="
17341                        + Binder.getCallingPid()
17342                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17343            }
17344            if (className == null) {
17345                // We're dealing with an application/package level state change
17346                if (pkgSetting.getEnabled(userId) == newState) {
17347                    // Nothing to do
17348                    return;
17349                }
17350                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17351                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17352                    // Don't care about who enables an app.
17353                    callingPackage = null;
17354                }
17355                pkgSetting.setEnabled(newState, userId, callingPackage);
17356                // pkgSetting.pkg.mSetEnabled = newState;
17357            } else {
17358                // We're dealing with a component level state change
17359                // First, verify that this is a valid class name.
17360                PackageParser.Package pkg = pkgSetting.pkg;
17361                if (pkg == null || !pkg.hasComponentClassName(className)) {
17362                    if (pkg != null &&
17363                            pkg.applicationInfo.targetSdkVersion >=
17364                                    Build.VERSION_CODES.JELLY_BEAN) {
17365                        throw new IllegalArgumentException("Component class " + className
17366                                + " does not exist in " + packageName);
17367                    } else {
17368                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17369                                + className + " does not exist in " + packageName);
17370                    }
17371                }
17372                switch (newState) {
17373                case COMPONENT_ENABLED_STATE_ENABLED:
17374                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17375                        return;
17376                    }
17377                    break;
17378                case COMPONENT_ENABLED_STATE_DISABLED:
17379                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17380                        return;
17381                    }
17382                    break;
17383                case COMPONENT_ENABLED_STATE_DEFAULT:
17384                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17385                        return;
17386                    }
17387                    break;
17388                default:
17389                    Slog.e(TAG, "Invalid new component state: " + newState);
17390                    return;
17391                }
17392            }
17393            scheduleWritePackageRestrictionsLocked(userId);
17394            components = mPendingBroadcasts.get(userId, packageName);
17395            final boolean newPackage = components == null;
17396            if (newPackage) {
17397                components = new ArrayList<String>();
17398            }
17399            if (!components.contains(componentName)) {
17400                components.add(componentName);
17401            }
17402            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17403                sendNow = true;
17404                // Purge entry from pending broadcast list if another one exists already
17405                // since we are sending one right away.
17406                mPendingBroadcasts.remove(userId, packageName);
17407            } else {
17408                if (newPackage) {
17409                    mPendingBroadcasts.put(userId, packageName, components);
17410                }
17411                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17412                    // Schedule a message
17413                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17414                }
17415            }
17416        }
17417
17418        long callingId = Binder.clearCallingIdentity();
17419        try {
17420            if (sendNow) {
17421                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17422                sendPackageChangedBroadcast(packageName,
17423                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17424            }
17425        } finally {
17426            Binder.restoreCallingIdentity(callingId);
17427        }
17428    }
17429
17430    @Override
17431    public void flushPackageRestrictionsAsUser(int userId) {
17432        if (!sUserManager.exists(userId)) {
17433            return;
17434        }
17435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17436                false /* checkShell */, "flushPackageRestrictions");
17437        synchronized (mPackages) {
17438            mSettings.writePackageRestrictionsLPr(userId);
17439            mDirtyUsers.remove(userId);
17440            if (mDirtyUsers.isEmpty()) {
17441                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17442            }
17443        }
17444    }
17445
17446    private void sendPackageChangedBroadcast(String packageName,
17447            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17448        if (DEBUG_INSTALL)
17449            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17450                    + componentNames);
17451        Bundle extras = new Bundle(4);
17452        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17453        String nameList[] = new String[componentNames.size()];
17454        componentNames.toArray(nameList);
17455        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17456        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17457        extras.putInt(Intent.EXTRA_UID, packageUid);
17458        // If this is not reporting a change of the overall package, then only send it
17459        // to registered receivers.  We don't want to launch a swath of apps for every
17460        // little component state change.
17461        final int flags = !componentNames.contains(packageName)
17462                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17463        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17464                new int[] {UserHandle.getUserId(packageUid)});
17465    }
17466
17467    @Override
17468    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17469        if (!sUserManager.exists(userId)) return;
17470        final int uid = Binder.getCallingUid();
17471        final int permission = mContext.checkCallingOrSelfPermission(
17472                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17473        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17474        enforceCrossUserPermission(uid, userId,
17475                true /* requireFullPermission */, true /* checkShell */, "stop package");
17476        // writer
17477        synchronized (mPackages) {
17478            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17479                    allowedByPermission, uid, userId)) {
17480                scheduleWritePackageRestrictionsLocked(userId);
17481            }
17482        }
17483    }
17484
17485    @Override
17486    public String getInstallerPackageName(String packageName) {
17487        // reader
17488        synchronized (mPackages) {
17489            return mSettings.getInstallerPackageNameLPr(packageName);
17490        }
17491    }
17492
17493    @Override
17494    public int getApplicationEnabledSetting(String packageName, int userId) {
17495        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17496        int uid = Binder.getCallingUid();
17497        enforceCrossUserPermission(uid, userId,
17498                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17499        // reader
17500        synchronized (mPackages) {
17501            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17502        }
17503    }
17504
17505    @Override
17506    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17507        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17508        int uid = Binder.getCallingUid();
17509        enforceCrossUserPermission(uid, userId,
17510                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17511        // reader
17512        synchronized (mPackages) {
17513            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17514        }
17515    }
17516
17517    @Override
17518    public void enterSafeMode() {
17519        enforceSystemOrRoot("Only the system can request entering safe mode");
17520
17521        if (!mSystemReady) {
17522            mSafeMode = true;
17523        }
17524    }
17525
17526    @Override
17527    public void systemReady() {
17528        mSystemReady = true;
17529
17530        // Read the compatibilty setting when the system is ready.
17531        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17532                mContext.getContentResolver(),
17533                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17534        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17535        if (DEBUG_SETTINGS) {
17536            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17537        }
17538
17539        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17540
17541        synchronized (mPackages) {
17542            // Verify that all of the preferred activity components actually
17543            // exist.  It is possible for applications to be updated and at
17544            // that point remove a previously declared activity component that
17545            // had been set as a preferred activity.  We try to clean this up
17546            // the next time we encounter that preferred activity, but it is
17547            // possible for the user flow to never be able to return to that
17548            // situation so here we do a sanity check to make sure we haven't
17549            // left any junk around.
17550            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17551            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17552                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17553                removed.clear();
17554                for (PreferredActivity pa : pir.filterSet()) {
17555                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17556                        removed.add(pa);
17557                    }
17558                }
17559                if (removed.size() > 0) {
17560                    for (int r=0; r<removed.size(); r++) {
17561                        PreferredActivity pa = removed.get(r);
17562                        Slog.w(TAG, "Removing dangling preferred activity: "
17563                                + pa.mPref.mComponent);
17564                        pir.removeFilter(pa);
17565                    }
17566                    mSettings.writePackageRestrictionsLPr(
17567                            mSettings.mPreferredActivities.keyAt(i));
17568                }
17569            }
17570
17571            for (int userId : UserManagerService.getInstance().getUserIds()) {
17572                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17573                    grantPermissionsUserIds = ArrayUtils.appendInt(
17574                            grantPermissionsUserIds, userId);
17575                }
17576            }
17577        }
17578        sUserManager.systemReady();
17579
17580        // If we upgraded grant all default permissions before kicking off.
17581        for (int userId : grantPermissionsUserIds) {
17582            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17583        }
17584
17585        // Kick off any messages waiting for system ready
17586        if (mPostSystemReadyMessages != null) {
17587            for (Message msg : mPostSystemReadyMessages) {
17588                msg.sendToTarget();
17589            }
17590            mPostSystemReadyMessages = null;
17591        }
17592
17593        // Watch for external volumes that come and go over time
17594        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17595        storage.registerListener(mStorageListener);
17596
17597        mInstallerService.systemReady();
17598        mPackageDexOptimizer.systemReady();
17599
17600        MountServiceInternal mountServiceInternal = LocalServices.getService(
17601                MountServiceInternal.class);
17602        mountServiceInternal.addExternalStoragePolicy(
17603                new MountServiceInternal.ExternalStorageMountPolicy() {
17604            @Override
17605            public int getMountMode(int uid, String packageName) {
17606                if (Process.isIsolated(uid)) {
17607                    return Zygote.MOUNT_EXTERNAL_NONE;
17608                }
17609                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17610                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17611                }
17612                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17613                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17614                }
17615                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17616                    return Zygote.MOUNT_EXTERNAL_READ;
17617                }
17618                return Zygote.MOUNT_EXTERNAL_WRITE;
17619            }
17620
17621            @Override
17622            public boolean hasExternalStorage(int uid, String packageName) {
17623                return true;
17624            }
17625        });
17626
17627        // Now that we're mostly running, clean up stale users and apps
17628        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17629        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17630    }
17631
17632    @Override
17633    public boolean isSafeMode() {
17634        return mSafeMode;
17635    }
17636
17637    @Override
17638    public boolean hasSystemUidErrors() {
17639        return mHasSystemUidErrors;
17640    }
17641
17642    static String arrayToString(int[] array) {
17643        StringBuffer buf = new StringBuffer(128);
17644        buf.append('[');
17645        if (array != null) {
17646            for (int i=0; i<array.length; i++) {
17647                if (i > 0) buf.append(", ");
17648                buf.append(array[i]);
17649            }
17650        }
17651        buf.append(']');
17652        return buf.toString();
17653    }
17654
17655    static class DumpState {
17656        public static final int DUMP_LIBS = 1 << 0;
17657        public static final int DUMP_FEATURES = 1 << 1;
17658        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17659        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17660        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17661        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17662        public static final int DUMP_PERMISSIONS = 1 << 6;
17663        public static final int DUMP_PACKAGES = 1 << 7;
17664        public static final int DUMP_SHARED_USERS = 1 << 8;
17665        public static final int DUMP_MESSAGES = 1 << 9;
17666        public static final int DUMP_PROVIDERS = 1 << 10;
17667        public static final int DUMP_VERIFIERS = 1 << 11;
17668        public static final int DUMP_PREFERRED = 1 << 12;
17669        public static final int DUMP_PREFERRED_XML = 1 << 13;
17670        public static final int DUMP_KEYSETS = 1 << 14;
17671        public static final int DUMP_VERSION = 1 << 15;
17672        public static final int DUMP_INSTALLS = 1 << 16;
17673        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17674        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17675        public static final int DUMP_FROZEN = 1 << 19;
17676
17677        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17678
17679        private int mTypes;
17680
17681        private int mOptions;
17682
17683        private boolean mTitlePrinted;
17684
17685        private SharedUserSetting mSharedUser;
17686
17687        public boolean isDumping(int type) {
17688            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17689                return true;
17690            }
17691
17692            return (mTypes & type) != 0;
17693        }
17694
17695        public void setDump(int type) {
17696            mTypes |= type;
17697        }
17698
17699        public boolean isOptionEnabled(int option) {
17700            return (mOptions & option) != 0;
17701        }
17702
17703        public void setOptionEnabled(int option) {
17704            mOptions |= option;
17705        }
17706
17707        public boolean onTitlePrinted() {
17708            final boolean printed = mTitlePrinted;
17709            mTitlePrinted = true;
17710            return printed;
17711        }
17712
17713        public boolean getTitlePrinted() {
17714            return mTitlePrinted;
17715        }
17716
17717        public void setTitlePrinted(boolean enabled) {
17718            mTitlePrinted = enabled;
17719        }
17720
17721        public SharedUserSetting getSharedUser() {
17722            return mSharedUser;
17723        }
17724
17725        public void setSharedUser(SharedUserSetting user) {
17726            mSharedUser = user;
17727        }
17728    }
17729
17730    @Override
17731    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17732            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17733        (new PackageManagerShellCommand(this)).exec(
17734                this, in, out, err, args, resultReceiver);
17735    }
17736
17737    @Override
17738    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17739        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17740                != PackageManager.PERMISSION_GRANTED) {
17741            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17742                    + Binder.getCallingPid()
17743                    + ", uid=" + Binder.getCallingUid()
17744                    + " without permission "
17745                    + android.Manifest.permission.DUMP);
17746            return;
17747        }
17748
17749        DumpState dumpState = new DumpState();
17750        boolean fullPreferred = false;
17751        boolean checkin = false;
17752
17753        String packageName = null;
17754        ArraySet<String> permissionNames = null;
17755
17756        int opti = 0;
17757        while (opti < args.length) {
17758            String opt = args[opti];
17759            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17760                break;
17761            }
17762            opti++;
17763
17764            if ("-a".equals(opt)) {
17765                // Right now we only know how to print all.
17766            } else if ("-h".equals(opt)) {
17767                pw.println("Package manager dump options:");
17768                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17769                pw.println("    --checkin: dump for a checkin");
17770                pw.println("    -f: print details of intent filters");
17771                pw.println("    -h: print this help");
17772                pw.println("  cmd may be one of:");
17773                pw.println("    l[ibraries]: list known shared libraries");
17774                pw.println("    f[eatures]: list device features");
17775                pw.println("    k[eysets]: print known keysets");
17776                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17777                pw.println("    perm[issions]: dump permissions");
17778                pw.println("    permission [name ...]: dump declaration and use of given permission");
17779                pw.println("    pref[erred]: print preferred package settings");
17780                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17781                pw.println("    prov[iders]: dump content providers");
17782                pw.println("    p[ackages]: dump installed packages");
17783                pw.println("    s[hared-users]: dump shared user IDs");
17784                pw.println("    m[essages]: print collected runtime messages");
17785                pw.println("    v[erifiers]: print package verifier info");
17786                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17787                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17788                pw.println("    version: print database version info");
17789                pw.println("    write: write current settings now");
17790                pw.println("    installs: details about install sessions");
17791                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17792                pw.println("    <package.name>: info about given package");
17793                return;
17794            } else if ("--checkin".equals(opt)) {
17795                checkin = true;
17796            } else if ("-f".equals(opt)) {
17797                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17798            } else {
17799                pw.println("Unknown argument: " + opt + "; use -h for help");
17800            }
17801        }
17802
17803        // Is the caller requesting to dump a particular piece of data?
17804        if (opti < args.length) {
17805            String cmd = args[opti];
17806            opti++;
17807            // Is this a package name?
17808            if ("android".equals(cmd) || cmd.contains(".")) {
17809                packageName = cmd;
17810                // When dumping a single package, we always dump all of its
17811                // filter information since the amount of data will be reasonable.
17812                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17813            } else if ("check-permission".equals(cmd)) {
17814                if (opti >= args.length) {
17815                    pw.println("Error: check-permission missing permission argument");
17816                    return;
17817                }
17818                String perm = args[opti];
17819                opti++;
17820                if (opti >= args.length) {
17821                    pw.println("Error: check-permission missing package argument");
17822                    return;
17823                }
17824                String pkg = args[opti];
17825                opti++;
17826                int user = UserHandle.getUserId(Binder.getCallingUid());
17827                if (opti < args.length) {
17828                    try {
17829                        user = Integer.parseInt(args[opti]);
17830                    } catch (NumberFormatException e) {
17831                        pw.println("Error: check-permission user argument is not a number: "
17832                                + args[opti]);
17833                        return;
17834                    }
17835                }
17836                pw.println(checkPermission(perm, pkg, user));
17837                return;
17838            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17839                dumpState.setDump(DumpState.DUMP_LIBS);
17840            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17841                dumpState.setDump(DumpState.DUMP_FEATURES);
17842            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17843                if (opti >= args.length) {
17844                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17845                            | DumpState.DUMP_SERVICE_RESOLVERS
17846                            | DumpState.DUMP_RECEIVER_RESOLVERS
17847                            | DumpState.DUMP_CONTENT_RESOLVERS);
17848                } else {
17849                    while (opti < args.length) {
17850                        String name = args[opti];
17851                        if ("a".equals(name) || "activity".equals(name)) {
17852                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17853                        } else if ("s".equals(name) || "service".equals(name)) {
17854                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17855                        } else if ("r".equals(name) || "receiver".equals(name)) {
17856                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17857                        } else if ("c".equals(name) || "content".equals(name)) {
17858                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17859                        } else {
17860                            pw.println("Error: unknown resolver table type: " + name);
17861                            return;
17862                        }
17863                        opti++;
17864                    }
17865                }
17866            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17867                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17868            } else if ("permission".equals(cmd)) {
17869                if (opti >= args.length) {
17870                    pw.println("Error: permission requires permission name");
17871                    return;
17872                }
17873                permissionNames = new ArraySet<>();
17874                while (opti < args.length) {
17875                    permissionNames.add(args[opti]);
17876                    opti++;
17877                }
17878                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17879                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17880            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17881                dumpState.setDump(DumpState.DUMP_PREFERRED);
17882            } else if ("preferred-xml".equals(cmd)) {
17883                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17884                if (opti < args.length && "--full".equals(args[opti])) {
17885                    fullPreferred = true;
17886                    opti++;
17887                }
17888            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17889                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17890            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17891                dumpState.setDump(DumpState.DUMP_PACKAGES);
17892            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17893                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17894            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17895                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17896            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17897                dumpState.setDump(DumpState.DUMP_MESSAGES);
17898            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17899                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17900            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17901                    || "intent-filter-verifiers".equals(cmd)) {
17902                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17903            } else if ("version".equals(cmd)) {
17904                dumpState.setDump(DumpState.DUMP_VERSION);
17905            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17906                dumpState.setDump(DumpState.DUMP_KEYSETS);
17907            } else if ("installs".equals(cmd)) {
17908                dumpState.setDump(DumpState.DUMP_INSTALLS);
17909            } else if ("frozen".equals(cmd)) {
17910                dumpState.setDump(DumpState.DUMP_FROZEN);
17911            } else if ("write".equals(cmd)) {
17912                synchronized (mPackages) {
17913                    mSettings.writeLPr();
17914                    pw.println("Settings written.");
17915                    return;
17916                }
17917            }
17918        }
17919
17920        if (checkin) {
17921            pw.println("vers,1");
17922        }
17923
17924        // reader
17925        synchronized (mPackages) {
17926            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17927                if (!checkin) {
17928                    if (dumpState.onTitlePrinted())
17929                        pw.println();
17930                    pw.println("Database versions:");
17931                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17932                }
17933            }
17934
17935            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17936                if (!checkin) {
17937                    if (dumpState.onTitlePrinted())
17938                        pw.println();
17939                    pw.println("Verifiers:");
17940                    pw.print("  Required: ");
17941                    pw.print(mRequiredVerifierPackage);
17942                    pw.print(" (uid=");
17943                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17944                            UserHandle.USER_SYSTEM));
17945                    pw.println(")");
17946                } else if (mRequiredVerifierPackage != null) {
17947                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17948                    pw.print(",");
17949                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17950                            UserHandle.USER_SYSTEM));
17951                }
17952            }
17953
17954            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17955                    packageName == null) {
17956                if (mIntentFilterVerifierComponent != null) {
17957                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17958                    if (!checkin) {
17959                        if (dumpState.onTitlePrinted())
17960                            pw.println();
17961                        pw.println("Intent Filter Verifier:");
17962                        pw.print("  Using: ");
17963                        pw.print(verifierPackageName);
17964                        pw.print(" (uid=");
17965                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17966                                UserHandle.USER_SYSTEM));
17967                        pw.println(")");
17968                    } else if (verifierPackageName != null) {
17969                        pw.print("ifv,"); pw.print(verifierPackageName);
17970                        pw.print(",");
17971                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17972                                UserHandle.USER_SYSTEM));
17973                    }
17974                } else {
17975                    pw.println();
17976                    pw.println("No Intent Filter Verifier available!");
17977                }
17978            }
17979
17980            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17981                boolean printedHeader = false;
17982                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17983                while (it.hasNext()) {
17984                    String name = it.next();
17985                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17986                    if (!checkin) {
17987                        if (!printedHeader) {
17988                            if (dumpState.onTitlePrinted())
17989                                pw.println();
17990                            pw.println("Libraries:");
17991                            printedHeader = true;
17992                        }
17993                        pw.print("  ");
17994                    } else {
17995                        pw.print("lib,");
17996                    }
17997                    pw.print(name);
17998                    if (!checkin) {
17999                        pw.print(" -> ");
18000                    }
18001                    if (ent.path != null) {
18002                        if (!checkin) {
18003                            pw.print("(jar) ");
18004                            pw.print(ent.path);
18005                        } else {
18006                            pw.print(",jar,");
18007                            pw.print(ent.path);
18008                        }
18009                    } else {
18010                        if (!checkin) {
18011                            pw.print("(apk) ");
18012                            pw.print(ent.apk);
18013                        } else {
18014                            pw.print(",apk,");
18015                            pw.print(ent.apk);
18016                        }
18017                    }
18018                    pw.println();
18019                }
18020            }
18021
18022            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18023                if (dumpState.onTitlePrinted())
18024                    pw.println();
18025                if (!checkin) {
18026                    pw.println("Features:");
18027                }
18028
18029                for (FeatureInfo feat : mAvailableFeatures.values()) {
18030                    if (checkin) {
18031                        pw.print("feat,");
18032                        pw.print(feat.name);
18033                        pw.print(",");
18034                        pw.println(feat.version);
18035                    } else {
18036                        pw.print("  ");
18037                        pw.print(feat.name);
18038                        if (feat.version > 0) {
18039                            pw.print(" version=");
18040                            pw.print(feat.version);
18041                        }
18042                        pw.println();
18043                    }
18044                }
18045            }
18046
18047            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18048                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18049                        : "Activity Resolver Table:", "  ", packageName,
18050                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18051                    dumpState.setTitlePrinted(true);
18052                }
18053            }
18054            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18055                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18056                        : "Receiver Resolver Table:", "  ", packageName,
18057                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18058                    dumpState.setTitlePrinted(true);
18059                }
18060            }
18061            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18062                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18063                        : "Service Resolver Table:", "  ", packageName,
18064                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18065                    dumpState.setTitlePrinted(true);
18066                }
18067            }
18068            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18069                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18070                        : "Provider Resolver Table:", "  ", packageName,
18071                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18072                    dumpState.setTitlePrinted(true);
18073                }
18074            }
18075
18076            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18077                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18078                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18079                    int user = mSettings.mPreferredActivities.keyAt(i);
18080                    if (pir.dump(pw,
18081                            dumpState.getTitlePrinted()
18082                                ? "\nPreferred Activities User " + user + ":"
18083                                : "Preferred Activities User " + user + ":", "  ",
18084                            packageName, true, false)) {
18085                        dumpState.setTitlePrinted(true);
18086                    }
18087                }
18088            }
18089
18090            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18091                pw.flush();
18092                FileOutputStream fout = new FileOutputStream(fd);
18093                BufferedOutputStream str = new BufferedOutputStream(fout);
18094                XmlSerializer serializer = new FastXmlSerializer();
18095                try {
18096                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18097                    serializer.startDocument(null, true);
18098                    serializer.setFeature(
18099                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18100                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18101                    serializer.endDocument();
18102                    serializer.flush();
18103                } catch (IllegalArgumentException e) {
18104                    pw.println("Failed writing: " + e);
18105                } catch (IllegalStateException e) {
18106                    pw.println("Failed writing: " + e);
18107                } catch (IOException e) {
18108                    pw.println("Failed writing: " + e);
18109                }
18110            }
18111
18112            if (!checkin
18113                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18114                    && packageName == null) {
18115                pw.println();
18116                int count = mSettings.mPackages.size();
18117                if (count == 0) {
18118                    pw.println("No applications!");
18119                    pw.println();
18120                } else {
18121                    final String prefix = "  ";
18122                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18123                    if (allPackageSettings.size() == 0) {
18124                        pw.println("No domain preferred apps!");
18125                        pw.println();
18126                    } else {
18127                        pw.println("App verification status:");
18128                        pw.println();
18129                        count = 0;
18130                        for (PackageSetting ps : allPackageSettings) {
18131                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18132                            if (ivi == null || ivi.getPackageName() == null) continue;
18133                            pw.println(prefix + "Package: " + ivi.getPackageName());
18134                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18135                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18136                            pw.println();
18137                            count++;
18138                        }
18139                        if (count == 0) {
18140                            pw.println(prefix + "No app verification established.");
18141                            pw.println();
18142                        }
18143                        for (int userId : sUserManager.getUserIds()) {
18144                            pw.println("App linkages for user " + userId + ":");
18145                            pw.println();
18146                            count = 0;
18147                            for (PackageSetting ps : allPackageSettings) {
18148                                final long status = ps.getDomainVerificationStatusForUser(userId);
18149                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18150                                    continue;
18151                                }
18152                                pw.println(prefix + "Package: " + ps.name);
18153                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18154                                String statusStr = IntentFilterVerificationInfo.
18155                                        getStatusStringFromValue(status);
18156                                pw.println(prefix + "Status:  " + statusStr);
18157                                pw.println();
18158                                count++;
18159                            }
18160                            if (count == 0) {
18161                                pw.println(prefix + "No configured app linkages.");
18162                                pw.println();
18163                            }
18164                        }
18165                    }
18166                }
18167            }
18168
18169            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18170                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18171                if (packageName == null && permissionNames == null) {
18172                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18173                        if (iperm == 0) {
18174                            if (dumpState.onTitlePrinted())
18175                                pw.println();
18176                            pw.println("AppOp Permissions:");
18177                        }
18178                        pw.print("  AppOp Permission ");
18179                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18180                        pw.println(":");
18181                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18182                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18183                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18184                        }
18185                    }
18186                }
18187            }
18188
18189            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18190                boolean printedSomething = false;
18191                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18192                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18193                        continue;
18194                    }
18195                    if (!printedSomething) {
18196                        if (dumpState.onTitlePrinted())
18197                            pw.println();
18198                        pw.println("Registered ContentProviders:");
18199                        printedSomething = true;
18200                    }
18201                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18202                    pw.print("    "); pw.println(p.toString());
18203                }
18204                printedSomething = false;
18205                for (Map.Entry<String, PackageParser.Provider> entry :
18206                        mProvidersByAuthority.entrySet()) {
18207                    PackageParser.Provider p = entry.getValue();
18208                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18209                        continue;
18210                    }
18211                    if (!printedSomething) {
18212                        if (dumpState.onTitlePrinted())
18213                            pw.println();
18214                        pw.println("ContentProvider Authorities:");
18215                        printedSomething = true;
18216                    }
18217                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18218                    pw.print("    "); pw.println(p.toString());
18219                    if (p.info != null && p.info.applicationInfo != null) {
18220                        final String appInfo = p.info.applicationInfo.toString();
18221                        pw.print("      applicationInfo="); pw.println(appInfo);
18222                    }
18223                }
18224            }
18225
18226            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18227                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18228            }
18229
18230            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18231                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18232            }
18233
18234            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18235                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18236            }
18237
18238            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18239                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18240            }
18241
18242            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18243                // XXX should handle packageName != null by dumping only install data that
18244                // the given package is involved with.
18245                if (dumpState.onTitlePrinted()) pw.println();
18246                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18247            }
18248
18249            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18250                // XXX should handle packageName != null by dumping only install data that
18251                // the given package is involved with.
18252                if (dumpState.onTitlePrinted()) pw.println();
18253
18254                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18255                ipw.println();
18256                ipw.println("Frozen packages:");
18257                ipw.increaseIndent();
18258                if (mFrozenPackages.size() == 0) {
18259                    ipw.println("(none)");
18260                } else {
18261                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18262                        ipw.println(mFrozenPackages.valueAt(i));
18263                    }
18264                }
18265                ipw.decreaseIndent();
18266            }
18267
18268            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18269                if (dumpState.onTitlePrinted()) pw.println();
18270                mSettings.dumpReadMessagesLPr(pw, dumpState);
18271
18272                pw.println();
18273                pw.println("Package warning messages:");
18274                BufferedReader in = null;
18275                String line = null;
18276                try {
18277                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18278                    while ((line = in.readLine()) != null) {
18279                        if (line.contains("ignored: updated version")) continue;
18280                        pw.println(line);
18281                    }
18282                } catch (IOException ignored) {
18283                } finally {
18284                    IoUtils.closeQuietly(in);
18285                }
18286            }
18287
18288            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18289                BufferedReader in = null;
18290                String line = null;
18291                try {
18292                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18293                    while ((line = in.readLine()) != null) {
18294                        if (line.contains("ignored: updated version")) continue;
18295                        pw.print("msg,");
18296                        pw.println(line);
18297                    }
18298                } catch (IOException ignored) {
18299                } finally {
18300                    IoUtils.closeQuietly(in);
18301                }
18302            }
18303        }
18304    }
18305
18306    private String dumpDomainString(String packageName) {
18307        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18308                .getList();
18309        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18310
18311        ArraySet<String> result = new ArraySet<>();
18312        if (iviList.size() > 0) {
18313            for (IntentFilterVerificationInfo ivi : iviList) {
18314                for (String host : ivi.getDomains()) {
18315                    result.add(host);
18316                }
18317            }
18318        }
18319        if (filters != null && filters.size() > 0) {
18320            for (IntentFilter filter : filters) {
18321                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18322                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18323                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18324                    result.addAll(filter.getHostsList());
18325                }
18326            }
18327        }
18328
18329        StringBuilder sb = new StringBuilder(result.size() * 16);
18330        for (String domain : result) {
18331            if (sb.length() > 0) sb.append(" ");
18332            sb.append(domain);
18333        }
18334        return sb.toString();
18335    }
18336
18337    // ------- apps on sdcard specific code -------
18338    static final boolean DEBUG_SD_INSTALL = false;
18339
18340    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18341
18342    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18343
18344    private boolean mMediaMounted = false;
18345
18346    static String getEncryptKey() {
18347        try {
18348            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18349                    SD_ENCRYPTION_KEYSTORE_NAME);
18350            if (sdEncKey == null) {
18351                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18352                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18353                if (sdEncKey == null) {
18354                    Slog.e(TAG, "Failed to create encryption keys");
18355                    return null;
18356                }
18357            }
18358            return sdEncKey;
18359        } catch (NoSuchAlgorithmException nsae) {
18360            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18361            return null;
18362        } catch (IOException ioe) {
18363            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18364            return null;
18365        }
18366    }
18367
18368    /*
18369     * Update media status on PackageManager.
18370     */
18371    @Override
18372    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18373        int callingUid = Binder.getCallingUid();
18374        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18375            throw new SecurityException("Media status can only be updated by the system");
18376        }
18377        // reader; this apparently protects mMediaMounted, but should probably
18378        // be a different lock in that case.
18379        synchronized (mPackages) {
18380            Log.i(TAG, "Updating external media status from "
18381                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18382                    + (mediaStatus ? "mounted" : "unmounted"));
18383            if (DEBUG_SD_INSTALL)
18384                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18385                        + ", mMediaMounted=" + mMediaMounted);
18386            if (mediaStatus == mMediaMounted) {
18387                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18388                        : 0, -1);
18389                mHandler.sendMessage(msg);
18390                return;
18391            }
18392            mMediaMounted = mediaStatus;
18393        }
18394        // Queue up an async operation since the package installation may take a
18395        // little while.
18396        mHandler.post(new Runnable() {
18397            public void run() {
18398                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18399            }
18400        });
18401    }
18402
18403    /**
18404     * Called by MountService when the initial ASECs to scan are available.
18405     * Should block until all the ASEC containers are finished being scanned.
18406     */
18407    public void scanAvailableAsecs() {
18408        updateExternalMediaStatusInner(true, false, false);
18409    }
18410
18411    /*
18412     * Collect information of applications on external media, map them against
18413     * existing containers and update information based on current mount status.
18414     * Please note that we always have to report status if reportStatus has been
18415     * set to true especially when unloading packages.
18416     */
18417    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18418            boolean externalStorage) {
18419        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18420        int[] uidArr = EmptyArray.INT;
18421
18422        final String[] list = PackageHelper.getSecureContainerList();
18423        if (ArrayUtils.isEmpty(list)) {
18424            Log.i(TAG, "No secure containers found");
18425        } else {
18426            // Process list of secure containers and categorize them
18427            // as active or stale based on their package internal state.
18428
18429            // reader
18430            synchronized (mPackages) {
18431                for (String cid : list) {
18432                    // Leave stages untouched for now; installer service owns them
18433                    if (PackageInstallerService.isStageName(cid)) continue;
18434
18435                    if (DEBUG_SD_INSTALL)
18436                        Log.i(TAG, "Processing container " + cid);
18437                    String pkgName = getAsecPackageName(cid);
18438                    if (pkgName == null) {
18439                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18440                        continue;
18441                    }
18442                    if (DEBUG_SD_INSTALL)
18443                        Log.i(TAG, "Looking for pkg : " + pkgName);
18444
18445                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18446                    if (ps == null) {
18447                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18448                        continue;
18449                    }
18450
18451                    /*
18452                     * Skip packages that are not external if we're unmounting
18453                     * external storage.
18454                     */
18455                    if (externalStorage && !isMounted && !isExternal(ps)) {
18456                        continue;
18457                    }
18458
18459                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18460                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18461                    // The package status is changed only if the code path
18462                    // matches between settings and the container id.
18463                    if (ps.codePathString != null
18464                            && ps.codePathString.startsWith(args.getCodePath())) {
18465                        if (DEBUG_SD_INSTALL) {
18466                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18467                                    + " at code path: " + ps.codePathString);
18468                        }
18469
18470                        // We do have a valid package installed on sdcard
18471                        processCids.put(args, ps.codePathString);
18472                        final int uid = ps.appId;
18473                        if (uid != -1) {
18474                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18475                        }
18476                    } else {
18477                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18478                                + ps.codePathString);
18479                    }
18480                }
18481            }
18482
18483            Arrays.sort(uidArr);
18484        }
18485
18486        // Process packages with valid entries.
18487        if (isMounted) {
18488            if (DEBUG_SD_INSTALL)
18489                Log.i(TAG, "Loading packages");
18490            loadMediaPackages(processCids, uidArr, externalStorage);
18491            startCleaningPackages();
18492            mInstallerService.onSecureContainersAvailable();
18493        } else {
18494            if (DEBUG_SD_INSTALL)
18495                Log.i(TAG, "Unloading packages");
18496            unloadMediaPackages(processCids, uidArr, reportStatus);
18497        }
18498    }
18499
18500    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18501            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18502        final int size = infos.size();
18503        final String[] packageNames = new String[size];
18504        final int[] packageUids = new int[size];
18505        for (int i = 0; i < size; i++) {
18506            final ApplicationInfo info = infos.get(i);
18507            packageNames[i] = info.packageName;
18508            packageUids[i] = info.uid;
18509        }
18510        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18511                finishedReceiver);
18512    }
18513
18514    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18515            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18516        sendResourcesChangedBroadcast(mediaStatus, replacing,
18517                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18518    }
18519
18520    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18521            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18522        int size = pkgList.length;
18523        if (size > 0) {
18524            // Send broadcasts here
18525            Bundle extras = new Bundle();
18526            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18527            if (uidArr != null) {
18528                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18529            }
18530            if (replacing) {
18531                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18532            }
18533            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18534                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18535            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18536        }
18537    }
18538
18539   /*
18540     * Look at potentially valid container ids from processCids If package
18541     * information doesn't match the one on record or package scanning fails,
18542     * the cid is added to list of removeCids. We currently don't delete stale
18543     * containers.
18544     */
18545    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18546            boolean externalStorage) {
18547        ArrayList<String> pkgList = new ArrayList<String>();
18548        Set<AsecInstallArgs> keys = processCids.keySet();
18549
18550        for (AsecInstallArgs args : keys) {
18551            String codePath = processCids.get(args);
18552            if (DEBUG_SD_INSTALL)
18553                Log.i(TAG, "Loading container : " + args.cid);
18554            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18555            try {
18556                // Make sure there are no container errors first.
18557                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18558                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18559                            + " when installing from sdcard");
18560                    continue;
18561                }
18562                // Check code path here.
18563                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18564                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18565                            + " does not match one in settings " + codePath);
18566                    continue;
18567                }
18568                // Parse package
18569                int parseFlags = mDefParseFlags;
18570                if (args.isExternalAsec()) {
18571                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18572                }
18573                if (args.isFwdLocked()) {
18574                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18575                }
18576
18577                synchronized (mInstallLock) {
18578                    PackageParser.Package pkg = null;
18579                    try {
18580                        // Sadly we don't know the package name yet to freeze it
18581                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18582                                SCAN_IGNORE_FROZEN, 0, null);
18583                    } catch (PackageManagerException e) {
18584                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18585                    }
18586                    // Scan the package
18587                    if (pkg != null) {
18588                        /*
18589                         * TODO why is the lock being held? doPostInstall is
18590                         * called in other places without the lock. This needs
18591                         * to be straightened out.
18592                         */
18593                        // writer
18594                        synchronized (mPackages) {
18595                            retCode = PackageManager.INSTALL_SUCCEEDED;
18596                            pkgList.add(pkg.packageName);
18597                            // Post process args
18598                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18599                                    pkg.applicationInfo.uid);
18600                        }
18601                    } else {
18602                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18603                    }
18604                }
18605
18606            } finally {
18607                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18608                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18609                }
18610            }
18611        }
18612        // writer
18613        synchronized (mPackages) {
18614            // If the platform SDK has changed since the last time we booted,
18615            // we need to re-grant app permission to catch any new ones that
18616            // appear. This is really a hack, and means that apps can in some
18617            // cases get permissions that the user didn't initially explicitly
18618            // allow... it would be nice to have some better way to handle
18619            // this situation.
18620            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18621                    : mSettings.getInternalVersion();
18622            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18623                    : StorageManager.UUID_PRIVATE_INTERNAL;
18624
18625            int updateFlags = UPDATE_PERMISSIONS_ALL;
18626            if (ver.sdkVersion != mSdkVersion) {
18627                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18628                        + mSdkVersion + "; regranting permissions for external");
18629                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18630            }
18631            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18632
18633            // Yay, everything is now upgraded
18634            ver.forceCurrent();
18635
18636            // can downgrade to reader
18637            // Persist settings
18638            mSettings.writeLPr();
18639        }
18640        // Send a broadcast to let everyone know we are done processing
18641        if (pkgList.size() > 0) {
18642            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18643        }
18644    }
18645
18646   /*
18647     * Utility method to unload a list of specified containers
18648     */
18649    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18650        // Just unmount all valid containers.
18651        for (AsecInstallArgs arg : cidArgs) {
18652            synchronized (mInstallLock) {
18653                arg.doPostDeleteLI(false);
18654           }
18655       }
18656   }
18657
18658    /*
18659     * Unload packages mounted on external media. This involves deleting package
18660     * data from internal structures, sending broadcasts about disabled packages,
18661     * gc'ing to free up references, unmounting all secure containers
18662     * corresponding to packages on external media, and posting a
18663     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18664     * that we always have to post this message if status has been requested no
18665     * matter what.
18666     */
18667    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18668            final boolean reportStatus) {
18669        if (DEBUG_SD_INSTALL)
18670            Log.i(TAG, "unloading media packages");
18671        ArrayList<String> pkgList = new ArrayList<String>();
18672        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18673        final Set<AsecInstallArgs> keys = processCids.keySet();
18674        for (AsecInstallArgs args : keys) {
18675            String pkgName = args.getPackageName();
18676            if (DEBUG_SD_INSTALL)
18677                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18678            // Delete package internally
18679            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18680            synchronized (mInstallLock) {
18681                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18682                final boolean res;
18683                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18684                        "unloadMediaPackages")) {
18685                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18686                            null);
18687                }
18688                if (res) {
18689                    pkgList.add(pkgName);
18690                } else {
18691                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18692                    failedList.add(args);
18693                }
18694            }
18695        }
18696
18697        // reader
18698        synchronized (mPackages) {
18699            // We didn't update the settings after removing each package;
18700            // write them now for all packages.
18701            mSettings.writeLPr();
18702        }
18703
18704        // We have to absolutely send UPDATED_MEDIA_STATUS only
18705        // after confirming that all the receivers processed the ordered
18706        // broadcast when packages get disabled, force a gc to clean things up.
18707        // and unload all the containers.
18708        if (pkgList.size() > 0) {
18709            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18710                    new IIntentReceiver.Stub() {
18711                public void performReceive(Intent intent, int resultCode, String data,
18712                        Bundle extras, boolean ordered, boolean sticky,
18713                        int sendingUser) throws RemoteException {
18714                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18715                            reportStatus ? 1 : 0, 1, keys);
18716                    mHandler.sendMessage(msg);
18717                }
18718            });
18719        } else {
18720            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18721                    keys);
18722            mHandler.sendMessage(msg);
18723        }
18724    }
18725
18726    private void loadPrivatePackages(final VolumeInfo vol) {
18727        mHandler.post(new Runnable() {
18728            @Override
18729            public void run() {
18730                loadPrivatePackagesInner(vol);
18731            }
18732        });
18733    }
18734
18735    private void loadPrivatePackagesInner(VolumeInfo vol) {
18736        final String volumeUuid = vol.fsUuid;
18737        if (TextUtils.isEmpty(volumeUuid)) {
18738            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18739            return;
18740        }
18741
18742        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18743        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18744        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18745
18746        final VersionInfo ver;
18747        final List<PackageSetting> packages;
18748        synchronized (mPackages) {
18749            ver = mSettings.findOrCreateVersion(volumeUuid);
18750            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18751        }
18752
18753        for (PackageSetting ps : packages) {
18754            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18755            synchronized (mInstallLock) {
18756                final PackageParser.Package pkg;
18757                try {
18758                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18759                    loaded.add(pkg.applicationInfo);
18760
18761                } catch (PackageManagerException e) {
18762                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18763                }
18764
18765                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18766                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18767                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18768                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18769                }
18770            }
18771        }
18772
18773        // Reconcile app data for all started/unlocked users
18774        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18775        final UserManager um = mContext.getSystemService(UserManager.class);
18776        for (UserInfo user : um.getUsers()) {
18777            final int flags;
18778            if (um.isUserUnlockingOrUnlocked(user.id)) {
18779                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18780            } else if (um.isUserRunning(user.id)) {
18781                flags = StorageManager.FLAG_STORAGE_DE;
18782            } else {
18783                continue;
18784            }
18785
18786            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18787            synchronized (mInstallLock) {
18788                reconcileAppsDataLI(volumeUuid, user.id, flags);
18789            }
18790        }
18791
18792        synchronized (mPackages) {
18793            int updateFlags = UPDATE_PERMISSIONS_ALL;
18794            if (ver.sdkVersion != mSdkVersion) {
18795                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18796                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18797                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18798            }
18799            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18800
18801            // Yay, everything is now upgraded
18802            ver.forceCurrent();
18803
18804            mSettings.writeLPr();
18805        }
18806
18807        for (PackageFreezer freezer : freezers) {
18808            freezer.close();
18809        }
18810
18811        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18812        sendResourcesChangedBroadcast(true, false, loaded, null);
18813    }
18814
18815    private void unloadPrivatePackages(final VolumeInfo vol) {
18816        mHandler.post(new Runnable() {
18817            @Override
18818            public void run() {
18819                unloadPrivatePackagesInner(vol);
18820            }
18821        });
18822    }
18823
18824    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18825        final String volumeUuid = vol.fsUuid;
18826        if (TextUtils.isEmpty(volumeUuid)) {
18827            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18828            return;
18829        }
18830
18831        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18832        synchronized (mInstallLock) {
18833        synchronized (mPackages) {
18834            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18835            for (PackageSetting ps : packages) {
18836                if (ps.pkg == null) continue;
18837
18838                final ApplicationInfo info = ps.pkg.applicationInfo;
18839                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18840                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18841
18842                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18843                        "unloadPrivatePackagesInner")) {
18844                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18845                            false, null)) {
18846                        unloaded.add(info);
18847                    } else {
18848                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18849                    }
18850                }
18851            }
18852
18853            mSettings.writeLPr();
18854        }
18855        }
18856
18857        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18858        sendResourcesChangedBroadcast(false, false, unloaded, null);
18859    }
18860
18861    /**
18862     * Prepare storage areas for given user on all mounted devices.
18863     */
18864    void prepareUserData(int userId, int userSerial, int flags) {
18865        synchronized (mInstallLock) {
18866            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18867            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18868                final String volumeUuid = vol.getFsUuid();
18869                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18870            }
18871        }
18872    }
18873
18874    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18875            boolean allowRecover) {
18876        // Prepare storage and verify that serial numbers are consistent; if
18877        // there's a mismatch we need to destroy to avoid leaking data
18878        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18879        try {
18880            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18881
18882            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18883                UserManagerService.enforceSerialNumber(
18884                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18885            }
18886            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18887                UserManagerService.enforceSerialNumber(
18888                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18889            }
18890
18891            synchronized (mInstallLock) {
18892                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18893            }
18894        } catch (Exception e) {
18895            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18896                    + " because we failed to prepare: " + e);
18897            destroyUserDataLI(volumeUuid, userId,
18898                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18899
18900            if (allowRecover) {
18901                // Try one last time; if we fail again we're really in trouble
18902                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18903            }
18904        }
18905    }
18906
18907    /**
18908     * Destroy storage areas for given user on all mounted devices.
18909     */
18910    void destroyUserData(int userId, int flags) {
18911        synchronized (mInstallLock) {
18912            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18913            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18914                final String volumeUuid = vol.getFsUuid();
18915                destroyUserDataLI(volumeUuid, userId, flags);
18916            }
18917        }
18918    }
18919
18920    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18921        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18922        try {
18923            // Clean up app data, profile data, and media data
18924            mInstaller.destroyUserData(volumeUuid, userId, flags);
18925
18926            // Clean up system data
18927            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18928                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18929                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18930                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18931                }
18932                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18933                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18934                }
18935            }
18936
18937            // Data with special labels is now gone, so finish the job
18938            storage.destroyUserStorage(volumeUuid, userId, flags);
18939
18940        } catch (Exception e) {
18941            logCriticalInfo(Log.WARN,
18942                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18943        }
18944    }
18945
18946    /**
18947     * Examine all users present on given mounted volume, and destroy data
18948     * belonging to users that are no longer valid, or whose user ID has been
18949     * recycled.
18950     */
18951    private void reconcileUsers(String volumeUuid) {
18952        final List<File> files = new ArrayList<>();
18953        Collections.addAll(files, FileUtils
18954                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18955        Collections.addAll(files, FileUtils
18956                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18957        for (File file : files) {
18958            if (!file.isDirectory()) continue;
18959
18960            final int userId;
18961            final UserInfo info;
18962            try {
18963                userId = Integer.parseInt(file.getName());
18964                info = sUserManager.getUserInfo(userId);
18965            } catch (NumberFormatException e) {
18966                Slog.w(TAG, "Invalid user directory " + file);
18967                continue;
18968            }
18969
18970            boolean destroyUser = false;
18971            if (info == null) {
18972                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18973                        + " because no matching user was found");
18974                destroyUser = true;
18975            } else if (!mOnlyCore) {
18976                try {
18977                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18978                } catch (IOException e) {
18979                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18980                            + " because we failed to enforce serial number: " + e);
18981                    destroyUser = true;
18982                }
18983            }
18984
18985            if (destroyUser) {
18986                synchronized (mInstallLock) {
18987                    destroyUserDataLI(volumeUuid, userId,
18988                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18989                }
18990            }
18991        }
18992    }
18993
18994    private void assertPackageKnown(String volumeUuid, String packageName)
18995            throws PackageManagerException {
18996        synchronized (mPackages) {
18997            final PackageSetting ps = mSettings.mPackages.get(packageName);
18998            if (ps == null) {
18999                throw new PackageManagerException("Package " + packageName + " is unknown");
19000            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19001                throw new PackageManagerException(
19002                        "Package " + packageName + " found on unknown volume " + volumeUuid
19003                                + "; expected volume " + ps.volumeUuid);
19004            }
19005        }
19006    }
19007
19008    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19009            throws PackageManagerException {
19010        synchronized (mPackages) {
19011            final PackageSetting ps = mSettings.mPackages.get(packageName);
19012            if (ps == null) {
19013                throw new PackageManagerException("Package " + packageName + " is unknown");
19014            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19015                throw new PackageManagerException(
19016                        "Package " + packageName + " found on unknown volume " + volumeUuid
19017                                + "; expected volume " + ps.volumeUuid);
19018            } else if (!ps.getInstalled(userId)) {
19019                throw new PackageManagerException(
19020                        "Package " + packageName + " not installed for user " + userId);
19021            }
19022        }
19023    }
19024
19025    /**
19026     * Examine all apps present on given mounted volume, and destroy apps that
19027     * aren't expected, either due to uninstallation or reinstallation on
19028     * another volume.
19029     */
19030    private void reconcileApps(String volumeUuid) {
19031        final File[] files = FileUtils
19032                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19033        for (File file : files) {
19034            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19035                    && !PackageInstallerService.isStageName(file.getName());
19036            if (!isPackage) {
19037                // Ignore entries which are not packages
19038                continue;
19039            }
19040
19041            try {
19042                final PackageLite pkg = PackageParser.parsePackageLite(file,
19043                        PackageParser.PARSE_MUST_BE_APK);
19044                assertPackageKnown(volumeUuid, pkg.packageName);
19045
19046            } catch (PackageParserException | PackageManagerException e) {
19047                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19048                synchronized (mInstallLock) {
19049                    removeCodePathLI(file);
19050                }
19051            }
19052        }
19053    }
19054
19055    /**
19056     * Reconcile all app data for the given user.
19057     * <p>
19058     * Verifies that directories exist and that ownership and labeling is
19059     * correct for all installed apps on all mounted volumes.
19060     */
19061    void reconcileAppsData(int userId, int flags) {
19062        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19063        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19064            final String volumeUuid = vol.getFsUuid();
19065            synchronized (mInstallLock) {
19066                reconcileAppsDataLI(volumeUuid, userId, flags);
19067            }
19068        }
19069    }
19070
19071    /**
19072     * Reconcile all app data on given mounted volume.
19073     * <p>
19074     * Destroys app data that isn't expected, either due to uninstallation or
19075     * reinstallation on another volume.
19076     * <p>
19077     * Verifies that directories exist and that ownership and labeling is
19078     * correct for all installed apps.
19079     */
19080    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19081        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19082                + Integer.toHexString(flags));
19083
19084        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19085        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19086
19087        boolean restoreconNeeded = false;
19088
19089        // First look for stale data that doesn't belong, and check if things
19090        // have changed since we did our last restorecon
19091        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19092            if (!StorageManager.isUserKeyUnlocked(userId)) {
19093                throw new RuntimeException(
19094                        "Yikes, someone asked us to reconcile CE storage while " + userId
19095                                + " was still locked; this would have caused massive data loss!");
19096            }
19097
19098            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19099
19100            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19101            for (File file : files) {
19102                final String packageName = file.getName();
19103                try {
19104                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19105                } catch (PackageManagerException e) {
19106                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19107                    try {
19108                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19109                                StorageManager.FLAG_STORAGE_CE, 0);
19110                    } catch (InstallerException e2) {
19111                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19112                    }
19113                }
19114            }
19115        }
19116        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19117            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19118
19119            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19120            for (File file : files) {
19121                final String packageName = file.getName();
19122                try {
19123                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19124                } catch (PackageManagerException e) {
19125                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19126                    try {
19127                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19128                                StorageManager.FLAG_STORAGE_DE, 0);
19129                    } catch (InstallerException e2) {
19130                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19131                    }
19132                }
19133            }
19134        }
19135
19136        // Ensure that data directories are ready to roll for all packages
19137        // installed for this volume and user
19138        final List<PackageSetting> packages;
19139        synchronized (mPackages) {
19140            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19141        }
19142        int preparedCount = 0;
19143        for (PackageSetting ps : packages) {
19144            final String packageName = ps.name;
19145            if (ps.pkg == null) {
19146                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19147                // TODO: might be due to legacy ASEC apps; we should circle back
19148                // and reconcile again once they're scanned
19149                continue;
19150            }
19151
19152            if (ps.getInstalled(userId)) {
19153                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19154
19155                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19156                    // We may have just shuffled around app data directories, so
19157                    // prepare them one more time
19158                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19159                }
19160
19161                preparedCount++;
19162            }
19163        }
19164
19165        if (restoreconNeeded) {
19166            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19167                SELinuxMMAC.setRestoreconDone(ceDir);
19168            }
19169            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19170                SELinuxMMAC.setRestoreconDone(deDir);
19171            }
19172        }
19173
19174        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19175                + " packages; restoreconNeeded was " + restoreconNeeded);
19176    }
19177
19178    /**
19179     * Prepare app data for the given app just after it was installed or
19180     * upgraded. This method carefully only touches users that it's installed
19181     * for, and it forces a restorecon to handle any seinfo changes.
19182     * <p>
19183     * Verifies that directories exist and that ownership and labeling is
19184     * correct for all installed apps. If there is an ownership mismatch, it
19185     * will try recovering system apps by wiping data; third-party app data is
19186     * left intact.
19187     * <p>
19188     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19189     */
19190    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19191        final PackageSetting ps;
19192        synchronized (mPackages) {
19193            ps = mSettings.mPackages.get(pkg.packageName);
19194            mSettings.writeKernelMappingLPr(ps);
19195        }
19196
19197        final UserManager um = mContext.getSystemService(UserManager.class);
19198        for (UserInfo user : um.getUsers()) {
19199            final int flags;
19200            if (um.isUserUnlockingOrUnlocked(user.id)) {
19201                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19202            } else if (um.isUserRunning(user.id)) {
19203                flags = StorageManager.FLAG_STORAGE_DE;
19204            } else {
19205                continue;
19206            }
19207
19208            if (ps.getInstalled(user.id)) {
19209                // Whenever an app changes, force a restorecon of its data
19210                // TODO: when user data is locked, mark that we're still dirty
19211                prepareAppDataLIF(pkg, user.id, flags, true);
19212            }
19213        }
19214    }
19215
19216    /**
19217     * Prepare app data for the given app.
19218     * <p>
19219     * Verifies that directories exist and that ownership and labeling is
19220     * correct for all installed apps. If there is an ownership mismatch, this
19221     * will try recovering system apps by wiping data; third-party app data is
19222     * left intact.
19223     */
19224    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19225            boolean restoreconNeeded) {
19226        if (pkg == null) {
19227            Slog.wtf(TAG, "Package was null!", new Throwable());
19228            return;
19229        }
19230        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19231        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19232        for (int i = 0; i < childCount; i++) {
19233            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19234        }
19235    }
19236
19237    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19238            boolean restoreconNeeded) {
19239        if (DEBUG_APP_DATA) {
19240            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19241                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19242        }
19243
19244        final String volumeUuid = pkg.volumeUuid;
19245        final String packageName = pkg.packageName;
19246        final ApplicationInfo app = pkg.applicationInfo;
19247        final int appId = UserHandle.getAppId(app.uid);
19248
19249        Preconditions.checkNotNull(app.seinfo);
19250
19251        try {
19252            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19253                    appId, app.seinfo, app.targetSdkVersion);
19254        } catch (InstallerException e) {
19255            if (app.isSystemApp()) {
19256                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19257                        + ", but trying to recover: " + e);
19258                destroyAppDataLeafLIF(pkg, userId, flags);
19259                try {
19260                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19261                            appId, app.seinfo, app.targetSdkVersion);
19262                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19263                } catch (InstallerException e2) {
19264                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19265                }
19266            } else {
19267                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19268            }
19269        }
19270
19271        if (restoreconNeeded) {
19272            try {
19273                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19274                        app.seinfo);
19275            } catch (InstallerException e) {
19276                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19277            }
19278        }
19279
19280        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19281            try {
19282                // CE storage is unlocked right now, so read out the inode and
19283                // remember for use later when it's locked
19284                // TODO: mark this structure as dirty so we persist it!
19285                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19286                        StorageManager.FLAG_STORAGE_CE);
19287                synchronized (mPackages) {
19288                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19289                    if (ps != null) {
19290                        ps.setCeDataInode(ceDataInode, userId);
19291                    }
19292                }
19293            } catch (InstallerException e) {
19294                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19295            }
19296        }
19297
19298        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19299    }
19300
19301    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19302        if (pkg == null) {
19303            Slog.wtf(TAG, "Package was null!", new Throwable());
19304            return;
19305        }
19306        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19307        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19308        for (int i = 0; i < childCount; i++) {
19309            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19310        }
19311    }
19312
19313    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19314        final String volumeUuid = pkg.volumeUuid;
19315        final String packageName = pkg.packageName;
19316        final ApplicationInfo app = pkg.applicationInfo;
19317
19318        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19319            // Create a native library symlink only if we have native libraries
19320            // and if the native libraries are 32 bit libraries. We do not provide
19321            // this symlink for 64 bit libraries.
19322            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19323                final String nativeLibPath = app.nativeLibraryDir;
19324                try {
19325                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19326                            nativeLibPath, userId);
19327                } catch (InstallerException e) {
19328                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19329                }
19330            }
19331        }
19332    }
19333
19334    /**
19335     * For system apps on non-FBE devices, this method migrates any existing
19336     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19337     * requested by the app.
19338     */
19339    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19340        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19341                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19342            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19343                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19344            try {
19345                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19346                        storageTarget);
19347            } catch (InstallerException e) {
19348                logCriticalInfo(Log.WARN,
19349                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19350            }
19351            return true;
19352        } else {
19353            return false;
19354        }
19355    }
19356
19357    public PackageFreezer freezePackage(String packageName, String killReason) {
19358        return new PackageFreezer(packageName, killReason);
19359    }
19360
19361    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19362            String killReason) {
19363        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19364            return new PackageFreezer();
19365        } else {
19366            return freezePackage(packageName, killReason);
19367        }
19368    }
19369
19370    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19371            String killReason) {
19372        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19373            return new PackageFreezer();
19374        } else {
19375            return freezePackage(packageName, killReason);
19376        }
19377    }
19378
19379    /**
19380     * Class that freezes and kills the given package upon creation, and
19381     * unfreezes it upon closing. This is typically used when doing surgery on
19382     * app code/data to prevent the app from running while you're working.
19383     */
19384    private class PackageFreezer implements AutoCloseable {
19385        private final String mPackageName;
19386        private final PackageFreezer[] mChildren;
19387
19388        private final boolean mWeFroze;
19389
19390        private final AtomicBoolean mClosed = new AtomicBoolean();
19391        private final CloseGuard mCloseGuard = CloseGuard.get();
19392
19393        /**
19394         * Create and return a stub freezer that doesn't actually do anything,
19395         * typically used when someone requested
19396         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19397         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19398         */
19399        public PackageFreezer() {
19400            mPackageName = null;
19401            mChildren = null;
19402            mWeFroze = false;
19403            mCloseGuard.open("close");
19404        }
19405
19406        public PackageFreezer(String packageName, String killReason) {
19407            synchronized (mPackages) {
19408                mPackageName = packageName;
19409                mWeFroze = mFrozenPackages.add(mPackageName);
19410
19411                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19412                if (ps != null) {
19413                    killApplication(ps.name, ps.appId, killReason);
19414                }
19415
19416                final PackageParser.Package p = mPackages.get(packageName);
19417                if (p != null && p.childPackages != null) {
19418                    final int N = p.childPackages.size();
19419                    mChildren = new PackageFreezer[N];
19420                    for (int i = 0; i < N; i++) {
19421                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19422                                killReason);
19423                    }
19424                } else {
19425                    mChildren = null;
19426                }
19427            }
19428            mCloseGuard.open("close");
19429        }
19430
19431        @Override
19432        protected void finalize() throws Throwable {
19433            try {
19434                mCloseGuard.warnIfOpen();
19435                close();
19436            } finally {
19437                super.finalize();
19438            }
19439        }
19440
19441        @Override
19442        public void close() {
19443            mCloseGuard.close();
19444            if (mClosed.compareAndSet(false, true)) {
19445                synchronized (mPackages) {
19446                    if (mWeFroze) {
19447                        mFrozenPackages.remove(mPackageName);
19448                    }
19449
19450                    if (mChildren != null) {
19451                        for (PackageFreezer freezer : mChildren) {
19452                            freezer.close();
19453                        }
19454                    }
19455                }
19456            }
19457        }
19458    }
19459
19460    /**
19461     * Verify that given package is currently frozen.
19462     */
19463    private void checkPackageFrozen(String packageName) {
19464        synchronized (mPackages) {
19465            if (!mFrozenPackages.contains(packageName)) {
19466                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19467            }
19468        }
19469    }
19470
19471    @Override
19472    public int movePackage(final String packageName, final String volumeUuid) {
19473        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19474
19475        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19476        final int moveId = mNextMoveId.getAndIncrement();
19477        mHandler.post(new Runnable() {
19478            @Override
19479            public void run() {
19480                try {
19481                    movePackageInternal(packageName, volumeUuid, moveId, user);
19482                } catch (PackageManagerException e) {
19483                    Slog.w(TAG, "Failed to move " + packageName, e);
19484                    mMoveCallbacks.notifyStatusChanged(moveId,
19485                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19486                }
19487            }
19488        });
19489        return moveId;
19490    }
19491
19492    private void movePackageInternal(final String packageName, final String volumeUuid,
19493            final int moveId, UserHandle user) throws PackageManagerException {
19494        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19495        final PackageManager pm = mContext.getPackageManager();
19496
19497        final boolean currentAsec;
19498        final String currentVolumeUuid;
19499        final File codeFile;
19500        final String installerPackageName;
19501        final String packageAbiOverride;
19502        final int appId;
19503        final String seinfo;
19504        final String label;
19505        final int targetSdkVersion;
19506        final PackageFreezer freezer;
19507
19508        // reader
19509        synchronized (mPackages) {
19510            final PackageParser.Package pkg = mPackages.get(packageName);
19511            final PackageSetting ps = mSettings.mPackages.get(packageName);
19512            if (pkg == null || ps == null) {
19513                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19514            }
19515
19516            if (pkg.applicationInfo.isSystemApp()) {
19517                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19518                        "Cannot move system application");
19519            }
19520
19521            if (pkg.applicationInfo.isExternalAsec()) {
19522                currentAsec = true;
19523                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19524            } else if (pkg.applicationInfo.isForwardLocked()) {
19525                currentAsec = true;
19526                currentVolumeUuid = "forward_locked";
19527            } else {
19528                currentAsec = false;
19529                currentVolumeUuid = ps.volumeUuid;
19530
19531                final File probe = new File(pkg.codePath);
19532                final File probeOat = new File(probe, "oat");
19533                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19534                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19535                            "Move only supported for modern cluster style installs");
19536                }
19537            }
19538
19539            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19540                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19541                        "Package already moved to " + volumeUuid);
19542            }
19543            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19544                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19545                        "Device admin cannot be moved");
19546            }
19547
19548            if (mFrozenPackages.contains(packageName)) {
19549                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19550                        "Failed to move already frozen package");
19551            }
19552
19553            codeFile = new File(pkg.codePath);
19554            installerPackageName = ps.installerPackageName;
19555            packageAbiOverride = ps.cpuAbiOverrideString;
19556            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19557            seinfo = pkg.applicationInfo.seinfo;
19558            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19559            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19560            freezer = new PackageFreezer(packageName, "movePackageInternal");
19561        }
19562
19563        final Bundle extras = new Bundle();
19564        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19565        extras.putString(Intent.EXTRA_TITLE, label);
19566        mMoveCallbacks.notifyCreated(moveId, extras);
19567
19568        int installFlags;
19569        final boolean moveCompleteApp;
19570        final File measurePath;
19571
19572        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19573            installFlags = INSTALL_INTERNAL;
19574            moveCompleteApp = !currentAsec;
19575            measurePath = Environment.getDataAppDirectory(volumeUuid);
19576        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19577            installFlags = INSTALL_EXTERNAL;
19578            moveCompleteApp = false;
19579            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19580        } else {
19581            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19582            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19583                    || !volume.isMountedWritable()) {
19584                freezer.close();
19585                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19586                        "Move location not mounted private volume");
19587            }
19588
19589            Preconditions.checkState(!currentAsec);
19590
19591            installFlags = INSTALL_INTERNAL;
19592            moveCompleteApp = true;
19593            measurePath = Environment.getDataAppDirectory(volumeUuid);
19594        }
19595
19596        final PackageStats stats = new PackageStats(null, -1);
19597        synchronized (mInstaller) {
19598            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19599                freezer.close();
19600                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19601                        "Failed to measure package size");
19602            }
19603        }
19604
19605        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19606                + stats.dataSize);
19607
19608        final long startFreeBytes = measurePath.getFreeSpace();
19609        final long sizeBytes;
19610        if (moveCompleteApp) {
19611            sizeBytes = stats.codeSize + stats.dataSize;
19612        } else {
19613            sizeBytes = stats.codeSize;
19614        }
19615
19616        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19617            freezer.close();
19618            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19619                    "Not enough free space to move");
19620        }
19621
19622        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19623
19624        final CountDownLatch installedLatch = new CountDownLatch(1);
19625        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19626            @Override
19627            public void onUserActionRequired(Intent intent) throws RemoteException {
19628                throw new IllegalStateException();
19629            }
19630
19631            @Override
19632            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19633                    Bundle extras) throws RemoteException {
19634                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19635                        + PackageManager.installStatusToString(returnCode, msg));
19636
19637                installedLatch.countDown();
19638                freezer.close();
19639
19640                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19641                switch (status) {
19642                    case PackageInstaller.STATUS_SUCCESS:
19643                        mMoveCallbacks.notifyStatusChanged(moveId,
19644                                PackageManager.MOVE_SUCCEEDED);
19645                        break;
19646                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19647                        mMoveCallbacks.notifyStatusChanged(moveId,
19648                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19649                        break;
19650                    default:
19651                        mMoveCallbacks.notifyStatusChanged(moveId,
19652                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19653                        break;
19654                }
19655            }
19656        };
19657
19658        final MoveInfo move;
19659        if (moveCompleteApp) {
19660            // Kick off a thread to report progress estimates
19661            new Thread() {
19662                @Override
19663                public void run() {
19664                    while (true) {
19665                        try {
19666                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19667                                break;
19668                            }
19669                        } catch (InterruptedException ignored) {
19670                        }
19671
19672                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19673                        final int progress = 10 + (int) MathUtils.constrain(
19674                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19675                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19676                    }
19677                }
19678            }.start();
19679
19680            final String dataAppName = codeFile.getName();
19681            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19682                    dataAppName, appId, seinfo, targetSdkVersion);
19683        } else {
19684            move = null;
19685        }
19686
19687        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19688
19689        final Message msg = mHandler.obtainMessage(INIT_COPY);
19690        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19691        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19692                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19693                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19694        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19695        msg.obj = params;
19696
19697        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19698                System.identityHashCode(msg.obj));
19699        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19700                System.identityHashCode(msg.obj));
19701
19702        mHandler.sendMessage(msg);
19703    }
19704
19705    @Override
19706    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19707        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19708
19709        final int realMoveId = mNextMoveId.getAndIncrement();
19710        final Bundle extras = new Bundle();
19711        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19712        mMoveCallbacks.notifyCreated(realMoveId, extras);
19713
19714        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19715            @Override
19716            public void onCreated(int moveId, Bundle extras) {
19717                // Ignored
19718            }
19719
19720            @Override
19721            public void onStatusChanged(int moveId, int status, long estMillis) {
19722                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19723            }
19724        };
19725
19726        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19727        storage.setPrimaryStorageUuid(volumeUuid, callback);
19728        return realMoveId;
19729    }
19730
19731    @Override
19732    public int getMoveStatus(int moveId) {
19733        mContext.enforceCallingOrSelfPermission(
19734                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19735        return mMoveCallbacks.mLastStatus.get(moveId);
19736    }
19737
19738    @Override
19739    public void registerMoveCallback(IPackageMoveObserver callback) {
19740        mContext.enforceCallingOrSelfPermission(
19741                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19742        mMoveCallbacks.register(callback);
19743    }
19744
19745    @Override
19746    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19747        mContext.enforceCallingOrSelfPermission(
19748                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19749        mMoveCallbacks.unregister(callback);
19750    }
19751
19752    @Override
19753    public boolean setInstallLocation(int loc) {
19754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19755                null);
19756        if (getInstallLocation() == loc) {
19757            return true;
19758        }
19759        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19760                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19761            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19762                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19763            return true;
19764        }
19765        return false;
19766   }
19767
19768    @Override
19769    public int getInstallLocation() {
19770        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19771                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19772                PackageHelper.APP_INSTALL_AUTO);
19773    }
19774
19775    /** Called by UserManagerService */
19776    void cleanUpUser(UserManagerService userManager, int userHandle) {
19777        synchronized (mPackages) {
19778            mDirtyUsers.remove(userHandle);
19779            mUserNeedsBadging.delete(userHandle);
19780            mSettings.removeUserLPw(userHandle);
19781            mPendingBroadcasts.remove(userHandle);
19782            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19783            removeUnusedPackagesLPw(userManager, userHandle);
19784        }
19785    }
19786
19787    /**
19788     * We're removing userHandle and would like to remove any downloaded packages
19789     * that are no longer in use by any other user.
19790     * @param userHandle the user being removed
19791     */
19792    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19793        final boolean DEBUG_CLEAN_APKS = false;
19794        int [] users = userManager.getUserIds();
19795        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19796        while (psit.hasNext()) {
19797            PackageSetting ps = psit.next();
19798            if (ps.pkg == null) {
19799                continue;
19800            }
19801            final String packageName = ps.pkg.packageName;
19802            // Skip over if system app
19803            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19804                continue;
19805            }
19806            if (DEBUG_CLEAN_APKS) {
19807                Slog.i(TAG, "Checking package " + packageName);
19808            }
19809            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19810            if (keep) {
19811                if (DEBUG_CLEAN_APKS) {
19812                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19813                }
19814            } else {
19815                for (int i = 0; i < users.length; i++) {
19816                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19817                        keep = true;
19818                        if (DEBUG_CLEAN_APKS) {
19819                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19820                                    + users[i]);
19821                        }
19822                        break;
19823                    }
19824                }
19825            }
19826            if (!keep) {
19827                if (DEBUG_CLEAN_APKS) {
19828                    Slog.i(TAG, "  Removing package " + packageName);
19829                }
19830                mHandler.post(new Runnable() {
19831                    public void run() {
19832                        deletePackageX(packageName, userHandle, 0);
19833                    } //end run
19834                });
19835            }
19836        }
19837    }
19838
19839    /** Called by UserManagerService */
19840    void createNewUser(int userHandle) {
19841        synchronized (mInstallLock) {
19842            mSettings.createNewUserLI(this, mInstaller, userHandle);
19843        }
19844        synchronized (mPackages) {
19845            applyFactoryDefaultBrowserLPw(userHandle);
19846            primeDomainVerificationsLPw(userHandle);
19847        }
19848    }
19849
19850    void newUserCreated(final int userHandle) {
19851        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19852        // If permission review for legacy apps is required, we represent
19853        // dagerous permissions for such apps as always granted runtime
19854        // permissions to keep per user flag state whether review is needed.
19855        // Hence, if a new user is added we have to propagate dangerous
19856        // permission grants for these legacy apps.
19857        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19858            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19859                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19860        }
19861    }
19862
19863    @Override
19864    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19865        mContext.enforceCallingOrSelfPermission(
19866                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19867                "Only package verification agents can read the verifier device identity");
19868
19869        synchronized (mPackages) {
19870            return mSettings.getVerifierDeviceIdentityLPw();
19871        }
19872    }
19873
19874    @Override
19875    public void setPermissionEnforced(String permission, boolean enforced) {
19876        // TODO: Now that we no longer change GID for storage, this should to away.
19877        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19878                "setPermissionEnforced");
19879        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19880            synchronized (mPackages) {
19881                if (mSettings.mReadExternalStorageEnforced == null
19882                        || mSettings.mReadExternalStorageEnforced != enforced) {
19883                    mSettings.mReadExternalStorageEnforced = enforced;
19884                    mSettings.writeLPr();
19885                }
19886            }
19887            // kill any non-foreground processes so we restart them and
19888            // grant/revoke the GID.
19889            final IActivityManager am = ActivityManagerNative.getDefault();
19890            if (am != null) {
19891                final long token = Binder.clearCallingIdentity();
19892                try {
19893                    am.killProcessesBelowForeground("setPermissionEnforcement");
19894                } catch (RemoteException e) {
19895                } finally {
19896                    Binder.restoreCallingIdentity(token);
19897                }
19898            }
19899        } else {
19900            throw new IllegalArgumentException("No selective enforcement for " + permission);
19901        }
19902    }
19903
19904    @Override
19905    @Deprecated
19906    public boolean isPermissionEnforced(String permission) {
19907        return true;
19908    }
19909
19910    @Override
19911    public boolean isStorageLow() {
19912        final long token = Binder.clearCallingIdentity();
19913        try {
19914            final DeviceStorageMonitorInternal
19915                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19916            if (dsm != null) {
19917                return dsm.isMemoryLow();
19918            } else {
19919                return false;
19920            }
19921        } finally {
19922            Binder.restoreCallingIdentity(token);
19923        }
19924    }
19925
19926    @Override
19927    public IPackageInstaller getPackageInstaller() {
19928        return mInstallerService;
19929    }
19930
19931    private boolean userNeedsBadging(int userId) {
19932        int index = mUserNeedsBadging.indexOfKey(userId);
19933        if (index < 0) {
19934            final UserInfo userInfo;
19935            final long token = Binder.clearCallingIdentity();
19936            try {
19937                userInfo = sUserManager.getUserInfo(userId);
19938            } finally {
19939                Binder.restoreCallingIdentity(token);
19940            }
19941            final boolean b;
19942            if (userInfo != null && userInfo.isManagedProfile()) {
19943                b = true;
19944            } else {
19945                b = false;
19946            }
19947            mUserNeedsBadging.put(userId, b);
19948            return b;
19949        }
19950        return mUserNeedsBadging.valueAt(index);
19951    }
19952
19953    @Override
19954    public KeySet getKeySetByAlias(String packageName, String alias) {
19955        if (packageName == null || alias == null) {
19956            return null;
19957        }
19958        synchronized(mPackages) {
19959            final PackageParser.Package pkg = mPackages.get(packageName);
19960            if (pkg == null) {
19961                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19962                throw new IllegalArgumentException("Unknown package: " + packageName);
19963            }
19964            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19965            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19966        }
19967    }
19968
19969    @Override
19970    public KeySet getSigningKeySet(String packageName) {
19971        if (packageName == null) {
19972            return null;
19973        }
19974        synchronized(mPackages) {
19975            final PackageParser.Package pkg = mPackages.get(packageName);
19976            if (pkg == null) {
19977                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19978                throw new IllegalArgumentException("Unknown package: " + packageName);
19979            }
19980            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19981                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19982                throw new SecurityException("May not access signing KeySet of other apps.");
19983            }
19984            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19985            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19986        }
19987    }
19988
19989    @Override
19990    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19991        if (packageName == null || ks == null) {
19992            return false;
19993        }
19994        synchronized(mPackages) {
19995            final PackageParser.Package pkg = mPackages.get(packageName);
19996            if (pkg == null) {
19997                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19998                throw new IllegalArgumentException("Unknown package: " + packageName);
19999            }
20000            IBinder ksh = ks.getToken();
20001            if (ksh instanceof KeySetHandle) {
20002                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20003                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20004            }
20005            return false;
20006        }
20007    }
20008
20009    @Override
20010    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20011        if (packageName == null || ks == null) {
20012            return false;
20013        }
20014        synchronized(mPackages) {
20015            final PackageParser.Package pkg = mPackages.get(packageName);
20016            if (pkg == null) {
20017                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20018                throw new IllegalArgumentException("Unknown package: " + packageName);
20019            }
20020            IBinder ksh = ks.getToken();
20021            if (ksh instanceof KeySetHandle) {
20022                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20023                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20024            }
20025            return false;
20026        }
20027    }
20028
20029    private void deletePackageIfUnusedLPr(final String packageName) {
20030        PackageSetting ps = mSettings.mPackages.get(packageName);
20031        if (ps == null) {
20032            return;
20033        }
20034        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20035            // TODO Implement atomic delete if package is unused
20036            // It is currently possible that the package will be deleted even if it is installed
20037            // after this method returns.
20038            mHandler.post(new Runnable() {
20039                public void run() {
20040                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20041                }
20042            });
20043        }
20044    }
20045
20046    /**
20047     * Check and throw if the given before/after packages would be considered a
20048     * downgrade.
20049     */
20050    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20051            throws PackageManagerException {
20052        if (after.versionCode < before.mVersionCode) {
20053            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20054                    "Update version code " + after.versionCode + " is older than current "
20055                    + before.mVersionCode);
20056        } else if (after.versionCode == before.mVersionCode) {
20057            if (after.baseRevisionCode < before.baseRevisionCode) {
20058                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20059                        "Update base revision code " + after.baseRevisionCode
20060                        + " is older than current " + before.baseRevisionCode);
20061            }
20062
20063            if (!ArrayUtils.isEmpty(after.splitNames)) {
20064                for (int i = 0; i < after.splitNames.length; i++) {
20065                    final String splitName = after.splitNames[i];
20066                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20067                    if (j != -1) {
20068                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20069                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20070                                    "Update split " + splitName + " revision code "
20071                                    + after.splitRevisionCodes[i] + " is older than current "
20072                                    + before.splitRevisionCodes[j]);
20073                        }
20074                    }
20075                }
20076            }
20077        }
20078    }
20079
20080    private static class MoveCallbacks extends Handler {
20081        private static final int MSG_CREATED = 1;
20082        private static final int MSG_STATUS_CHANGED = 2;
20083
20084        private final RemoteCallbackList<IPackageMoveObserver>
20085                mCallbacks = new RemoteCallbackList<>();
20086
20087        private final SparseIntArray mLastStatus = new SparseIntArray();
20088
20089        public MoveCallbacks(Looper looper) {
20090            super(looper);
20091        }
20092
20093        public void register(IPackageMoveObserver callback) {
20094            mCallbacks.register(callback);
20095        }
20096
20097        public void unregister(IPackageMoveObserver callback) {
20098            mCallbacks.unregister(callback);
20099        }
20100
20101        @Override
20102        public void handleMessage(Message msg) {
20103            final SomeArgs args = (SomeArgs) msg.obj;
20104            final int n = mCallbacks.beginBroadcast();
20105            for (int i = 0; i < n; i++) {
20106                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20107                try {
20108                    invokeCallback(callback, msg.what, args);
20109                } catch (RemoteException ignored) {
20110                }
20111            }
20112            mCallbacks.finishBroadcast();
20113            args.recycle();
20114        }
20115
20116        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20117                throws RemoteException {
20118            switch (what) {
20119                case MSG_CREATED: {
20120                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20121                    break;
20122                }
20123                case MSG_STATUS_CHANGED: {
20124                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20125                    break;
20126                }
20127            }
20128        }
20129
20130        private void notifyCreated(int moveId, Bundle extras) {
20131            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20132
20133            final SomeArgs args = SomeArgs.obtain();
20134            args.argi1 = moveId;
20135            args.arg2 = extras;
20136            obtainMessage(MSG_CREATED, args).sendToTarget();
20137        }
20138
20139        private void notifyStatusChanged(int moveId, int status) {
20140            notifyStatusChanged(moveId, status, -1);
20141        }
20142
20143        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20144            Slog.v(TAG, "Move " + moveId + " status " + status);
20145
20146            final SomeArgs args = SomeArgs.obtain();
20147            args.argi1 = moveId;
20148            args.argi2 = status;
20149            args.arg3 = estMillis;
20150            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20151
20152            synchronized (mLastStatus) {
20153                mLastStatus.put(moveId, status);
20154            }
20155        }
20156    }
20157
20158    private final static class OnPermissionChangeListeners extends Handler {
20159        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20160
20161        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20162                new RemoteCallbackList<>();
20163
20164        public OnPermissionChangeListeners(Looper looper) {
20165            super(looper);
20166        }
20167
20168        @Override
20169        public void handleMessage(Message msg) {
20170            switch (msg.what) {
20171                case MSG_ON_PERMISSIONS_CHANGED: {
20172                    final int uid = msg.arg1;
20173                    handleOnPermissionsChanged(uid);
20174                } break;
20175            }
20176        }
20177
20178        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20179            mPermissionListeners.register(listener);
20180
20181        }
20182
20183        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20184            mPermissionListeners.unregister(listener);
20185        }
20186
20187        public void onPermissionsChanged(int uid) {
20188            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20189                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20190            }
20191        }
20192
20193        private void handleOnPermissionsChanged(int uid) {
20194            final int count = mPermissionListeners.beginBroadcast();
20195            try {
20196                for (int i = 0; i < count; i++) {
20197                    IOnPermissionsChangeListener callback = mPermissionListeners
20198                            .getBroadcastItem(i);
20199                    try {
20200                        callback.onPermissionsChanged(uid);
20201                    } catch (RemoteException e) {
20202                        Log.e(TAG, "Permission listener is dead", e);
20203                    }
20204                }
20205            } finally {
20206                mPermissionListeners.finishBroadcast();
20207            }
20208        }
20209    }
20210
20211    private class PackageManagerInternalImpl extends PackageManagerInternal {
20212        @Override
20213        public void setLocationPackagesProvider(PackagesProvider provider) {
20214            synchronized (mPackages) {
20215                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20216            }
20217        }
20218
20219        @Override
20220        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20221            synchronized (mPackages) {
20222                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20223            }
20224        }
20225
20226        @Override
20227        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20228            synchronized (mPackages) {
20229                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20230            }
20231        }
20232
20233        @Override
20234        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20235            synchronized (mPackages) {
20236                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20237            }
20238        }
20239
20240        @Override
20241        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20242            synchronized (mPackages) {
20243                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20244            }
20245        }
20246
20247        @Override
20248        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20249            synchronized (mPackages) {
20250                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20251            }
20252        }
20253
20254        @Override
20255        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20256            synchronized (mPackages) {
20257                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20258                        packageName, userId);
20259            }
20260        }
20261
20262        @Override
20263        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20264            synchronized (mPackages) {
20265                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20266                        packageName, userId);
20267            }
20268        }
20269
20270        @Override
20271        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20272            synchronized (mPackages) {
20273                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20274                        packageName, userId);
20275            }
20276        }
20277
20278        @Override
20279        public void setKeepUninstalledPackages(final List<String> packageList) {
20280            Preconditions.checkNotNull(packageList);
20281            List<String> removedFromList = null;
20282            synchronized (mPackages) {
20283                if (mKeepUninstalledPackages != null) {
20284                    final int packagesCount = mKeepUninstalledPackages.size();
20285                    for (int i = 0; i < packagesCount; i++) {
20286                        String oldPackage = mKeepUninstalledPackages.get(i);
20287                        if (packageList != null && packageList.contains(oldPackage)) {
20288                            continue;
20289                        }
20290                        if (removedFromList == null) {
20291                            removedFromList = new ArrayList<>();
20292                        }
20293                        removedFromList.add(oldPackage);
20294                    }
20295                }
20296                mKeepUninstalledPackages = new ArrayList<>(packageList);
20297                if (removedFromList != null) {
20298                    final int removedCount = removedFromList.size();
20299                    for (int i = 0; i < removedCount; i++) {
20300                        deletePackageIfUnusedLPr(removedFromList.get(i));
20301                    }
20302                }
20303            }
20304        }
20305
20306        @Override
20307        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20308            synchronized (mPackages) {
20309                // If we do not support permission review, done.
20310                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20311                    return false;
20312                }
20313
20314                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20315                if (packageSetting == null) {
20316                    return false;
20317                }
20318
20319                // Permission review applies only to apps not supporting the new permission model.
20320                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20321                    return false;
20322                }
20323
20324                // Legacy apps have the permission and get user consent on launch.
20325                PermissionsState permissionsState = packageSetting.getPermissionsState();
20326                return permissionsState.isPermissionReviewRequired(userId);
20327            }
20328        }
20329
20330        @Override
20331        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20332            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20333        }
20334
20335        @Override
20336        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20337                int userId) {
20338            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20339        }
20340    }
20341
20342    @Override
20343    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20344        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20345        synchronized (mPackages) {
20346            final long identity = Binder.clearCallingIdentity();
20347            try {
20348                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20349                        packageNames, userId);
20350            } finally {
20351                Binder.restoreCallingIdentity(identity);
20352            }
20353        }
20354    }
20355
20356    private static void enforceSystemOrPhoneCaller(String tag) {
20357        int callingUid = Binder.getCallingUid();
20358        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20359            throw new SecurityException(
20360                    "Cannot call " + tag + " from UID " + callingUid);
20361        }
20362    }
20363
20364    boolean isHistoricalPackageUsageAvailable() {
20365        return mPackageUsage.isHistoricalPackageUsageAvailable();
20366    }
20367
20368    /**
20369     * Return a <b>copy</b> of the collection of packages known to the package manager.
20370     * @return A copy of the values of mPackages.
20371     */
20372    Collection<PackageParser.Package> getPackages() {
20373        synchronized (mPackages) {
20374            return new ArrayList<>(mPackages.values());
20375        }
20376    }
20377
20378    /**
20379     * Logs process start information (including base APK hash) to the security log.
20380     * @hide
20381     */
20382    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20383            String apkFile, int pid) {
20384        if (!SecurityLog.isLoggingEnabled()) {
20385            return;
20386        }
20387        Bundle data = new Bundle();
20388        data.putLong("startTimestamp", System.currentTimeMillis());
20389        data.putString("processName", processName);
20390        data.putInt("uid", uid);
20391        data.putString("seinfo", seinfo);
20392        data.putString("apkFile", apkFile);
20393        data.putInt("pid", pid);
20394        Message msg = mProcessLoggingHandler.obtainMessage(
20395                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20396        msg.setData(data);
20397        mProcessLoggingHandler.sendMessage(msg);
20398    }
20399}
20400