PackageManagerService.java revision c7b9482b0c4bb2d378e63541b96be45c50094e05
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 DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    // Special String to skip shared libraries check during compilation.
502    private static final String SPECIAL_SHARED_LIBRARY = "&";
503
504    final ServiceThread mHandlerThread;
505
506    final PackageHandler mHandler;
507
508    private final ProcessLoggingHandler mProcessLoggingHandler;
509
510    /**
511     * Messages for {@link #mHandler} that need to wait for system ready before
512     * being dispatched.
513     */
514    private ArrayList<Message> mPostSystemReadyMessages;
515
516    final int mSdkVersion = Build.VERSION.SDK_INT;
517
518    final Context mContext;
519    final boolean mFactoryTest;
520    final boolean mOnlyCore;
521    final DisplayMetrics mMetrics;
522    final int mDefParseFlags;
523    final String[] mSeparateProcesses;
524    final boolean mIsUpgrade;
525    final boolean mIsPreNUpgrade;
526
527    /** The location for ASEC container files on internal storage. */
528    final String mAsecInternalPath;
529
530    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
531    // LOCK HELD.  Can be called with mInstallLock held.
532    @GuardedBy("mInstallLock")
533    final Installer mInstaller;
534
535    /** Directory where installed third-party apps stored */
536    final File mAppInstallDir;
537    final File mEphemeralInstallDir;
538
539    /**
540     * Directory to which applications installed internally have their
541     * 32 bit native libraries copied.
542     */
543    private File mAppLib32InstallDir;
544
545    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
546    // apps.
547    final File mDrmAppPrivateInstallDir;
548
549    // ----------------------------------------------------------------
550
551    // Lock for state used when installing and doing other long running
552    // operations.  Methods that must be called with this lock held have
553    // the suffix "LI".
554    final Object mInstallLock = new Object();
555
556    // ----------------------------------------------------------------
557
558    // Keys are String (package name), values are Package.  This also serves
559    // as the lock for the global state.  Methods that must be called with
560    // this lock held have the prefix "LP".
561    @GuardedBy("mPackages")
562    final ArrayMap<String, PackageParser.Package> mPackages =
563            new ArrayMap<String, PackageParser.Package>();
564
565    final ArrayMap<String, Set<String>> mKnownCodebase =
566            new ArrayMap<String, Set<String>>();
567
568    // Tracks available target package names -> overlay package paths.
569    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
570        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
571
572    /**
573     * Tracks new system packages [received in an OTA] that we expect to
574     * find updated user-installed versions. Keys are package name, values
575     * are package location.
576     */
577    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
578    /**
579     * Tracks high priority intent filters for protected actions. During boot, certain
580     * filter actions are protected and should never be allowed to have a high priority
581     * intent filter for them. However, there is one, and only one exception -- the
582     * setup wizard. It must be able to define a high priority intent filter for these
583     * actions to ensure there are no escapes from the wizard. We need to delay processing
584     * of these during boot as we need to look at all of the system packages in order
585     * to know which component is the setup wizard.
586     */
587    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
588    /**
589     * Whether or not processing protected filters should be deferred.
590     */
591    private boolean mDeferProtectedFilters = true;
592
593    /**
594     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
595     */
596    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
597    /**
598     * Whether or not system app permissions should be promoted from install to runtime.
599     */
600    boolean mPromoteSystemApps;
601
602    @GuardedBy("mPackages")
603    final Settings mSettings;
604
605    /**
606     * Set of package names that are currently "frozen", which means active
607     * surgery is being done on the code/data for that package. The platform
608     * will refuse to launch frozen packages to avoid race conditions.
609     *
610     * @see PackageFreezer
611     */
612    @GuardedBy("mPackages")
613    final ArraySet<String> mFrozenPackages = new ArraySet<>();
614
615    boolean mRestoredSettings;
616
617    // System configuration read by SystemConfig.
618    final int[] mGlobalGids;
619    final SparseArray<ArraySet<String>> mSystemPermissions;
620    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
621
622    // If mac_permissions.xml was found for seinfo labeling.
623    boolean mFoundPolicyFile;
624
625    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
626
627    public static final class SharedLibraryEntry {
628        public final String path;
629        public final String apk;
630
631        SharedLibraryEntry(String _path, String _apk) {
632            path = _path;
633            apk = _apk;
634        }
635    }
636
637    // Currently known shared libraries.
638    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
639            new ArrayMap<String, SharedLibraryEntry>();
640
641    // All available activities, for your resolving pleasure.
642    final ActivityIntentResolver mActivities =
643            new ActivityIntentResolver();
644
645    // All available receivers, for your resolving pleasure.
646    final ActivityIntentResolver mReceivers =
647            new ActivityIntentResolver();
648
649    // All available services, for your resolving pleasure.
650    final ServiceIntentResolver mServices = new ServiceIntentResolver();
651
652    // All available providers, for your resolving pleasure.
653    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
654
655    // Mapping from provider base names (first directory in content URI codePath)
656    // to the provider information.
657    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
658            new ArrayMap<String, PackageParser.Provider>();
659
660    // Mapping from instrumentation class names to info about them.
661    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
662            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
663
664    // Mapping from permission names to info about them.
665    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
666            new ArrayMap<String, PackageParser.PermissionGroup>();
667
668    // Packages whose data we have transfered into another package, thus
669    // should no longer exist.
670    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
671
672    // Broadcast actions that are only available to the system.
673    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
674
675    /** List of packages waiting for verification. */
676    final SparseArray<PackageVerificationState> mPendingVerification
677            = new SparseArray<PackageVerificationState>();
678
679    /** Set of packages associated with each app op permission. */
680    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
681
682    final PackageInstallerService mInstallerService;
683
684    private final PackageDexOptimizer mPackageDexOptimizer;
685
686    private AtomicInteger mNextMoveId = new AtomicInteger();
687    private final MoveCallbacks mMoveCallbacks;
688
689    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
690
691    // Cache of users who need badging.
692    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
693
694    /** Token for keys in mPendingVerification. */
695    private int mPendingVerificationToken = 0;
696
697    volatile boolean mSystemReady;
698    volatile boolean mSafeMode;
699    volatile boolean mHasSystemUidErrors;
700
701    ApplicationInfo mAndroidApplication;
702    final ActivityInfo mResolveActivity = new ActivityInfo();
703    final ResolveInfo mResolveInfo = new ResolveInfo();
704    ComponentName mResolveComponentName;
705    PackageParser.Package mPlatformPackage;
706    ComponentName mCustomResolverComponentName;
707
708    boolean mResolverReplaced = false;
709
710    private final @Nullable ComponentName mIntentFilterVerifierComponent;
711    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
712
713    private int mIntentFilterVerificationToken = 0;
714
715    /** Component that knows whether or not an ephemeral application exists */
716    final ComponentName mEphemeralResolverComponent;
717    /** The service connection to the ephemeral resolver */
718    final EphemeralResolverConnection mEphemeralResolverConnection;
719
720    /** Component used to install ephemeral applications */
721    final ComponentName mEphemeralInstallerComponent;
722    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
723    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
724
725    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
726            = new SparseArray<IntentFilterVerificationState>();
727
728    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
729            new DefaultPermissionGrantPolicy(this);
730
731    // List of packages names to keep cached, even if they are uninstalled for all users
732    private List<String> mKeepUninstalledPackages;
733
734    private static class IFVerificationParams {
735        PackageParser.Package pkg;
736        boolean replacing;
737        int userId;
738        int verifierUid;
739
740        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
741                int _userId, int _verifierUid) {
742            pkg = _pkg;
743            replacing = _replacing;
744            userId = _userId;
745            replacing = _replacing;
746            verifierUid = _verifierUid;
747        }
748    }
749
750    private interface IntentFilterVerifier<T extends IntentFilter> {
751        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
752                                               T filter, String packageName);
753        void startVerifications(int userId);
754        void receiveVerificationResponse(int verificationId);
755    }
756
757    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
758        private Context mContext;
759        private ComponentName mIntentFilterVerifierComponent;
760        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
761
762        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
763            mContext = context;
764            mIntentFilterVerifierComponent = verifierComponent;
765        }
766
767        private String getDefaultScheme() {
768            return IntentFilter.SCHEME_HTTPS;
769        }
770
771        @Override
772        public void startVerifications(int userId) {
773            // Launch verifications requests
774            int count = mCurrentIntentFilterVerifications.size();
775            for (int n=0; n<count; n++) {
776                int verificationId = mCurrentIntentFilterVerifications.get(n);
777                final IntentFilterVerificationState ivs =
778                        mIntentFilterVerificationStates.get(verificationId);
779
780                String packageName = ivs.getPackageName();
781
782                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
783                final int filterCount = filters.size();
784                ArraySet<String> domainsSet = new ArraySet<>();
785                for (int m=0; m<filterCount; m++) {
786                    PackageParser.ActivityIntentInfo filter = filters.get(m);
787                    domainsSet.addAll(filter.getHostsList());
788                }
789                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
790                synchronized (mPackages) {
791                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
792                            packageName, domainsList) != null) {
793                        scheduleWriteSettingsLocked();
794                    }
795                }
796                sendVerificationRequest(userId, verificationId, ivs);
797            }
798            mCurrentIntentFilterVerifications.clear();
799        }
800
801        private void sendVerificationRequest(int userId, int verificationId,
802                IntentFilterVerificationState ivs) {
803
804            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
807                    verificationId);
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
810                    getDefaultScheme());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
813                    ivs.getHostsString());
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
816                    ivs.getPackageName());
817            verificationIntent.setComponent(mIntentFilterVerifierComponent);
818            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
819
820            UserHandle user = new UserHandle(userId);
821            mContext.sendBroadcastAsUser(verificationIntent, user);
822            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
823                    "Sending IntentFilter verification broadcast");
824        }
825
826        public void receiveVerificationResponse(int verificationId) {
827            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
828
829            final boolean verified = ivs.isVerified();
830
831            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
832            final int count = filters.size();
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.i(TAG, "Received verification response " + verificationId
835                        + " for " + count + " filters, verified=" + verified);
836            }
837            for (int n=0; n<count; n++) {
838                PackageParser.ActivityIntentInfo filter = filters.get(n);
839                filter.setVerified(verified);
840
841                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
842                        + " verified with result:" + verified + " and hosts:"
843                        + ivs.getHostsString());
844            }
845
846            mIntentFilterVerificationStates.remove(verificationId);
847
848            final String packageName = ivs.getPackageName();
849            IntentFilterVerificationInfo ivi = null;
850
851            synchronized (mPackages) {
852                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
853            }
854            if (ivi == null) {
855                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
856                        + verificationId + " packageName:" + packageName);
857                return;
858            }
859            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
860                    "Updating IntentFilterVerificationInfo for package " + packageName
861                            +" verificationId:" + verificationId);
862
863            synchronized (mPackages) {
864                if (verified) {
865                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
866                } else {
867                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
868                }
869                scheduleWriteSettingsLocked();
870
871                final int userId = ivs.getUserId();
872                if (userId != UserHandle.USER_ALL) {
873                    final int userStatus =
874                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
875
876                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
877                    boolean needUpdate = false;
878
879                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
880                    // already been set by the User thru the Disambiguation dialog
881                    switch (userStatus) {
882                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
883                            if (verified) {
884                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
885                            } else {
886                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
887                            }
888                            needUpdate = true;
889                            break;
890
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                                needUpdate = true;
895                            }
896                            break;
897
898                        default:
899                            // Nothing to do
900                    }
901
902                    if (needUpdate) {
903                        mSettings.updateIntentFilterVerificationStatusLPw(
904                                packageName, updatedStatus, userId);
905                        scheduleWritePackageRestrictionsLocked(userId);
906                    }
907                }
908            }
909        }
910
911        @Override
912        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
913                    ActivityIntentInfo filter, String packageName) {
914            if (!hasValidDomains(filter)) {
915                return false;
916            }
917            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
918            if (ivs == null) {
919                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
920                        packageName);
921            }
922            if (DEBUG_DOMAIN_VERIFICATION) {
923                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
924            }
925            ivs.addFilter(filter);
926            return true;
927        }
928
929        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
930                int userId, int verificationId, String packageName) {
931            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
932                    verifierUid, userId, packageName);
933            ivs.setPendingState();
934            synchronized (mPackages) {
935                mIntentFilterVerificationStates.append(verificationId, ivs);
936                mCurrentIntentFilterVerifications.add(verificationId);
937            }
938            return ivs;
939        }
940    }
941
942    private static boolean hasValidDomains(ActivityIntentInfo filter) {
943        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
944                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
945                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
946    }
947
948    // Set of pending broadcasts for aggregating enable/disable of components.
949    static class PendingPackageBroadcasts {
950        // for each user id, a map of <package name -> components within that package>
951        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
952
953        public PendingPackageBroadcasts() {
954            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
955        }
956
957        public ArrayList<String> get(int userId, String packageName) {
958            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
959            return packages.get(packageName);
960        }
961
962        public void put(int userId, String packageName, ArrayList<String> components) {
963            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
964            packages.put(packageName, components);
965        }
966
967        public void remove(int userId, String packageName) {
968            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
969            if (packages != null) {
970                packages.remove(packageName);
971            }
972        }
973
974        public void remove(int userId) {
975            mUidMap.remove(userId);
976        }
977
978        public int userIdCount() {
979            return mUidMap.size();
980        }
981
982        public int userIdAt(int n) {
983            return mUidMap.keyAt(n);
984        }
985
986        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
987            return mUidMap.get(userId);
988        }
989
990        public int size() {
991            // total number of pending broadcast entries across all userIds
992            int num = 0;
993            for (int i = 0; i< mUidMap.size(); i++) {
994                num += mUidMap.valueAt(i).size();
995            }
996            return num;
997        }
998
999        public void clear() {
1000            mUidMap.clear();
1001        }
1002
1003        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1004            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1005            if (map == null) {
1006                map = new ArrayMap<String, ArrayList<String>>();
1007                mUidMap.put(userId, map);
1008            }
1009            return map;
1010        }
1011    }
1012    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1013
1014    // Service Connection to remote media container service to copy
1015    // package uri's from external media onto secure containers
1016    // or internal storage.
1017    private IMediaContainerService mContainerService = null;
1018
1019    static final int SEND_PENDING_BROADCAST = 1;
1020    static final int MCS_BOUND = 3;
1021    static final int END_COPY = 4;
1022    static final int INIT_COPY = 5;
1023    static final int MCS_UNBIND = 6;
1024    static final int START_CLEANING_PACKAGE = 7;
1025    static final int FIND_INSTALL_LOC = 8;
1026    static final int POST_INSTALL = 9;
1027    static final int MCS_RECONNECT = 10;
1028    static final int MCS_GIVE_UP = 11;
1029    static final int UPDATED_MEDIA_STATUS = 12;
1030    static final int WRITE_SETTINGS = 13;
1031    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1032    static final int PACKAGE_VERIFIED = 15;
1033    static final int CHECK_PENDING_VERIFICATION = 16;
1034    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1035    static final int INTENT_FILTER_VERIFIED = 18;
1036
1037    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1038
1039    // Delay time in millisecs
1040    static final int BROADCAST_DELAY = 10 * 1000;
1041
1042    static UserManagerService sUserManager;
1043
1044    // Stores a list of users whose package restrictions file needs to be updated
1045    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1046
1047    final private DefaultContainerConnection mDefContainerConn =
1048            new DefaultContainerConnection();
1049    class DefaultContainerConnection implements ServiceConnection {
1050        public void onServiceConnected(ComponentName name, IBinder service) {
1051            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1052            IMediaContainerService imcs =
1053                IMediaContainerService.Stub.asInterface(service);
1054            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1055        }
1056
1057        public void onServiceDisconnected(ComponentName name) {
1058            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1059        }
1060    }
1061
1062    // Recordkeeping of restore-after-install operations that are currently in flight
1063    // between the Package Manager and the Backup Manager
1064    static class PostInstallData {
1065        public InstallArgs args;
1066        public PackageInstalledInfo res;
1067
1068        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1069            args = _a;
1070            res = _r;
1071        }
1072    }
1073
1074    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1075    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1076
1077    // XML tags for backup/restore of various bits of state
1078    private static final String TAG_PREFERRED_BACKUP = "pa";
1079    private static final String TAG_DEFAULT_APPS = "da";
1080    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1081
1082    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1083    private static final String TAG_ALL_GRANTS = "rt-grants";
1084    private static final String TAG_GRANT = "grant";
1085    private static final String ATTR_PACKAGE_NAME = "pkg";
1086
1087    private static final String TAG_PERMISSION = "perm";
1088    private static final String ATTR_PERMISSION_NAME = "name";
1089    private static final String ATTR_IS_GRANTED = "g";
1090    private static final String ATTR_USER_SET = "set";
1091    private static final String ATTR_USER_FIXED = "fixed";
1092    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1093
1094    // System/policy permission grants are not backed up
1095    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1096            FLAG_PERMISSION_POLICY_FIXED
1097            | FLAG_PERMISSION_SYSTEM_FIXED
1098            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1099
1100    // And we back up these user-adjusted states
1101    private static final int USER_RUNTIME_GRANT_MASK =
1102            FLAG_PERMISSION_USER_SET
1103            | FLAG_PERMISSION_USER_FIXED
1104            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1105
1106    final @Nullable String mRequiredVerifierPackage;
1107    final @NonNull String mRequiredInstallerPackage;
1108    final @Nullable String mSetupWizardPackage;
1109    final @NonNull String mServicesSystemSharedLibraryPackageName;
1110    final @NonNull String mSharedSystemSharedLibraryPackageName;
1111
1112    private final PackageUsage mPackageUsage = new PackageUsage();
1113
1114    private class PackageUsage {
1115        private static final int WRITE_INTERVAL
1116            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1117
1118        private final Object mFileLock = new Object();
1119        private final AtomicLong mLastWritten = new AtomicLong(0);
1120        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1121
1122        private boolean mIsHistoricalPackageUsageAvailable = true;
1123
1124        boolean isHistoricalPackageUsageAvailable() {
1125            return mIsHistoricalPackageUsageAvailable;
1126        }
1127
1128        void write(boolean force) {
1129            if (force) {
1130                writeInternal();
1131                return;
1132            }
1133            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1134                && !DEBUG_DEXOPT) {
1135                return;
1136            }
1137            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1138                new Thread("PackageUsage_DiskWriter") {
1139                    @Override
1140                    public void run() {
1141                        try {
1142                            writeInternal();
1143                        } finally {
1144                            mBackgroundWriteRunning.set(false);
1145                        }
1146                    }
1147                }.start();
1148            }
1149        }
1150
1151        private void writeInternal() {
1152            synchronized (mPackages) {
1153                synchronized (mFileLock) {
1154                    AtomicFile file = getFile();
1155                    FileOutputStream f = null;
1156                    try {
1157                        f = file.startWrite();
1158                        BufferedOutputStream out = new BufferedOutputStream(f);
1159                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1160                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1161                        StringBuilder sb = new StringBuilder();
1162
1163                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1164                        sb.append('\n');
1165                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1166
1167                        for (PackageParser.Package pkg : mPackages.values()) {
1168                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1169                                continue;
1170                            }
1171                            sb.setLength(0);
1172                            sb.append(pkg.packageName);
1173                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1174                                sb.append(' ');
1175                                sb.append(usageTimeInMillis);
1176                            }
1177                            sb.append('\n');
1178                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1179                        }
1180                        out.flush();
1181                        file.finishWrite(f);
1182                    } catch (IOException e) {
1183                        if (f != null) {
1184                            file.failWrite(f);
1185                        }
1186                        Log.e(TAG, "Failed to write package usage times", e);
1187                    }
1188                }
1189            }
1190            mLastWritten.set(SystemClock.elapsedRealtime());
1191        }
1192
1193        void readLP() {
1194            synchronized (mFileLock) {
1195                AtomicFile file = getFile();
1196                BufferedInputStream in = null;
1197                try {
1198                    in = new BufferedInputStream(file.openRead());
1199                    StringBuffer sb = new StringBuffer();
1200
1201                    String firstLine = readLine(in, sb);
1202                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1203                        readVersion1LP(in, sb);
1204                    } else {
1205                        readVersion0LP(in, sb, firstLine);
1206                    }
1207                } catch (FileNotFoundException expected) {
1208                    mIsHistoricalPackageUsageAvailable = false;
1209                } catch (IOException e) {
1210                    Log.w(TAG, "Failed to read package usage times", e);
1211                } finally {
1212                    IoUtils.closeQuietly(in);
1213                }
1214            }
1215            mLastWritten.set(SystemClock.elapsedRealtime());
1216        }
1217
1218        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1219                throws IOException {
1220            // Initial version of the file had no version number and stored one
1221            // package-timestamp pair per line.
1222            // Note that the first line has already been read from the InputStream.
1223            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1224                String[] tokens = line.split(" ");
1225                if (tokens.length != 2) {
1226                    throw new IOException("Failed to parse " + line +
1227                            " as package-timestamp pair.");
1228                }
1229
1230                String packageName = tokens[0];
1231                PackageParser.Package pkg = mPackages.get(packageName);
1232                if (pkg == null) {
1233                    continue;
1234                }
1235
1236                long timestamp = parseAsLong(tokens[1]);
1237                for (int reason = 0;
1238                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1239                        reason++) {
1240                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1241                }
1242            }
1243        }
1244
1245        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1246            // Version 1 of the file started with the corresponding version
1247            // number and then stored a package name and eight timestamps per line.
1248            String line;
1249            while ((line = readLine(in, sb)) != null) {
1250                String[] tokens = line.split(" ");
1251                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1252                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1253                }
1254
1255                String packageName = tokens[0];
1256                PackageParser.Package pkg = mPackages.get(packageName);
1257                if (pkg == null) {
1258                    continue;
1259                }
1260
1261                for (int reason = 0;
1262                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1263                        reason++) {
1264                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1265                }
1266            }
1267        }
1268
1269        private long parseAsLong(String token) throws IOException {
1270            try {
1271                return Long.parseLong(token);
1272            } catch (NumberFormatException e) {
1273                throw new IOException("Failed to parse " + token + " as a long.", e);
1274            }
1275        }
1276
1277        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1278            return readToken(in, sb, '\n');
1279        }
1280
1281        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1282                throws IOException {
1283            sb.setLength(0);
1284            while (true) {
1285                int ch = in.read();
1286                if (ch == -1) {
1287                    if (sb.length() == 0) {
1288                        return null;
1289                    }
1290                    throw new IOException("Unexpected EOF");
1291                }
1292                if (ch == endOfToken) {
1293                    return sb.toString();
1294                }
1295                sb.append((char)ch);
1296            }
1297        }
1298
1299        private AtomicFile getFile() {
1300            File dataDir = Environment.getDataDirectory();
1301            File systemDir = new File(dataDir, "system");
1302            File fname = new File(systemDir, "package-usage.list");
1303            return new AtomicFile(fname);
1304        }
1305
1306        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1307        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1308    }
1309
1310    class PackageHandler extends Handler {
1311        private boolean mBound = false;
1312        final ArrayList<HandlerParams> mPendingInstalls =
1313            new ArrayList<HandlerParams>();
1314
1315        private boolean connectToService() {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1317                    " DefaultContainerService");
1318            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1319            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1320            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1321                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1322                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1323                mBound = true;
1324                return true;
1325            }
1326            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1327            return false;
1328        }
1329
1330        private void disconnectService() {
1331            mContainerService = null;
1332            mBound = false;
1333            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1334            mContext.unbindService(mDefContainerConn);
1335            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336        }
1337
1338        PackageHandler(Looper looper) {
1339            super(looper);
1340        }
1341
1342        public void handleMessage(Message msg) {
1343            try {
1344                doHandleMessage(msg);
1345            } finally {
1346                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1347            }
1348        }
1349
1350        void doHandleMessage(Message msg) {
1351            switch (msg.what) {
1352                case INIT_COPY: {
1353                    HandlerParams params = (HandlerParams) msg.obj;
1354                    int idx = mPendingInstalls.size();
1355                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1356                    // If a bind was already initiated we dont really
1357                    // need to do anything. The pending install
1358                    // will be processed later on.
1359                    if (!mBound) {
1360                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1361                                System.identityHashCode(mHandler));
1362                        // If this is the only one pending we might
1363                        // have to bind to the service again.
1364                        if (!connectToService()) {
1365                            Slog.e(TAG, "Failed to bind to media container service");
1366                            params.serviceError();
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1368                                    System.identityHashCode(mHandler));
1369                            if (params.traceMethod != null) {
1370                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1371                                        params.traceCookie);
1372                            }
1373                            return;
1374                        } else {
1375                            // Once we bind to the service, the first
1376                            // pending request will be processed.
1377                            mPendingInstalls.add(idx, params);
1378                        }
1379                    } else {
1380                        mPendingInstalls.add(idx, params);
1381                        // Already bound to the service. Just make
1382                        // sure we trigger off processing the first request.
1383                        if (idx == 0) {
1384                            mHandler.sendEmptyMessage(MCS_BOUND);
1385                        }
1386                    }
1387                    break;
1388                }
1389                case MCS_BOUND: {
1390                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1391                    if (msg.obj != null) {
1392                        mContainerService = (IMediaContainerService) msg.obj;
1393                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1394                                System.identityHashCode(mHandler));
1395                    }
1396                    if (mContainerService == null) {
1397                        if (!mBound) {
1398                            // Something seriously wrong since we are not bound and we are not
1399                            // waiting for connection. Bail out.
1400                            Slog.e(TAG, "Cannot bind to media container service");
1401                            for (HandlerParams params : mPendingInstalls) {
1402                                // Indicate service bind error
1403                                params.serviceError();
1404                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1405                                        System.identityHashCode(params));
1406                                if (params.traceMethod != null) {
1407                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1408                                            params.traceMethod, params.traceCookie);
1409                                }
1410                                return;
1411                            }
1412                            mPendingInstalls.clear();
1413                        } else {
1414                            Slog.w(TAG, "Waiting to connect to media container service");
1415                        }
1416                    } else if (mPendingInstalls.size() > 0) {
1417                        HandlerParams params = mPendingInstalls.get(0);
1418                        if (params != null) {
1419                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                                    System.identityHashCode(params));
1421                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1422                            if (params.startCopy()) {
1423                                // We are done...  look for more work or to
1424                                // go idle.
1425                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1426                                        "Checking for more work or unbind...");
1427                                // Delete pending install
1428                                if (mPendingInstalls.size() > 0) {
1429                                    mPendingInstalls.remove(0);
1430                                }
1431                                if (mPendingInstalls.size() == 0) {
1432                                    if (mBound) {
1433                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1434                                                "Posting delayed MCS_UNBIND");
1435                                        removeMessages(MCS_UNBIND);
1436                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1437                                        // Unbind after a little delay, to avoid
1438                                        // continual thrashing.
1439                                        sendMessageDelayed(ubmsg, 10000);
1440                                    }
1441                                } else {
1442                                    // There are more pending requests in queue.
1443                                    // Just post MCS_BOUND message to trigger processing
1444                                    // of next pending install.
1445                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1446                                            "Posting MCS_BOUND for next work");
1447                                    mHandler.sendEmptyMessage(MCS_BOUND);
1448                                }
1449                            }
1450                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1451                        }
1452                    } else {
1453                        // Should never happen ideally.
1454                        Slog.w(TAG, "Empty queue");
1455                    }
1456                    break;
1457                }
1458                case MCS_RECONNECT: {
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1460                    if (mPendingInstalls.size() > 0) {
1461                        if (mBound) {
1462                            disconnectService();
1463                        }
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            for (HandlerParams params : mPendingInstalls) {
1467                                // Indicate service bind error
1468                                params.serviceError();
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1470                                        System.identityHashCode(params));
1471                            }
1472                            mPendingInstalls.clear();
1473                        }
1474                    }
1475                    break;
1476                }
1477                case MCS_UNBIND: {
1478                    // If there is no actual work left, then time to unbind.
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1480
1481                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1482                        if (mBound) {
1483                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1484
1485                            disconnectService();
1486                        }
1487                    } else if (mPendingInstalls.size() > 0) {
1488                        // There are more pending requests in queue.
1489                        // Just post MCS_BOUND message to trigger processing
1490                        // of next pending install.
1491                        mHandler.sendEmptyMessage(MCS_BOUND);
1492                    }
1493
1494                    break;
1495                }
1496                case MCS_GIVE_UP: {
1497                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1498                    HandlerParams params = mPendingInstalls.remove(0);
1499                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                            System.identityHashCode(params));
1501                    break;
1502                }
1503                case SEND_PENDING_BROADCAST: {
1504                    String packages[];
1505                    ArrayList<String> components[];
1506                    int size = 0;
1507                    int uids[];
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1509                    synchronized (mPackages) {
1510                        if (mPendingBroadcasts == null) {
1511                            return;
1512                        }
1513                        size = mPendingBroadcasts.size();
1514                        if (size <= 0) {
1515                            // Nothing to be done. Just return
1516                            return;
1517                        }
1518                        packages = new String[size];
1519                        components = new ArrayList[size];
1520                        uids = new int[size];
1521                        int i = 0;  // filling out the above arrays
1522
1523                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1524                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1525                            Iterator<Map.Entry<String, ArrayList<String>>> it
1526                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1527                                            .entrySet().iterator();
1528                            while (it.hasNext() && i < size) {
1529                                Map.Entry<String, ArrayList<String>> ent = it.next();
1530                                packages[i] = ent.getKey();
1531                                components[i] = ent.getValue();
1532                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1533                                uids[i] = (ps != null)
1534                                        ? UserHandle.getUid(packageUserId, ps.appId)
1535                                        : -1;
1536                                i++;
1537                            }
1538                        }
1539                        size = i;
1540                        mPendingBroadcasts.clear();
1541                    }
1542                    // Send broadcasts
1543                    for (int i = 0; i < size; i++) {
1544                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1545                    }
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1547                    break;
1548                }
1549                case START_CLEANING_PACKAGE: {
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1551                    final String packageName = (String)msg.obj;
1552                    final int userId = msg.arg1;
1553                    final boolean andCode = msg.arg2 != 0;
1554                    synchronized (mPackages) {
1555                        if (userId == UserHandle.USER_ALL) {
1556                            int[] users = sUserManager.getUserIds();
1557                            for (int user : users) {
1558                                mSettings.addPackageToCleanLPw(
1559                                        new PackageCleanItem(user, packageName, andCode));
1560                            }
1561                        } else {
1562                            mSettings.addPackageToCleanLPw(
1563                                    new PackageCleanItem(userId, packageName, andCode));
1564                        }
1565                    }
1566                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1567                    startCleaningPackages();
1568                } break;
1569                case POST_INSTALL: {
1570                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1571
1572                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1573                    mRunningInstalls.delete(msg.arg1);
1574
1575                    if (data != null) {
1576                        InstallArgs args = data.args;
1577                        PackageInstalledInfo parentRes = data.res;
1578
1579                        final boolean grantPermissions = (args.installFlags
1580                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1581                        final boolean killApp = (args.installFlags
1582                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1583                        final String[] grantedPermissions = args.installGrantPermissions;
1584
1585                        // Handle the parent package
1586                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1587                                grantedPermissions, args.observer);
1588
1589                        // Handle the child packages
1590                        final int childCount = (parentRes.addedChildPackages != null)
1591                                ? parentRes.addedChildPackages.size() : 0;
1592                        for (int i = 0; i < childCount; i++) {
1593                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1594                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1595                                    grantedPermissions, args.observer);
1596                        }
1597
1598                        // Log tracing if needed
1599                        if (args.traceMethod != null) {
1600                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1601                                    args.traceCookie);
1602                        }
1603                    } else {
1604                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1605                    }
1606
1607                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1608                } break;
1609                case UPDATED_MEDIA_STATUS: {
1610                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1611                    boolean reportStatus = msg.arg1 == 1;
1612                    boolean doGc = msg.arg2 == 1;
1613                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1614                    if (doGc) {
1615                        // Force a gc to clear up stale containers.
1616                        Runtime.getRuntime().gc();
1617                    }
1618                    if (msg.obj != null) {
1619                        @SuppressWarnings("unchecked")
1620                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1621                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1622                        // Unload containers
1623                        unloadAllContainers(args);
1624                    }
1625                    if (reportStatus) {
1626                        try {
1627                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1628                            PackageHelper.getMountService().finishMediaUpdate();
1629                        } catch (RemoteException e) {
1630                            Log.e(TAG, "MountService not running?");
1631                        }
1632                    }
1633                } break;
1634                case WRITE_SETTINGS: {
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1636                    synchronized (mPackages) {
1637                        removeMessages(WRITE_SETTINGS);
1638                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1639                        mSettings.writeLPr();
1640                        mDirtyUsers.clear();
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                } break;
1644                case WRITE_PACKAGE_RESTRICTIONS: {
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1646                    synchronized (mPackages) {
1647                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1648                        for (int userId : mDirtyUsers) {
1649                            mSettings.writePackageRestrictionsLPr(userId);
1650                        }
1651                        mDirtyUsers.clear();
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                } break;
1655                case CHECK_PENDING_VERIFICATION: {
1656                    final int verificationId = msg.arg1;
1657                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1658
1659                    if ((state != null) && !state.timeoutExtended()) {
1660                        final InstallArgs args = state.getInstallArgs();
1661                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1662
1663                        Slog.i(TAG, "Verification timed out for " + originUri);
1664                        mPendingVerification.remove(verificationId);
1665
1666                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1667
1668                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1669                            Slog.i(TAG, "Continuing with installation of " + originUri);
1670                            state.setVerifierResponse(Binder.getCallingUid(),
1671                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1672                            broadcastPackageVerified(verificationId, originUri,
1673                                    PackageManager.VERIFICATION_ALLOW,
1674                                    state.getInstallArgs().getUser());
1675                            try {
1676                                ret = args.copyApk(mContainerService, true);
1677                            } catch (RemoteException e) {
1678                                Slog.e(TAG, "Could not contact the ContainerService");
1679                            }
1680                        } else {
1681                            broadcastPackageVerified(verificationId, originUri,
1682                                    PackageManager.VERIFICATION_REJECT,
1683                                    state.getInstallArgs().getUser());
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692                    break;
1693                }
1694                case PACKAGE_VERIFIED: {
1695                    final int verificationId = msg.arg1;
1696
1697                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1698                    if (state == null) {
1699                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1700                        break;
1701                    }
1702
1703                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1704
1705                    state.setVerifierResponse(response.callerUid, response.code);
1706
1707                    if (state.isVerificationComplete()) {
1708                        mPendingVerification.remove(verificationId);
1709
1710                        final InstallArgs args = state.getInstallArgs();
1711                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1712
1713                        int ret;
1714                        if (state.isInstallAllowed()) {
1715                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1716                            broadcastPackageVerified(verificationId, originUri,
1717                                    response.code, state.getInstallArgs().getUser());
1718                            try {
1719                                ret = args.copyApk(mContainerService, true);
1720                            } catch (RemoteException e) {
1721                                Slog.e(TAG, "Could not contact the ContainerService");
1722                            }
1723                        } else {
1724                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1725                        }
1726
1727                        Trace.asyncTraceEnd(
1728                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1729
1730                        processPendingInstall(args, ret);
1731                        mHandler.sendEmptyMessage(MCS_UNBIND);
1732                    }
1733
1734                    break;
1735                }
1736                case START_INTENT_FILTER_VERIFICATIONS: {
1737                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1738                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1739                            params.replacing, params.pkg);
1740                    break;
1741                }
1742                case INTENT_FILTER_VERIFIED: {
1743                    final int verificationId = msg.arg1;
1744
1745                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1746                            verificationId);
1747                    if (state == null) {
1748                        Slog.w(TAG, "Invalid IntentFilter verification token "
1749                                + verificationId + " received");
1750                        break;
1751                    }
1752
1753                    final int userId = state.getUserId();
1754
1755                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1756                            "Processing IntentFilter verification with token:"
1757                            + verificationId + " and userId:" + userId);
1758
1759                    final IntentFilterVerificationResponse response =
1760                            (IntentFilterVerificationResponse) msg.obj;
1761
1762                    state.setVerifierResponse(response.callerUid, response.code);
1763
1764                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1765                            "IntentFilter verification with token:" + verificationId
1766                            + " and userId:" + userId
1767                            + " is settings verifier response with response code:"
1768                            + response.code);
1769
1770                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1771                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1772                                + response.getFailedDomainsString());
1773                    }
1774
1775                    if (state.isVerificationComplete()) {
1776                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1777                    } else {
1778                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1779                                "IntentFilter verification with token:" + verificationId
1780                                + " was not said to be complete");
1781                    }
1782
1783                    break;
1784                }
1785            }
1786        }
1787    }
1788
1789    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1790            boolean killApp, String[] grantedPermissions,
1791            IPackageInstallObserver2 installObserver) {
1792        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1793            // Send the removed broadcasts
1794            if (res.removedInfo != null) {
1795                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1796            }
1797
1798            // Now that we successfully installed the package, grant runtime
1799            // permissions if requested before broadcasting the install.
1800            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1801                    >= Build.VERSION_CODES.M) {
1802                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1803            }
1804
1805            final boolean update = res.removedInfo != null
1806                    && res.removedInfo.removedPackage != null;
1807
1808            // If this is the first time we have child packages for a disabled privileged
1809            // app that had no children, we grant requested runtime permissions to the new
1810            // children if the parent on the system image had them already granted.
1811            if (res.pkg.parentPackage != null) {
1812                synchronized (mPackages) {
1813                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1814                }
1815            }
1816
1817            synchronized (mPackages) {
1818                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1819            }
1820
1821            final String packageName = res.pkg.applicationInfo.packageName;
1822            Bundle extras = new Bundle(1);
1823            extras.putInt(Intent.EXTRA_UID, res.uid);
1824
1825            // Determine the set of users who are adding this package for
1826            // the first time vs. those who are seeing an update.
1827            int[] firstUsers = EMPTY_INT_ARRAY;
1828            int[] updateUsers = EMPTY_INT_ARRAY;
1829            if (res.origUsers == null || res.origUsers.length == 0) {
1830                firstUsers = res.newUsers;
1831            } else {
1832                for (int newUser : res.newUsers) {
1833                    boolean isNew = true;
1834                    for (int origUser : res.origUsers) {
1835                        if (origUser == newUser) {
1836                            isNew = false;
1837                            break;
1838                        }
1839                    }
1840                    if (isNew) {
1841                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1842                    } else {
1843                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1844                    }
1845                }
1846            }
1847
1848            // Send installed broadcasts if the install/update is not ephemeral
1849            if (!isEphemeral(res.pkg)) {
1850                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1851
1852                // Send added for users that see the package for the first time
1853                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1854                        extras, 0 /*flags*/, null /*targetPackage*/,
1855                        null /*finishedReceiver*/, firstUsers);
1856
1857                // Send added for users that don't see the package for the first time
1858                if (update) {
1859                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1860                }
1861                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1862                        extras, 0 /*flags*/, null /*targetPackage*/,
1863                        null /*finishedReceiver*/, updateUsers);
1864
1865                // Send replaced for users that don't see the package for the first time
1866                if (update) {
1867                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1868                            packageName, extras, 0 /*flags*/,
1869                            null /*targetPackage*/, null /*finishedReceiver*/,
1870                            updateUsers);
1871                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1872                            null /*package*/, null /*extras*/, 0 /*flags*/,
1873                            packageName /*targetPackage*/,
1874                            null /*finishedReceiver*/, updateUsers);
1875                }
1876
1877                // Send broadcast package appeared if forward locked/external for all users
1878                // treat asec-hosted packages like removable media on upgrade
1879                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1880                    if (DEBUG_INSTALL) {
1881                        Slog.i(TAG, "upgrading pkg " + res.pkg
1882                                + " is ASEC-hosted -> AVAILABLE");
1883                    }
1884                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1885                    ArrayList<String> pkgList = new ArrayList<>(1);
1886                    pkgList.add(packageName);
1887                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1888                }
1889            }
1890
1891            // Work that needs to happen on first install within each user
1892            if (firstUsers != null && firstUsers.length > 0) {
1893                synchronized (mPackages) {
1894                    for (int userId : firstUsers) {
1895                        // If this app is a browser and it's newly-installed for some
1896                        // users, clear any default-browser state in those users. The
1897                        // app's nature doesn't depend on the user, so we can just check
1898                        // its browser nature in any user and generalize.
1899                        if (packageIsBrowser(packageName, userId)) {
1900                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1901                        }
1902
1903                        // We may also need to apply pending (restored) runtime
1904                        // permission grants within these users.
1905                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1906                    }
1907                }
1908            }
1909
1910            // Log current value of "unknown sources" setting
1911            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1912                    getUnknownSourcesSettings());
1913
1914            // Force a gc to clear up things
1915            Runtime.getRuntime().gc();
1916
1917            // Remove the replaced package's older resources safely now
1918            // We delete after a gc for applications  on sdcard.
1919            if (res.removedInfo != null && res.removedInfo.args != null) {
1920                synchronized (mInstallLock) {
1921                    res.removedInfo.args.doPostDeleteLI(true);
1922                }
1923            }
1924        }
1925
1926        // If someone is watching installs - notify them
1927        if (installObserver != null) {
1928            try {
1929                Bundle extras = extrasForInstallResult(res);
1930                installObserver.onPackageInstalled(res.name, res.returnCode,
1931                        res.returnMsg, extras);
1932            } catch (RemoteException e) {
1933                Slog.i(TAG, "Observer no longer exists.");
1934            }
1935        }
1936    }
1937
1938    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1939            PackageParser.Package pkg) {
1940        if (pkg.parentPackage == null) {
1941            return;
1942        }
1943        if (pkg.requestedPermissions == null) {
1944            return;
1945        }
1946        final PackageSetting disabledSysParentPs = mSettings
1947                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1948        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1949                || !disabledSysParentPs.isPrivileged()
1950                || (disabledSysParentPs.childPackageNames != null
1951                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1952            return;
1953        }
1954        final int[] allUserIds = sUserManager.getUserIds();
1955        final int permCount = pkg.requestedPermissions.size();
1956        for (int i = 0; i < permCount; i++) {
1957            String permission = pkg.requestedPermissions.get(i);
1958            BasePermission bp = mSettings.mPermissions.get(permission);
1959            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1960                continue;
1961            }
1962            for (int userId : allUserIds) {
1963                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1964                        permission, userId)) {
1965                    grantRuntimePermission(pkg.packageName, permission, userId);
1966                }
1967            }
1968        }
1969    }
1970
1971    private StorageEventListener mStorageListener = new StorageEventListener() {
1972        @Override
1973        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1974            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1975                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1976                    final String volumeUuid = vol.getFsUuid();
1977
1978                    // Clean up any users or apps that were removed or recreated
1979                    // while this volume was missing
1980                    reconcileUsers(volumeUuid);
1981                    reconcileApps(volumeUuid);
1982
1983                    // Clean up any install sessions that expired or were
1984                    // cancelled while this volume was missing
1985                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1986
1987                    loadPrivatePackages(vol);
1988
1989                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1990                    unloadPrivatePackages(vol);
1991                }
1992            }
1993
1994            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1995                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1996                    updateExternalMediaStatus(true, false);
1997                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1998                    updateExternalMediaStatus(false, false);
1999                }
2000            }
2001        }
2002
2003        @Override
2004        public void onVolumeForgotten(String fsUuid) {
2005            if (TextUtils.isEmpty(fsUuid)) {
2006                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2007                return;
2008            }
2009
2010            // Remove any apps installed on the forgotten volume
2011            synchronized (mPackages) {
2012                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2013                for (PackageSetting ps : packages) {
2014                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2015                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2016                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2017                }
2018
2019                mSettings.onVolumeForgotten(fsUuid);
2020                mSettings.writeLPr();
2021            }
2022        }
2023    };
2024
2025    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2026            String[] grantedPermissions) {
2027        for (int userId : userIds) {
2028            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2029        }
2030
2031        // We could have touched GID membership, so flush out packages.list
2032        synchronized (mPackages) {
2033            mSettings.writePackageListLPr();
2034        }
2035    }
2036
2037    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2038            String[] grantedPermissions) {
2039        SettingBase sb = (SettingBase) pkg.mExtras;
2040        if (sb == null) {
2041            return;
2042        }
2043
2044        PermissionsState permissionsState = sb.getPermissionsState();
2045
2046        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2047                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2048
2049        for (String permission : pkg.requestedPermissions) {
2050            final BasePermission bp;
2051            synchronized (mPackages) {
2052                bp = mSettings.mPermissions.get(permission);
2053            }
2054            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2055                    && (grantedPermissions == null
2056                           || ArrayUtils.contains(grantedPermissions, permission))) {
2057                final int flags = permissionsState.getPermissionFlags(permission, userId);
2058                // Installer cannot change immutable permissions.
2059                if ((flags & immutableFlags) == 0) {
2060                    grantRuntimePermission(pkg.packageName, permission, userId);
2061                }
2062            }
2063        }
2064    }
2065
2066    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2067        Bundle extras = null;
2068        switch (res.returnCode) {
2069            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2070                extras = new Bundle();
2071                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2072                        res.origPermission);
2073                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2074                        res.origPackage);
2075                break;
2076            }
2077            case PackageManager.INSTALL_SUCCEEDED: {
2078                extras = new Bundle();
2079                extras.putBoolean(Intent.EXTRA_REPLACING,
2080                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2081                break;
2082            }
2083        }
2084        return extras;
2085    }
2086
2087    void scheduleWriteSettingsLocked() {
2088        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2089            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2090        }
2091    }
2092
2093    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2094        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2095        scheduleWritePackageRestrictionsLocked(userId);
2096    }
2097
2098    void scheduleWritePackageRestrictionsLocked(int userId) {
2099        final int[] userIds = (userId == UserHandle.USER_ALL)
2100                ? sUserManager.getUserIds() : new int[]{userId};
2101        for (int nextUserId : userIds) {
2102            if (!sUserManager.exists(nextUserId)) return;
2103            mDirtyUsers.add(nextUserId);
2104            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2105                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2106            }
2107        }
2108    }
2109
2110    public static PackageManagerService main(Context context, Installer installer,
2111            boolean factoryTest, boolean onlyCore) {
2112        // Self-check for initial settings.
2113        PackageManagerServiceCompilerMapping.checkProperties();
2114
2115        PackageManagerService m = new PackageManagerService(context, installer,
2116                factoryTest, onlyCore);
2117        m.enableSystemUserPackages();
2118        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2119        // disabled after already being started.
2120        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2121                UserHandle.USER_SYSTEM);
2122        ServiceManager.addService("package", m);
2123        return m;
2124    }
2125
2126    private void enableSystemUserPackages() {
2127        if (!UserManager.isSplitSystemUser()) {
2128            return;
2129        }
2130        // For system user, enable apps based on the following conditions:
2131        // - app is whitelisted or belong to one of these groups:
2132        //   -- system app which has no launcher icons
2133        //   -- system app which has INTERACT_ACROSS_USERS permission
2134        //   -- system IME app
2135        // - app is not in the blacklist
2136        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2137        Set<String> enableApps = new ArraySet<>();
2138        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2139                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2140                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2141        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2142        enableApps.addAll(wlApps);
2143        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2144                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2145        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2146        enableApps.removeAll(blApps);
2147        Log.i(TAG, "Applications installed for system user: " + enableApps);
2148        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2149                UserHandle.SYSTEM);
2150        final int allAppsSize = allAps.size();
2151        synchronized (mPackages) {
2152            for (int i = 0; i < allAppsSize; i++) {
2153                String pName = allAps.get(i);
2154                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2155                // Should not happen, but we shouldn't be failing if it does
2156                if (pkgSetting == null) {
2157                    continue;
2158                }
2159                boolean install = enableApps.contains(pName);
2160                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2161                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2162                            + " for system user");
2163                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2164                }
2165            }
2166        }
2167    }
2168
2169    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2170        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2171                Context.DISPLAY_SERVICE);
2172        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2173    }
2174
2175    public PackageManagerService(Context context, Installer installer,
2176            boolean factoryTest, boolean onlyCore) {
2177        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2178                SystemClock.uptimeMillis());
2179
2180        if (mSdkVersion <= 0) {
2181            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2182        }
2183
2184        mContext = context;
2185        mFactoryTest = factoryTest;
2186        mOnlyCore = onlyCore;
2187        mMetrics = new DisplayMetrics();
2188        mSettings = new Settings(mPackages);
2189        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2190                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2191        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2192                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2193        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2194                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2195        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2196                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2197        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2198                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2199        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2200                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2201
2202        String separateProcesses = SystemProperties.get("debug.separate_processes");
2203        if (separateProcesses != null && separateProcesses.length() > 0) {
2204            if ("*".equals(separateProcesses)) {
2205                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2206                mSeparateProcesses = null;
2207                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2208            } else {
2209                mDefParseFlags = 0;
2210                mSeparateProcesses = separateProcesses.split(",");
2211                Slog.w(TAG, "Running with debug.separate_processes: "
2212                        + separateProcesses);
2213            }
2214        } else {
2215            mDefParseFlags = 0;
2216            mSeparateProcesses = null;
2217        }
2218
2219        mInstaller = installer;
2220        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2221                "*dexopt*");
2222        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2223
2224        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2225                FgThread.get().getLooper());
2226
2227        getDefaultDisplayMetrics(context, mMetrics);
2228
2229        SystemConfig systemConfig = SystemConfig.getInstance();
2230        mGlobalGids = systemConfig.getGlobalGids();
2231        mSystemPermissions = systemConfig.getSystemPermissions();
2232        mAvailableFeatures = systemConfig.getAvailableFeatures();
2233
2234        synchronized (mInstallLock) {
2235        // writer
2236        synchronized (mPackages) {
2237            mHandlerThread = new ServiceThread(TAG,
2238                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2239            mHandlerThread.start();
2240            mHandler = new PackageHandler(mHandlerThread.getLooper());
2241            mProcessLoggingHandler = new ProcessLoggingHandler();
2242            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2243
2244            File dataDir = Environment.getDataDirectory();
2245            mAppInstallDir = new File(dataDir, "app");
2246            mAppLib32InstallDir = new File(dataDir, "app-lib");
2247            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2248            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2249            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2250
2251            sUserManager = new UserManagerService(context, this, mPackages);
2252
2253            // Propagate permission configuration in to package manager.
2254            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2255                    = systemConfig.getPermissions();
2256            for (int i=0; i<permConfig.size(); i++) {
2257                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2258                BasePermission bp = mSettings.mPermissions.get(perm.name);
2259                if (bp == null) {
2260                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2261                    mSettings.mPermissions.put(perm.name, bp);
2262                }
2263                if (perm.gids != null) {
2264                    bp.setGids(perm.gids, perm.perUser);
2265                }
2266            }
2267
2268            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2269            for (int i=0; i<libConfig.size(); i++) {
2270                mSharedLibraries.put(libConfig.keyAt(i),
2271                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2272            }
2273
2274            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2275
2276            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2277
2278            String customResolverActivity = Resources.getSystem().getString(
2279                    R.string.config_customResolverActivity);
2280            if (TextUtils.isEmpty(customResolverActivity)) {
2281                customResolverActivity = null;
2282            } else {
2283                mCustomResolverComponentName = ComponentName.unflattenFromString(
2284                        customResolverActivity);
2285            }
2286
2287            long startTime = SystemClock.uptimeMillis();
2288
2289            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2290                    startTime);
2291
2292            // Set flag to monitor and not change apk file paths when
2293            // scanning install directories.
2294            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2295
2296            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2297            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2298
2299            if (bootClassPath == null) {
2300                Slog.w(TAG, "No BOOTCLASSPATH found!");
2301            }
2302
2303            if (systemServerClassPath == null) {
2304                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2305            }
2306
2307            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2308            final String[] dexCodeInstructionSets =
2309                    getDexCodeInstructionSets(
2310                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2311
2312            /**
2313             * Ensure all external libraries have had dexopt run on them.
2314             */
2315            if (mSharedLibraries.size() > 0) {
2316                // NOTE: For now, we're compiling these system "shared libraries"
2317                // (and framework jars) into all available architectures. It's possible
2318                // to compile them only when we come across an app that uses them (there's
2319                // already logic for that in scanPackageLI) but that adds some complexity.
2320                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2321                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2322                        final String lib = libEntry.path;
2323                        if (lib == null) {
2324                            continue;
2325                        }
2326
2327                        try {
2328                            // Shared libraries do not have profiles so we perform a full
2329                            // AOT compilation (if needed).
2330                            int dexoptNeeded = DexFile.getDexOptNeeded(
2331                                    lib, dexCodeInstructionSet,
2332                                    getCompilerFilterForReason(REASON_SHARED_APK),
2333                                    false /* newProfile */);
2334                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2335                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2336                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2337                                        getCompilerFilterForReason(REASON_SHARED_APK),
2338                                        StorageManager.UUID_PRIVATE_INTERNAL,
2339                                        SPECIAL_SHARED_LIBRARY);
2340                            }
2341                        } catch (FileNotFoundException e) {
2342                            Slog.w(TAG, "Library not found: " + lib);
2343                        } catch (IOException | InstallerException e) {
2344                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2345                                    + e.getMessage());
2346                        }
2347                    }
2348                }
2349            }
2350
2351            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2352
2353            final VersionInfo ver = mSettings.getInternalVersion();
2354            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2355
2356            // when upgrading from pre-M, promote system app permissions from install to runtime
2357            mPromoteSystemApps =
2358                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2359
2360            // save off the names of pre-existing system packages prior to scanning; we don't
2361            // want to automatically grant runtime permissions for new system apps
2362            if (mPromoteSystemApps) {
2363                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2364                while (pkgSettingIter.hasNext()) {
2365                    PackageSetting ps = pkgSettingIter.next();
2366                    if (isSystemApp(ps)) {
2367                        mExistingSystemPackages.add(ps.name);
2368                    }
2369                }
2370            }
2371
2372            // When upgrading from pre-N, we need to handle package extraction like first boot,
2373            // as there is no profiling data available.
2374            mIsPreNUpgrade = !mSettings.isNWorkDone();
2375            mSettings.setNWorkDone();
2376
2377            // Collect vendor overlay packages.
2378            // (Do this before scanning any apps.)
2379            // For security and version matching reason, only consider
2380            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2381            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2382            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2383                    | PackageParser.PARSE_IS_SYSTEM
2384                    | PackageParser.PARSE_IS_SYSTEM_DIR
2385                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2386
2387            // Find base frameworks (resource packages without code).
2388            scanDirTracedLI(frameworkDir, mDefParseFlags
2389                    | PackageParser.PARSE_IS_SYSTEM
2390                    | PackageParser.PARSE_IS_SYSTEM_DIR
2391                    | PackageParser.PARSE_IS_PRIVILEGED,
2392                    scanFlags | SCAN_NO_DEX, 0);
2393
2394            // Collected privileged system packages.
2395            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2396            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2397                    | PackageParser.PARSE_IS_SYSTEM
2398                    | PackageParser.PARSE_IS_SYSTEM_DIR
2399                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2400
2401            // Collect ordinary system packages.
2402            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2403            scanDirTracedLI(systemAppDir, mDefParseFlags
2404                    | PackageParser.PARSE_IS_SYSTEM
2405                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2406
2407            // Collect all vendor packages.
2408            File vendorAppDir = new File("/vendor/app");
2409            try {
2410                vendorAppDir = vendorAppDir.getCanonicalFile();
2411            } catch (IOException e) {
2412                // failed to look up canonical path, continue with original one
2413            }
2414            scanDirTracedLI(vendorAppDir, mDefParseFlags
2415                    | PackageParser.PARSE_IS_SYSTEM
2416                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2417
2418            // Collect all OEM packages.
2419            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2420            scanDirTracedLI(oemAppDir, mDefParseFlags
2421                    | PackageParser.PARSE_IS_SYSTEM
2422                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2423
2424            // Prune any system packages that no longer exist.
2425            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2426            if (!mOnlyCore) {
2427                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2428                while (psit.hasNext()) {
2429                    PackageSetting ps = psit.next();
2430
2431                    /*
2432                     * If this is not a system app, it can't be a
2433                     * disable system app.
2434                     */
2435                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2436                        continue;
2437                    }
2438
2439                    /*
2440                     * If the package is scanned, it's not erased.
2441                     */
2442                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2443                    if (scannedPkg != null) {
2444                        /*
2445                         * If the system app is both scanned and in the
2446                         * disabled packages list, then it must have been
2447                         * added via OTA. Remove it from the currently
2448                         * scanned package so the previously user-installed
2449                         * application can be scanned.
2450                         */
2451                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2452                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2453                                    + ps.name + "; removing system app.  Last known codePath="
2454                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2455                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2456                                    + scannedPkg.mVersionCode);
2457                            removePackageLI(scannedPkg, true);
2458                            mExpectingBetter.put(ps.name, ps.codePath);
2459                        }
2460
2461                        continue;
2462                    }
2463
2464                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2465                        psit.remove();
2466                        logCriticalInfo(Log.WARN, "System package " + ps.name
2467                                + " no longer exists; it's data will be wiped");
2468                        // Actual deletion of code and data will be handled by later
2469                        // reconciliation step
2470                    } else {
2471                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2472                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2473                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2474                        }
2475                    }
2476                }
2477            }
2478
2479            //look for any incomplete package installations
2480            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2481            for (int i = 0; i < deletePkgsList.size(); i++) {
2482                // Actual deletion of code and data will be handled by later
2483                // reconciliation step
2484                final String packageName = deletePkgsList.get(i).name;
2485                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2486                synchronized (mPackages) {
2487                    mSettings.removePackageLPw(packageName);
2488                }
2489            }
2490
2491            //delete tmp files
2492            deleteTempPackageFiles();
2493
2494            // Remove any shared userIDs that have no associated packages
2495            mSettings.pruneSharedUsersLPw();
2496
2497            if (!mOnlyCore) {
2498                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2499                        SystemClock.uptimeMillis());
2500                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2501
2502                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2503                        | PackageParser.PARSE_FORWARD_LOCK,
2504                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2505
2506                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2507                        | PackageParser.PARSE_IS_EPHEMERAL,
2508                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2509
2510                /**
2511                 * Remove disable package settings for any updated system
2512                 * apps that were removed via an OTA. If they're not a
2513                 * previously-updated app, remove them completely.
2514                 * Otherwise, just revoke their system-level permissions.
2515                 */
2516                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2517                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2518                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2519
2520                    String msg;
2521                    if (deletedPkg == null) {
2522                        msg = "Updated system package " + deletedAppName
2523                                + " no longer exists; it's data will be wiped";
2524                        // Actual deletion of code and data will be handled by later
2525                        // reconciliation step
2526                    } else {
2527                        msg = "Updated system app + " + deletedAppName
2528                                + " no longer present; removing system privileges for "
2529                                + deletedAppName;
2530
2531                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2532
2533                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2534                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2535                    }
2536                    logCriticalInfo(Log.WARN, msg);
2537                }
2538
2539                /**
2540                 * Make sure all system apps that we expected to appear on
2541                 * the userdata partition actually showed up. If they never
2542                 * appeared, crawl back and revive the system version.
2543                 */
2544                for (int i = 0; i < mExpectingBetter.size(); i++) {
2545                    final String packageName = mExpectingBetter.keyAt(i);
2546                    if (!mPackages.containsKey(packageName)) {
2547                        final File scanFile = mExpectingBetter.valueAt(i);
2548
2549                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2550                                + " but never showed up; reverting to system");
2551
2552                        int reparseFlags = mDefParseFlags;
2553                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2554                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2555                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2556                                    | PackageParser.PARSE_IS_PRIVILEGED;
2557                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2558                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2559                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2560                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2561                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2562                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2563                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2564                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2565                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2566                        } else {
2567                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2568                            continue;
2569                        }
2570
2571                        mSettings.enableSystemPackageLPw(packageName);
2572
2573                        try {
2574                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2575                        } catch (PackageManagerException e) {
2576                            Slog.e(TAG, "Failed to parse original system package: "
2577                                    + e.getMessage());
2578                        }
2579                    }
2580                }
2581            }
2582            mExpectingBetter.clear();
2583
2584            // Resolve protected action filters. Only the setup wizard is allowed to
2585            // have a high priority filter for these actions.
2586            mSetupWizardPackage = getSetupWizardPackageName();
2587            if (mProtectedFilters.size() > 0) {
2588                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2589                    Slog.i(TAG, "No setup wizard;"
2590                        + " All protected intents capped to priority 0");
2591                }
2592                for (ActivityIntentInfo filter : mProtectedFilters) {
2593                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2594                        if (DEBUG_FILTERS) {
2595                            Slog.i(TAG, "Found setup wizard;"
2596                                + " allow priority " + filter.getPriority() + ";"
2597                                + " package: " + filter.activity.info.packageName
2598                                + " activity: " + filter.activity.className
2599                                + " priority: " + filter.getPriority());
2600                        }
2601                        // skip setup wizard; allow it to keep the high priority filter
2602                        continue;
2603                    }
2604                    Slog.w(TAG, "Protected action; cap priority to 0;"
2605                            + " package: " + filter.activity.info.packageName
2606                            + " activity: " + filter.activity.className
2607                            + " origPrio: " + filter.getPriority());
2608                    filter.setPriority(0);
2609                }
2610            }
2611            mDeferProtectedFilters = false;
2612            mProtectedFilters.clear();
2613
2614            // Now that we know all of the shared libraries, update all clients to have
2615            // the correct library paths.
2616            updateAllSharedLibrariesLPw();
2617
2618            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2619                // NOTE: We ignore potential failures here during a system scan (like
2620                // the rest of the commands above) because there's precious little we
2621                // can do about it. A settings error is reported, though.
2622                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2623                        false /* boot complete */);
2624            }
2625
2626            // Now that we know all the packages we are keeping,
2627            // read and update their last usage times.
2628            mPackageUsage.readLP();
2629
2630            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2631                    SystemClock.uptimeMillis());
2632            Slog.i(TAG, "Time to scan packages: "
2633                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2634                    + " seconds");
2635
2636            // If the platform SDK has changed since the last time we booted,
2637            // we need to re-grant app permission to catch any new ones that
2638            // appear.  This is really a hack, and means that apps can in some
2639            // cases get permissions that the user didn't initially explicitly
2640            // allow...  it would be nice to have some better way to handle
2641            // this situation.
2642            int updateFlags = UPDATE_PERMISSIONS_ALL;
2643            if (ver.sdkVersion != mSdkVersion) {
2644                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2645                        + mSdkVersion + "; regranting permissions for internal storage");
2646                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2647            }
2648            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2649            ver.sdkVersion = mSdkVersion;
2650
2651            // If this is the first boot or an update from pre-M, and it is a normal
2652            // boot, then we need to initialize the default preferred apps across
2653            // all defined users.
2654            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2655                for (UserInfo user : sUserManager.getUsers(true)) {
2656                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2657                    applyFactoryDefaultBrowserLPw(user.id);
2658                    primeDomainVerificationsLPw(user.id);
2659                }
2660            }
2661
2662            // Prepare storage for system user really early during boot,
2663            // since core system apps like SettingsProvider and SystemUI
2664            // can't wait for user to start
2665            final int storageFlags;
2666            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2667                storageFlags = StorageManager.FLAG_STORAGE_DE;
2668            } else {
2669                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2670            }
2671            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2672                    storageFlags);
2673
2674            // If this is first boot after an OTA, and a normal boot, then
2675            // we need to clear code cache directories.
2676            if (mIsUpgrade && !onlyCore) {
2677                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2678                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2679                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2680                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2681                        // No apps are running this early, so no need to freeze
2682                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2683                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2684                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2685                    }
2686                    clearAppProfilesLIF(ps.pkg);
2687                }
2688                ver.fingerprint = Build.FINGERPRINT;
2689            }
2690
2691            checkDefaultBrowser();
2692
2693            // clear only after permissions and other defaults have been updated
2694            mExistingSystemPackages.clear();
2695            mPromoteSystemApps = false;
2696
2697            // All the changes are done during package scanning.
2698            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2699
2700            // can downgrade to reader
2701            mSettings.writeLPr();
2702
2703            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2704                    SystemClock.uptimeMillis());
2705
2706            if (!mOnlyCore) {
2707                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2708                mRequiredInstallerPackage = getRequiredInstallerLPr();
2709                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2710                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2711                        mIntentFilterVerifierComponent);
2712                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2713                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2714                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2715                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2716            } else {
2717                mRequiredVerifierPackage = null;
2718                mRequiredInstallerPackage = null;
2719                mIntentFilterVerifierComponent = null;
2720                mIntentFilterVerifier = null;
2721                mServicesSystemSharedLibraryPackageName = null;
2722                mSharedSystemSharedLibraryPackageName = null;
2723            }
2724
2725            mInstallerService = new PackageInstallerService(context, this);
2726
2727            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2728            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2729            // both the installer and resolver must be present to enable ephemeral
2730            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2731                if (DEBUG_EPHEMERAL) {
2732                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2733                            + " installer:" + ephemeralInstallerComponent);
2734                }
2735                mEphemeralResolverComponent = ephemeralResolverComponent;
2736                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2737                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2738                mEphemeralResolverConnection =
2739                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2740            } else {
2741                if (DEBUG_EPHEMERAL) {
2742                    final String missingComponent =
2743                            (ephemeralResolverComponent == null)
2744                            ? (ephemeralInstallerComponent == null)
2745                                    ? "resolver and installer"
2746                                    : "resolver"
2747                            : "installer";
2748                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2749                }
2750                mEphemeralResolverComponent = null;
2751                mEphemeralInstallerComponent = null;
2752                mEphemeralResolverConnection = null;
2753            }
2754
2755            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2756        } // synchronized (mPackages)
2757        } // synchronized (mInstallLock)
2758
2759        // Now after opening every single application zip, make sure they
2760        // are all flushed.  Not really needed, but keeps things nice and
2761        // tidy.
2762        Runtime.getRuntime().gc();
2763
2764        // The initial scanning above does many calls into installd while
2765        // holding the mPackages lock, but we're mostly interested in yelling
2766        // once we have a booted system.
2767        mInstaller.setWarnIfHeld(mPackages);
2768
2769        // Expose private service for system components to use.
2770        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2771    }
2772
2773    @Override
2774    public boolean isFirstBoot() {
2775        return !mRestoredSettings;
2776    }
2777
2778    @Override
2779    public boolean isOnlyCoreApps() {
2780        return mOnlyCore;
2781    }
2782
2783    @Override
2784    public boolean isUpgrade() {
2785        return mIsUpgrade;
2786    }
2787
2788    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2789        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2790
2791        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2792                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2793                UserHandle.USER_SYSTEM);
2794        if (matches.size() == 1) {
2795            return matches.get(0).getComponentInfo().packageName;
2796        } else {
2797            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2798            return null;
2799        }
2800    }
2801
2802    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2803        synchronized (mPackages) {
2804            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2805            if (libraryEntry == null) {
2806                throw new IllegalStateException("Missing required shared library:" + libraryName);
2807            }
2808            return libraryEntry.apk;
2809        }
2810    }
2811
2812    private @NonNull String getRequiredInstallerLPr() {
2813        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2814        intent.addCategory(Intent.CATEGORY_DEFAULT);
2815        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2816
2817        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2818                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2819                UserHandle.USER_SYSTEM);
2820        if (matches.size() == 1) {
2821            ResolveInfo resolveInfo = matches.get(0);
2822            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2823                throw new RuntimeException("The installer must be a privileged app");
2824            }
2825            return matches.get(0).getComponentInfo().packageName;
2826        } else {
2827            throw new RuntimeException("There must be exactly one installer; found " + matches);
2828        }
2829    }
2830
2831    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2832        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2833
2834        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2835                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2836                UserHandle.USER_SYSTEM);
2837        ResolveInfo best = null;
2838        final int N = matches.size();
2839        for (int i = 0; i < N; i++) {
2840            final ResolveInfo cur = matches.get(i);
2841            final String packageName = cur.getComponentInfo().packageName;
2842            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2843                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2844                continue;
2845            }
2846
2847            if (best == null || cur.priority > best.priority) {
2848                best = cur;
2849            }
2850        }
2851
2852        if (best != null) {
2853            return best.getComponentInfo().getComponentName();
2854        } else {
2855            throw new RuntimeException("There must be at least one intent filter verifier");
2856        }
2857    }
2858
2859    private @Nullable ComponentName getEphemeralResolverLPr() {
2860        final String[] packageArray =
2861                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2862        if (packageArray.length == 0) {
2863            if (DEBUG_EPHEMERAL) {
2864                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2865            }
2866            return null;
2867        }
2868
2869        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2870        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2871                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2872                UserHandle.USER_SYSTEM);
2873
2874        final int N = resolvers.size();
2875        if (N == 0) {
2876            if (DEBUG_EPHEMERAL) {
2877                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2878            }
2879            return null;
2880        }
2881
2882        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2883        for (int i = 0; i < N; i++) {
2884            final ResolveInfo info = resolvers.get(i);
2885
2886            if (info.serviceInfo == null) {
2887                continue;
2888            }
2889
2890            final String packageName = info.serviceInfo.packageName;
2891            if (!possiblePackages.contains(packageName)) {
2892                if (DEBUG_EPHEMERAL) {
2893                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2894                            + " pkg: " + packageName + ", info:" + info);
2895                }
2896                continue;
2897            }
2898
2899            if (DEBUG_EPHEMERAL) {
2900                Slog.v(TAG, "Ephemeral resolver found;"
2901                        + " pkg: " + packageName + ", info:" + info);
2902            }
2903            return new ComponentName(packageName, info.serviceInfo.name);
2904        }
2905        if (DEBUG_EPHEMERAL) {
2906            Slog.v(TAG, "Ephemeral resolver NOT found");
2907        }
2908        return null;
2909    }
2910
2911    private @Nullable ComponentName getEphemeralInstallerLPr() {
2912        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2913        intent.addCategory(Intent.CATEGORY_DEFAULT);
2914        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2915
2916        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2917                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2918                UserHandle.USER_SYSTEM);
2919        if (matches.size() == 0) {
2920            return null;
2921        } else if (matches.size() == 1) {
2922            return matches.get(0).getComponentInfo().getComponentName();
2923        } else {
2924            throw new RuntimeException(
2925                    "There must be at most one ephemeral installer; found " + matches);
2926        }
2927    }
2928
2929    private void primeDomainVerificationsLPw(int userId) {
2930        if (DEBUG_DOMAIN_VERIFICATION) {
2931            Slog.d(TAG, "Priming domain verifications in user " + userId);
2932        }
2933
2934        SystemConfig systemConfig = SystemConfig.getInstance();
2935        ArraySet<String> packages = systemConfig.getLinkedApps();
2936        ArraySet<String> domains = new ArraySet<String>();
2937
2938        for (String packageName : packages) {
2939            PackageParser.Package pkg = mPackages.get(packageName);
2940            if (pkg != null) {
2941                if (!pkg.isSystemApp()) {
2942                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2943                    continue;
2944                }
2945
2946                domains.clear();
2947                for (PackageParser.Activity a : pkg.activities) {
2948                    for (ActivityIntentInfo filter : a.intents) {
2949                        if (hasValidDomains(filter)) {
2950                            domains.addAll(filter.getHostsList());
2951                        }
2952                    }
2953                }
2954
2955                if (domains.size() > 0) {
2956                    if (DEBUG_DOMAIN_VERIFICATION) {
2957                        Slog.v(TAG, "      + " + packageName);
2958                    }
2959                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2960                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2961                    // and then 'always' in the per-user state actually used for intent resolution.
2962                    final IntentFilterVerificationInfo ivi;
2963                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2964                            new ArrayList<String>(domains));
2965                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2966                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2967                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2968                } else {
2969                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2970                            + "' does not handle web links");
2971                }
2972            } else {
2973                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2974            }
2975        }
2976
2977        scheduleWritePackageRestrictionsLocked(userId);
2978        scheduleWriteSettingsLocked();
2979    }
2980
2981    private void applyFactoryDefaultBrowserLPw(int userId) {
2982        // The default browser app's package name is stored in a string resource,
2983        // with a product-specific overlay used for vendor customization.
2984        String browserPkg = mContext.getResources().getString(
2985                com.android.internal.R.string.default_browser);
2986        if (!TextUtils.isEmpty(browserPkg)) {
2987            // non-empty string => required to be a known package
2988            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2989            if (ps == null) {
2990                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2991                browserPkg = null;
2992            } else {
2993                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2994            }
2995        }
2996
2997        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2998        // default.  If there's more than one, just leave everything alone.
2999        if (browserPkg == null) {
3000            calculateDefaultBrowserLPw(userId);
3001        }
3002    }
3003
3004    private void calculateDefaultBrowserLPw(int userId) {
3005        List<String> allBrowsers = resolveAllBrowserApps(userId);
3006        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3007        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3008    }
3009
3010    private List<String> resolveAllBrowserApps(int userId) {
3011        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3012        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3013                PackageManager.MATCH_ALL, userId);
3014
3015        final int count = list.size();
3016        List<String> result = new ArrayList<String>(count);
3017        for (int i=0; i<count; i++) {
3018            ResolveInfo info = list.get(i);
3019            if (info.activityInfo == null
3020                    || !info.handleAllWebDataURI
3021                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3022                    || result.contains(info.activityInfo.packageName)) {
3023                continue;
3024            }
3025            result.add(info.activityInfo.packageName);
3026        }
3027
3028        return result;
3029    }
3030
3031    private boolean packageIsBrowser(String packageName, int userId) {
3032        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3033                PackageManager.MATCH_ALL, userId);
3034        final int N = list.size();
3035        for (int i = 0; i < N; i++) {
3036            ResolveInfo info = list.get(i);
3037            if (packageName.equals(info.activityInfo.packageName)) {
3038                return true;
3039            }
3040        }
3041        return false;
3042    }
3043
3044    private void checkDefaultBrowser() {
3045        final int myUserId = UserHandle.myUserId();
3046        final String packageName = getDefaultBrowserPackageName(myUserId);
3047        if (packageName != null) {
3048            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3049            if (info == null) {
3050                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3051                synchronized (mPackages) {
3052                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3053                }
3054            }
3055        }
3056    }
3057
3058    @Override
3059    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3060            throws RemoteException {
3061        try {
3062            return super.onTransact(code, data, reply, flags);
3063        } catch (RuntimeException e) {
3064            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3065                Slog.wtf(TAG, "Package Manager Crash", e);
3066            }
3067            throw e;
3068        }
3069    }
3070
3071    static int[] appendInts(int[] cur, int[] add) {
3072        if (add == null) return cur;
3073        if (cur == null) return add;
3074        final int N = add.length;
3075        for (int i=0; i<N; i++) {
3076            cur = appendInt(cur, add[i]);
3077        }
3078        return cur;
3079    }
3080
3081    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3082        if (!sUserManager.exists(userId)) return null;
3083        if (ps == null) {
3084            return null;
3085        }
3086        final PackageParser.Package p = ps.pkg;
3087        if (p == null) {
3088            return null;
3089        }
3090
3091        final PermissionsState permissionsState = ps.getPermissionsState();
3092
3093        final int[] gids = permissionsState.computeGids(userId);
3094        final Set<String> permissions = permissionsState.getPermissions(userId);
3095        final PackageUserState state = ps.readUserState(userId);
3096
3097        return PackageParser.generatePackageInfo(p, gids, flags,
3098                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3099    }
3100
3101    @Override
3102    public void checkPackageStartable(String packageName, int userId) {
3103        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3104
3105        synchronized (mPackages) {
3106            final PackageSetting ps = mSettings.mPackages.get(packageName);
3107            if (ps == null) {
3108                throw new SecurityException("Package " + packageName + " was not found!");
3109            }
3110
3111            if (!ps.getInstalled(userId)) {
3112                throw new SecurityException(
3113                        "Package " + packageName + " was not installed for user " + userId + "!");
3114            }
3115
3116            if (mSafeMode && !ps.isSystem()) {
3117                throw new SecurityException("Package " + packageName + " not a system app!");
3118            }
3119
3120            if (mFrozenPackages.contains(packageName)) {
3121                throw new SecurityException("Package " + packageName + " is currently frozen!");
3122            }
3123
3124            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3125                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3126                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3127            }
3128        }
3129    }
3130
3131    @Override
3132    public boolean isPackageAvailable(String packageName, int userId) {
3133        if (!sUserManager.exists(userId)) return false;
3134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3135                false /* requireFullPermission */, false /* checkShell */, "is package available");
3136        synchronized (mPackages) {
3137            PackageParser.Package p = mPackages.get(packageName);
3138            if (p != null) {
3139                final PackageSetting ps = (PackageSetting) p.mExtras;
3140                if (ps != null) {
3141                    final PackageUserState state = ps.readUserState(userId);
3142                    if (state != null) {
3143                        return PackageParser.isAvailable(state);
3144                    }
3145                }
3146            }
3147        }
3148        return false;
3149    }
3150
3151    @Override
3152    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3153        if (!sUserManager.exists(userId)) return null;
3154        flags = updateFlagsForPackage(flags, userId, packageName);
3155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3156                false /* requireFullPermission */, false /* checkShell */, "get package info");
3157        // reader
3158        synchronized (mPackages) {
3159            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3160            PackageParser.Package p = null;
3161            if (matchFactoryOnly) {
3162                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3163                if (ps != null) {
3164                    return generatePackageInfo(ps, flags, userId);
3165                }
3166            }
3167            if (p == null) {
3168                p = mPackages.get(packageName);
3169                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3170                    return null;
3171                }
3172            }
3173            if (DEBUG_PACKAGE_INFO)
3174                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3175            if (p != null) {
3176                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3177            }
3178            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3179                final PackageSetting ps = mSettings.mPackages.get(packageName);
3180                return generatePackageInfo(ps, flags, userId);
3181            }
3182        }
3183        return null;
3184    }
3185
3186    @Override
3187    public String[] currentToCanonicalPackageNames(String[] names) {
3188        String[] out = new String[names.length];
3189        // reader
3190        synchronized (mPackages) {
3191            for (int i=names.length-1; i>=0; i--) {
3192                PackageSetting ps = mSettings.mPackages.get(names[i]);
3193                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3194            }
3195        }
3196        return out;
3197    }
3198
3199    @Override
3200    public String[] canonicalToCurrentPackageNames(String[] names) {
3201        String[] out = new String[names.length];
3202        // reader
3203        synchronized (mPackages) {
3204            for (int i=names.length-1; i>=0; i--) {
3205                String cur = mSettings.mRenamedPackages.get(names[i]);
3206                out[i] = cur != null ? cur : names[i];
3207            }
3208        }
3209        return out;
3210    }
3211
3212    @Override
3213    public int getPackageUid(String packageName, int flags, int userId) {
3214        if (!sUserManager.exists(userId)) return -1;
3215        flags = updateFlagsForPackage(flags, userId, packageName);
3216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3217                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3218
3219        // reader
3220        synchronized (mPackages) {
3221            final PackageParser.Package p = mPackages.get(packageName);
3222            if (p != null && p.isMatch(flags)) {
3223                return UserHandle.getUid(userId, p.applicationInfo.uid);
3224            }
3225            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3226                final PackageSetting ps = mSettings.mPackages.get(packageName);
3227                if (ps != null && ps.isMatch(flags)) {
3228                    return UserHandle.getUid(userId, ps.appId);
3229                }
3230            }
3231        }
3232
3233        return -1;
3234    }
3235
3236    @Override
3237    public int[] getPackageGids(String packageName, int flags, int userId) {
3238        if (!sUserManager.exists(userId)) return null;
3239        flags = updateFlagsForPackage(flags, userId, packageName);
3240        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3241                false /* requireFullPermission */, false /* checkShell */,
3242                "getPackageGids");
3243
3244        // reader
3245        synchronized (mPackages) {
3246            final PackageParser.Package p = mPackages.get(packageName);
3247            if (p != null && p.isMatch(flags)) {
3248                PackageSetting ps = (PackageSetting) p.mExtras;
3249                return ps.getPermissionsState().computeGids(userId);
3250            }
3251            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3252                final PackageSetting ps = mSettings.mPackages.get(packageName);
3253                if (ps != null && ps.isMatch(flags)) {
3254                    return ps.getPermissionsState().computeGids(userId);
3255                }
3256            }
3257        }
3258
3259        return null;
3260    }
3261
3262    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3263        if (bp.perm != null) {
3264            return PackageParser.generatePermissionInfo(bp.perm, flags);
3265        }
3266        PermissionInfo pi = new PermissionInfo();
3267        pi.name = bp.name;
3268        pi.packageName = bp.sourcePackage;
3269        pi.nonLocalizedLabel = bp.name;
3270        pi.protectionLevel = bp.protectionLevel;
3271        return pi;
3272    }
3273
3274    @Override
3275    public PermissionInfo getPermissionInfo(String name, int flags) {
3276        // reader
3277        synchronized (mPackages) {
3278            final BasePermission p = mSettings.mPermissions.get(name);
3279            if (p != null) {
3280                return generatePermissionInfo(p, flags);
3281            }
3282            return null;
3283        }
3284    }
3285
3286    @Override
3287    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3288            int flags) {
3289        // reader
3290        synchronized (mPackages) {
3291            if (group != null && !mPermissionGroups.containsKey(group)) {
3292                // This is thrown as NameNotFoundException
3293                return null;
3294            }
3295
3296            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3297            for (BasePermission p : mSettings.mPermissions.values()) {
3298                if (group == null) {
3299                    if (p.perm == null || p.perm.info.group == null) {
3300                        out.add(generatePermissionInfo(p, flags));
3301                    }
3302                } else {
3303                    if (p.perm != null && group.equals(p.perm.info.group)) {
3304                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3305                    }
3306                }
3307            }
3308            return new ParceledListSlice<>(out);
3309        }
3310    }
3311
3312    @Override
3313    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3314        // reader
3315        synchronized (mPackages) {
3316            return PackageParser.generatePermissionGroupInfo(
3317                    mPermissionGroups.get(name), flags);
3318        }
3319    }
3320
3321    @Override
3322    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3323        // reader
3324        synchronized (mPackages) {
3325            final int N = mPermissionGroups.size();
3326            ArrayList<PermissionGroupInfo> out
3327                    = new ArrayList<PermissionGroupInfo>(N);
3328            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3329                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3330            }
3331            return new ParceledListSlice<>(out);
3332        }
3333    }
3334
3335    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3336            int userId) {
3337        if (!sUserManager.exists(userId)) return null;
3338        PackageSetting ps = mSettings.mPackages.get(packageName);
3339        if (ps != null) {
3340            if (ps.pkg == null) {
3341                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3342                if (pInfo != null) {
3343                    return pInfo.applicationInfo;
3344                }
3345                return null;
3346            }
3347            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3348                    ps.readUserState(userId), userId);
3349        }
3350        return null;
3351    }
3352
3353    @Override
3354    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3355        if (!sUserManager.exists(userId)) return null;
3356        flags = updateFlagsForApplication(flags, userId, packageName);
3357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3358                false /* requireFullPermission */, false /* checkShell */, "get application info");
3359        // writer
3360        synchronized (mPackages) {
3361            PackageParser.Package p = mPackages.get(packageName);
3362            if (DEBUG_PACKAGE_INFO) Log.v(
3363                    TAG, "getApplicationInfo " + packageName
3364                    + ": " + p);
3365            if (p != null) {
3366                PackageSetting ps = mSettings.mPackages.get(packageName);
3367                if (ps == null) return null;
3368                // Note: isEnabledLP() does not apply here - always return info
3369                return PackageParser.generateApplicationInfo(
3370                        p, flags, ps.readUserState(userId), userId);
3371            }
3372            if ("android".equals(packageName)||"system".equals(packageName)) {
3373                return mAndroidApplication;
3374            }
3375            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3376                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3377            }
3378        }
3379        return null;
3380    }
3381
3382    @Override
3383    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3384            final IPackageDataObserver observer) {
3385        mContext.enforceCallingOrSelfPermission(
3386                android.Manifest.permission.CLEAR_APP_CACHE, null);
3387        // Queue up an async operation since clearing cache may take a little while.
3388        mHandler.post(new Runnable() {
3389            public void run() {
3390                mHandler.removeCallbacks(this);
3391                boolean success = true;
3392                synchronized (mInstallLock) {
3393                    try {
3394                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3395                    } catch (InstallerException e) {
3396                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3397                        success = false;
3398                    }
3399                }
3400                if (observer != null) {
3401                    try {
3402                        observer.onRemoveCompleted(null, success);
3403                    } catch (RemoteException e) {
3404                        Slog.w(TAG, "RemoveException when invoking call back");
3405                    }
3406                }
3407            }
3408        });
3409    }
3410
3411    @Override
3412    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3413            final IntentSender pi) {
3414        mContext.enforceCallingOrSelfPermission(
3415                android.Manifest.permission.CLEAR_APP_CACHE, null);
3416        // Queue up an async operation since clearing cache may take a little while.
3417        mHandler.post(new Runnable() {
3418            public void run() {
3419                mHandler.removeCallbacks(this);
3420                boolean success = true;
3421                synchronized (mInstallLock) {
3422                    try {
3423                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3424                    } catch (InstallerException e) {
3425                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3426                        success = false;
3427                    }
3428                }
3429                if(pi != null) {
3430                    try {
3431                        // Callback via pending intent
3432                        int code = success ? 1 : 0;
3433                        pi.sendIntent(null, code, null,
3434                                null, null);
3435                    } catch (SendIntentException e1) {
3436                        Slog.i(TAG, "Failed to send pending intent");
3437                    }
3438                }
3439            }
3440        });
3441    }
3442
3443    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3444        synchronized (mInstallLock) {
3445            try {
3446                mInstaller.freeCache(volumeUuid, freeStorageSize);
3447            } catch (InstallerException e) {
3448                throw new IOException("Failed to free enough space", e);
3449            }
3450        }
3451    }
3452
3453    /**
3454     * Return if the user key is currently unlocked.
3455     */
3456    private boolean isUserKeyUnlocked(int userId) {
3457        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3458            final IMountService mount = IMountService.Stub
3459                    .asInterface(ServiceManager.getService("mount"));
3460            if (mount == null) {
3461                Slog.w(TAG, "Early during boot, assuming locked");
3462                return false;
3463            }
3464            final long token = Binder.clearCallingIdentity();
3465            try {
3466                return mount.isUserKeyUnlocked(userId);
3467            } catch (RemoteException e) {
3468                throw e.rethrowAsRuntimeException();
3469            } finally {
3470                Binder.restoreCallingIdentity(token);
3471            }
3472        } else {
3473            return true;
3474        }
3475    }
3476
3477    /**
3478     * Update given flags based on encryption status of current user.
3479     */
3480    private int updateFlags(int flags, int userId) {
3481        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3482                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3483            // Caller expressed an explicit opinion about what encryption
3484            // aware/unaware components they want to see, so fall through and
3485            // give them what they want
3486        } else {
3487            // Caller expressed no opinion, so match based on user state
3488            if (isUserKeyUnlocked(userId)) {
3489                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3490            } else {
3491                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3492            }
3493        }
3494        return flags;
3495    }
3496
3497    /**
3498     * Update given flags when being used to request {@link PackageInfo}.
3499     */
3500    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3501        boolean triaged = true;
3502        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3503                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3504            // Caller is asking for component details, so they'd better be
3505            // asking for specific encryption matching behavior, or be triaged
3506            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3507                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3508                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3509                triaged = false;
3510            }
3511        }
3512        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3513                | PackageManager.MATCH_SYSTEM_ONLY
3514                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3515            triaged = false;
3516        }
3517        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3518            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3519                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3520        }
3521        return updateFlags(flags, userId);
3522    }
3523
3524    /**
3525     * Update given flags when being used to request {@link ApplicationInfo}.
3526     */
3527    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3528        return updateFlagsForPackage(flags, userId, cookie);
3529    }
3530
3531    /**
3532     * Update given flags when being used to request {@link ComponentInfo}.
3533     */
3534    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3535        if (cookie instanceof Intent) {
3536            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3537                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3538            }
3539        }
3540
3541        boolean triaged = true;
3542        // Caller is asking for component details, so they'd better be
3543        // asking for specific encryption matching behavior, or be triaged
3544        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3545                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3546                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3547            triaged = false;
3548        }
3549        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3550            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3551                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3552        }
3553
3554        return updateFlags(flags, userId);
3555    }
3556
3557    /**
3558     * Update given flags when being used to request {@link ResolveInfo}.
3559     */
3560    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3561        // Safe mode means we shouldn't match any third-party components
3562        if (mSafeMode) {
3563            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3564        }
3565
3566        return updateFlagsForComponent(flags, userId, cookie);
3567    }
3568
3569    @Override
3570    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        flags = updateFlagsForComponent(flags, userId, component);
3573        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3574                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3575        synchronized (mPackages) {
3576            PackageParser.Activity a = mActivities.mActivities.get(component);
3577
3578            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3579            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3580                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3581                if (ps == null) return null;
3582                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3583                        userId);
3584            }
3585            if (mResolveComponentName.equals(component)) {
3586                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3587                        new PackageUserState(), userId);
3588            }
3589        }
3590        return null;
3591    }
3592
3593    @Override
3594    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3595            String resolvedType) {
3596        synchronized (mPackages) {
3597            if (component.equals(mResolveComponentName)) {
3598                // The resolver supports EVERYTHING!
3599                return true;
3600            }
3601            PackageParser.Activity a = mActivities.mActivities.get(component);
3602            if (a == null) {
3603                return false;
3604            }
3605            for (int i=0; i<a.intents.size(); i++) {
3606                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3607                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3608                    return true;
3609                }
3610            }
3611            return false;
3612        }
3613    }
3614
3615    @Override
3616    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3617        if (!sUserManager.exists(userId)) return null;
3618        flags = updateFlagsForComponent(flags, userId, component);
3619        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3620                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3621        synchronized (mPackages) {
3622            PackageParser.Activity a = mReceivers.mActivities.get(component);
3623            if (DEBUG_PACKAGE_INFO) Log.v(
3624                TAG, "getReceiverInfo " + component + ": " + a);
3625            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3626                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3627                if (ps == null) return null;
3628                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3629                        userId);
3630            }
3631        }
3632        return null;
3633    }
3634
3635    @Override
3636    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3637        if (!sUserManager.exists(userId)) return null;
3638        flags = updateFlagsForComponent(flags, userId, component);
3639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3640                false /* requireFullPermission */, false /* checkShell */, "get service info");
3641        synchronized (mPackages) {
3642            PackageParser.Service s = mServices.mServices.get(component);
3643            if (DEBUG_PACKAGE_INFO) Log.v(
3644                TAG, "getServiceInfo " + component + ": " + s);
3645            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3646                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3647                if (ps == null) return null;
3648                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3649                        userId);
3650            }
3651        }
3652        return null;
3653    }
3654
3655    @Override
3656    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3657        if (!sUserManager.exists(userId)) return null;
3658        flags = updateFlagsForComponent(flags, userId, component);
3659        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3660                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3661        synchronized (mPackages) {
3662            PackageParser.Provider p = mProviders.mProviders.get(component);
3663            if (DEBUG_PACKAGE_INFO) Log.v(
3664                TAG, "getProviderInfo " + component + ": " + p);
3665            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3666                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3667                if (ps == null) return null;
3668                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3669                        userId);
3670            }
3671        }
3672        return null;
3673    }
3674
3675    @Override
3676    public String[] getSystemSharedLibraryNames() {
3677        Set<String> libSet;
3678        synchronized (mPackages) {
3679            libSet = mSharedLibraries.keySet();
3680            int size = libSet.size();
3681            if (size > 0) {
3682                String[] libs = new String[size];
3683                libSet.toArray(libs);
3684                return libs;
3685            }
3686        }
3687        return null;
3688    }
3689
3690    @Override
3691    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3692        synchronized (mPackages) {
3693            return mServicesSystemSharedLibraryPackageName;
3694        }
3695    }
3696
3697    @Override
3698    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3699        synchronized (mPackages) {
3700            return mSharedSystemSharedLibraryPackageName;
3701        }
3702    }
3703
3704    @Override
3705    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3706        synchronized (mPackages) {
3707            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3708
3709            final FeatureInfo fi = new FeatureInfo();
3710            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3711                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3712            res.add(fi);
3713
3714            return new ParceledListSlice<>(res);
3715        }
3716    }
3717
3718    @Override
3719    public boolean hasSystemFeature(String name, int version) {
3720        synchronized (mPackages) {
3721            final FeatureInfo feat = mAvailableFeatures.get(name);
3722            if (feat == null) {
3723                return false;
3724            } else {
3725                return feat.version >= version;
3726            }
3727        }
3728    }
3729
3730    @Override
3731    public int checkPermission(String permName, String pkgName, int userId) {
3732        if (!sUserManager.exists(userId)) {
3733            return PackageManager.PERMISSION_DENIED;
3734        }
3735
3736        synchronized (mPackages) {
3737            final PackageParser.Package p = mPackages.get(pkgName);
3738            if (p != null && p.mExtras != null) {
3739                final PackageSetting ps = (PackageSetting) p.mExtras;
3740                final PermissionsState permissionsState = ps.getPermissionsState();
3741                if (permissionsState.hasPermission(permName, userId)) {
3742                    return PackageManager.PERMISSION_GRANTED;
3743                }
3744                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3745                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3746                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3747                    return PackageManager.PERMISSION_GRANTED;
3748                }
3749            }
3750        }
3751
3752        return PackageManager.PERMISSION_DENIED;
3753    }
3754
3755    @Override
3756    public int checkUidPermission(String permName, int uid) {
3757        final int userId = UserHandle.getUserId(uid);
3758
3759        if (!sUserManager.exists(userId)) {
3760            return PackageManager.PERMISSION_DENIED;
3761        }
3762
3763        synchronized (mPackages) {
3764            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3765            if (obj != null) {
3766                final SettingBase ps = (SettingBase) obj;
3767                final PermissionsState permissionsState = ps.getPermissionsState();
3768                if (permissionsState.hasPermission(permName, userId)) {
3769                    return PackageManager.PERMISSION_GRANTED;
3770                }
3771                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3772                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3773                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3774                    return PackageManager.PERMISSION_GRANTED;
3775                }
3776            } else {
3777                ArraySet<String> perms = mSystemPermissions.get(uid);
3778                if (perms != null) {
3779                    if (perms.contains(permName)) {
3780                        return PackageManager.PERMISSION_GRANTED;
3781                    }
3782                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3783                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3784                        return PackageManager.PERMISSION_GRANTED;
3785                    }
3786                }
3787            }
3788        }
3789
3790        return PackageManager.PERMISSION_DENIED;
3791    }
3792
3793    @Override
3794    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3795        if (UserHandle.getCallingUserId() != userId) {
3796            mContext.enforceCallingPermission(
3797                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3798                    "isPermissionRevokedByPolicy for user " + userId);
3799        }
3800
3801        if (checkPermission(permission, packageName, userId)
3802                == PackageManager.PERMISSION_GRANTED) {
3803            return false;
3804        }
3805
3806        final long identity = Binder.clearCallingIdentity();
3807        try {
3808            final int flags = getPermissionFlags(permission, packageName, userId);
3809            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3810        } finally {
3811            Binder.restoreCallingIdentity(identity);
3812        }
3813    }
3814
3815    @Override
3816    public String getPermissionControllerPackageName() {
3817        synchronized (mPackages) {
3818            return mRequiredInstallerPackage;
3819        }
3820    }
3821
3822    /**
3823     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3824     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3825     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3826     * @param message the message to log on security exception
3827     */
3828    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3829            boolean checkShell, String message) {
3830        if (userId < 0) {
3831            throw new IllegalArgumentException("Invalid userId " + userId);
3832        }
3833        if (checkShell) {
3834            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3835        }
3836        if (userId == UserHandle.getUserId(callingUid)) return;
3837        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3838            if (requireFullPermission) {
3839                mContext.enforceCallingOrSelfPermission(
3840                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3841            } else {
3842                try {
3843                    mContext.enforceCallingOrSelfPermission(
3844                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3845                } catch (SecurityException se) {
3846                    mContext.enforceCallingOrSelfPermission(
3847                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3848                }
3849            }
3850        }
3851    }
3852
3853    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3854        if (callingUid == Process.SHELL_UID) {
3855            if (userHandle >= 0
3856                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3857                throw new SecurityException("Shell does not have permission to access user "
3858                        + userHandle);
3859            } else if (userHandle < 0) {
3860                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3861                        + Debug.getCallers(3));
3862            }
3863        }
3864    }
3865
3866    private BasePermission findPermissionTreeLP(String permName) {
3867        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3868            if (permName.startsWith(bp.name) &&
3869                    permName.length() > bp.name.length() &&
3870                    permName.charAt(bp.name.length()) == '.') {
3871                return bp;
3872            }
3873        }
3874        return null;
3875    }
3876
3877    private BasePermission checkPermissionTreeLP(String permName) {
3878        if (permName != null) {
3879            BasePermission bp = findPermissionTreeLP(permName);
3880            if (bp != null) {
3881                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3882                    return bp;
3883                }
3884                throw new SecurityException("Calling uid "
3885                        + Binder.getCallingUid()
3886                        + " is not allowed to add to permission tree "
3887                        + bp.name + " owned by uid " + bp.uid);
3888            }
3889        }
3890        throw new SecurityException("No permission tree found for " + permName);
3891    }
3892
3893    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3894        if (s1 == null) {
3895            return s2 == null;
3896        }
3897        if (s2 == null) {
3898            return false;
3899        }
3900        if (s1.getClass() != s2.getClass()) {
3901            return false;
3902        }
3903        return s1.equals(s2);
3904    }
3905
3906    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3907        if (pi1.icon != pi2.icon) return false;
3908        if (pi1.logo != pi2.logo) return false;
3909        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3910        if (!compareStrings(pi1.name, pi2.name)) return false;
3911        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3912        // We'll take care of setting this one.
3913        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3914        // These are not currently stored in settings.
3915        //if (!compareStrings(pi1.group, pi2.group)) return false;
3916        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3917        //if (pi1.labelRes != pi2.labelRes) return false;
3918        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3919        return true;
3920    }
3921
3922    int permissionInfoFootprint(PermissionInfo info) {
3923        int size = info.name.length();
3924        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3925        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3926        return size;
3927    }
3928
3929    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3930        int size = 0;
3931        for (BasePermission perm : mSettings.mPermissions.values()) {
3932            if (perm.uid == tree.uid) {
3933                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3934            }
3935        }
3936        return size;
3937    }
3938
3939    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3940        // We calculate the max size of permissions defined by this uid and throw
3941        // if that plus the size of 'info' would exceed our stated maximum.
3942        if (tree.uid != Process.SYSTEM_UID) {
3943            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3944            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3945                throw new SecurityException("Permission tree size cap exceeded");
3946            }
3947        }
3948    }
3949
3950    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3951        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3952            throw new SecurityException("Label must be specified in permission");
3953        }
3954        BasePermission tree = checkPermissionTreeLP(info.name);
3955        BasePermission bp = mSettings.mPermissions.get(info.name);
3956        boolean added = bp == null;
3957        boolean changed = true;
3958        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3959        if (added) {
3960            enforcePermissionCapLocked(info, tree);
3961            bp = new BasePermission(info.name, tree.sourcePackage,
3962                    BasePermission.TYPE_DYNAMIC);
3963        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3964            throw new SecurityException(
3965                    "Not allowed to modify non-dynamic permission "
3966                    + info.name);
3967        } else {
3968            if (bp.protectionLevel == fixedLevel
3969                    && bp.perm.owner.equals(tree.perm.owner)
3970                    && bp.uid == tree.uid
3971                    && comparePermissionInfos(bp.perm.info, info)) {
3972                changed = false;
3973            }
3974        }
3975        bp.protectionLevel = fixedLevel;
3976        info = new PermissionInfo(info);
3977        info.protectionLevel = fixedLevel;
3978        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3979        bp.perm.info.packageName = tree.perm.info.packageName;
3980        bp.uid = tree.uid;
3981        if (added) {
3982            mSettings.mPermissions.put(info.name, bp);
3983        }
3984        if (changed) {
3985            if (!async) {
3986                mSettings.writeLPr();
3987            } else {
3988                scheduleWriteSettingsLocked();
3989            }
3990        }
3991        return added;
3992    }
3993
3994    @Override
3995    public boolean addPermission(PermissionInfo info) {
3996        synchronized (mPackages) {
3997            return addPermissionLocked(info, false);
3998        }
3999    }
4000
4001    @Override
4002    public boolean addPermissionAsync(PermissionInfo info) {
4003        synchronized (mPackages) {
4004            return addPermissionLocked(info, true);
4005        }
4006    }
4007
4008    @Override
4009    public void removePermission(String name) {
4010        synchronized (mPackages) {
4011            checkPermissionTreeLP(name);
4012            BasePermission bp = mSettings.mPermissions.get(name);
4013            if (bp != null) {
4014                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4015                    throw new SecurityException(
4016                            "Not allowed to modify non-dynamic permission "
4017                            + name);
4018                }
4019                mSettings.mPermissions.remove(name);
4020                mSettings.writeLPr();
4021            }
4022        }
4023    }
4024
4025    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4026            BasePermission bp) {
4027        int index = pkg.requestedPermissions.indexOf(bp.name);
4028        if (index == -1) {
4029            throw new SecurityException("Package " + pkg.packageName
4030                    + " has not requested permission " + bp.name);
4031        }
4032        if (!bp.isRuntime() && !bp.isDevelopment()) {
4033            throw new SecurityException("Permission " + bp.name
4034                    + " is not a changeable permission type");
4035        }
4036    }
4037
4038    @Override
4039    public void grantRuntimePermission(String packageName, String name, final int userId) {
4040        if (!sUserManager.exists(userId)) {
4041            Log.e(TAG, "No such user:" + userId);
4042            return;
4043        }
4044
4045        mContext.enforceCallingOrSelfPermission(
4046                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4047                "grantRuntimePermission");
4048
4049        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4050                true /* requireFullPermission */, true /* checkShell */,
4051                "grantRuntimePermission");
4052
4053        final int uid;
4054        final SettingBase sb;
4055
4056        synchronized (mPackages) {
4057            final PackageParser.Package pkg = mPackages.get(packageName);
4058            if (pkg == null) {
4059                throw new IllegalArgumentException("Unknown package: " + packageName);
4060            }
4061
4062            final BasePermission bp = mSettings.mPermissions.get(name);
4063            if (bp == null) {
4064                throw new IllegalArgumentException("Unknown permission: " + name);
4065            }
4066
4067            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4068
4069            // If a permission review is required for legacy apps we represent
4070            // their permissions as always granted runtime ones since we need
4071            // to keep the review required permission flag per user while an
4072            // install permission's state is shared across all users.
4073            if (Build.PERMISSIONS_REVIEW_REQUIRED
4074                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4075                    && bp.isRuntime()) {
4076                return;
4077            }
4078
4079            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4080            sb = (SettingBase) pkg.mExtras;
4081            if (sb == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final PermissionsState permissionsState = sb.getPermissionsState();
4086
4087            final int flags = permissionsState.getPermissionFlags(name, userId);
4088            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4089                throw new SecurityException("Cannot grant system fixed permission "
4090                        + name + " for package " + packageName);
4091            }
4092
4093            if (bp.isDevelopment()) {
4094                // Development permissions must be handled specially, since they are not
4095                // normal runtime permissions.  For now they apply to all users.
4096                if (permissionsState.grantInstallPermission(bp) !=
4097                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4098                    scheduleWriteSettingsLocked();
4099                }
4100                return;
4101            }
4102
4103            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4104                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4105                return;
4106            }
4107
4108            final int result = permissionsState.grantRuntimePermission(bp, userId);
4109            switch (result) {
4110                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4111                    return;
4112                }
4113
4114                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4115                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4116                    mHandler.post(new Runnable() {
4117                        @Override
4118                        public void run() {
4119                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4120                        }
4121                    });
4122                }
4123                break;
4124            }
4125
4126            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4127
4128            // Not critical if that is lost - app has to request again.
4129            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4130        }
4131
4132        // Only need to do this if user is initialized. Otherwise it's a new user
4133        // and there are no processes running as the user yet and there's no need
4134        // to make an expensive call to remount processes for the changed permissions.
4135        if (READ_EXTERNAL_STORAGE.equals(name)
4136                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4137            final long token = Binder.clearCallingIdentity();
4138            try {
4139                if (sUserManager.isInitialized(userId)) {
4140                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4141                            MountServiceInternal.class);
4142                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4143                }
4144            } finally {
4145                Binder.restoreCallingIdentity(token);
4146            }
4147        }
4148    }
4149
4150    @Override
4151    public void revokeRuntimePermission(String packageName, String name, int userId) {
4152        if (!sUserManager.exists(userId)) {
4153            Log.e(TAG, "No such user:" + userId);
4154            return;
4155        }
4156
4157        mContext.enforceCallingOrSelfPermission(
4158                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4159                "revokeRuntimePermission");
4160
4161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4162                true /* requireFullPermission */, true /* checkShell */,
4163                "revokeRuntimePermission");
4164
4165        final int appId;
4166
4167        synchronized (mPackages) {
4168            final PackageParser.Package pkg = mPackages.get(packageName);
4169            if (pkg == null) {
4170                throw new IllegalArgumentException("Unknown package: " + packageName);
4171            }
4172
4173            final BasePermission bp = mSettings.mPermissions.get(name);
4174            if (bp == null) {
4175                throw new IllegalArgumentException("Unknown permission: " + name);
4176            }
4177
4178            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4179
4180            // If a permission review is required for legacy apps we represent
4181            // their permissions as always granted runtime ones since we need
4182            // to keep the review required permission flag per user while an
4183            // install permission's state is shared across all users.
4184            if (Build.PERMISSIONS_REVIEW_REQUIRED
4185                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4186                    && bp.isRuntime()) {
4187                return;
4188            }
4189
4190            SettingBase sb = (SettingBase) pkg.mExtras;
4191            if (sb == null) {
4192                throw new IllegalArgumentException("Unknown package: " + packageName);
4193            }
4194
4195            final PermissionsState permissionsState = sb.getPermissionsState();
4196
4197            final int flags = permissionsState.getPermissionFlags(name, userId);
4198            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4199                throw new SecurityException("Cannot revoke system fixed permission "
4200                        + name + " for package " + packageName);
4201            }
4202
4203            if (bp.isDevelopment()) {
4204                // Development permissions must be handled specially, since they are not
4205                // normal runtime permissions.  For now they apply to all users.
4206                if (permissionsState.revokeInstallPermission(bp) !=
4207                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4208                    scheduleWriteSettingsLocked();
4209                }
4210                return;
4211            }
4212
4213            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4214                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4215                return;
4216            }
4217
4218            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4219
4220            // Critical, after this call app should never have the permission.
4221            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4222
4223            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4224        }
4225
4226        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4227    }
4228
4229    @Override
4230    public void resetRuntimePermissions() {
4231        mContext.enforceCallingOrSelfPermission(
4232                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4233                "revokeRuntimePermission");
4234
4235        int callingUid = Binder.getCallingUid();
4236        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4237            mContext.enforceCallingOrSelfPermission(
4238                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4239                    "resetRuntimePermissions");
4240        }
4241
4242        synchronized (mPackages) {
4243            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4244            for (int userId : UserManagerService.getInstance().getUserIds()) {
4245                final int packageCount = mPackages.size();
4246                for (int i = 0; i < packageCount; i++) {
4247                    PackageParser.Package pkg = mPackages.valueAt(i);
4248                    if (!(pkg.mExtras instanceof PackageSetting)) {
4249                        continue;
4250                    }
4251                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4252                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4253                }
4254            }
4255        }
4256    }
4257
4258    @Override
4259    public int getPermissionFlags(String name, String packageName, int userId) {
4260        if (!sUserManager.exists(userId)) {
4261            return 0;
4262        }
4263
4264        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4265
4266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4267                true /* requireFullPermission */, false /* checkShell */,
4268                "getPermissionFlags");
4269
4270        synchronized (mPackages) {
4271            final PackageParser.Package pkg = mPackages.get(packageName);
4272            if (pkg == null) {
4273                throw new IllegalArgumentException("Unknown package: " + packageName);
4274            }
4275
4276            final BasePermission bp = mSettings.mPermissions.get(name);
4277            if (bp == null) {
4278                throw new IllegalArgumentException("Unknown permission: " + name);
4279            }
4280
4281            SettingBase sb = (SettingBase) pkg.mExtras;
4282            if (sb == null) {
4283                throw new IllegalArgumentException("Unknown package: " + packageName);
4284            }
4285
4286            PermissionsState permissionsState = sb.getPermissionsState();
4287            return permissionsState.getPermissionFlags(name, userId);
4288        }
4289    }
4290
4291    @Override
4292    public void updatePermissionFlags(String name, String packageName, int flagMask,
4293            int flagValues, int userId) {
4294        if (!sUserManager.exists(userId)) {
4295            return;
4296        }
4297
4298        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4299
4300        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4301                true /* requireFullPermission */, true /* checkShell */,
4302                "updatePermissionFlags");
4303
4304        // Only the system can change these flags and nothing else.
4305        if (getCallingUid() != Process.SYSTEM_UID) {
4306            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4307            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4308            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4309            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4310            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4311        }
4312
4313        synchronized (mPackages) {
4314            final PackageParser.Package pkg = mPackages.get(packageName);
4315            if (pkg == null) {
4316                throw new IllegalArgumentException("Unknown package: " + packageName);
4317            }
4318
4319            final BasePermission bp = mSettings.mPermissions.get(name);
4320            if (bp == null) {
4321                throw new IllegalArgumentException("Unknown permission: " + name);
4322            }
4323
4324            SettingBase sb = (SettingBase) pkg.mExtras;
4325            if (sb == null) {
4326                throw new IllegalArgumentException("Unknown package: " + packageName);
4327            }
4328
4329            PermissionsState permissionsState = sb.getPermissionsState();
4330
4331            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4332
4333            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4334                // Install and runtime permissions are stored in different places,
4335                // so figure out what permission changed and persist the change.
4336                if (permissionsState.getInstallPermissionState(name) != null) {
4337                    scheduleWriteSettingsLocked();
4338                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4339                        || hadState) {
4340                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4341                }
4342            }
4343        }
4344    }
4345
4346    /**
4347     * Update the permission flags for all packages and runtime permissions of a user in order
4348     * to allow device or profile owner to remove POLICY_FIXED.
4349     */
4350    @Override
4351    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4352        if (!sUserManager.exists(userId)) {
4353            return;
4354        }
4355
4356        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4357
4358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4359                true /* requireFullPermission */, true /* checkShell */,
4360                "updatePermissionFlagsForAllApps");
4361
4362        // Only the system can change system fixed flags.
4363        if (getCallingUid() != Process.SYSTEM_UID) {
4364            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4365            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4366        }
4367
4368        synchronized (mPackages) {
4369            boolean changed = false;
4370            final int packageCount = mPackages.size();
4371            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4372                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4373                SettingBase sb = (SettingBase) pkg.mExtras;
4374                if (sb == null) {
4375                    continue;
4376                }
4377                PermissionsState permissionsState = sb.getPermissionsState();
4378                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4379                        userId, flagMask, flagValues);
4380            }
4381            if (changed) {
4382                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4383            }
4384        }
4385    }
4386
4387    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4388        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4389                != PackageManager.PERMISSION_GRANTED
4390            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4391                != PackageManager.PERMISSION_GRANTED) {
4392            throw new SecurityException(message + " requires "
4393                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4394                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4395        }
4396    }
4397
4398    @Override
4399    public boolean shouldShowRequestPermissionRationale(String permissionName,
4400            String packageName, int userId) {
4401        if (UserHandle.getCallingUserId() != userId) {
4402            mContext.enforceCallingPermission(
4403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4404                    "canShowRequestPermissionRationale for user " + userId);
4405        }
4406
4407        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4408        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4409            return false;
4410        }
4411
4412        if (checkPermission(permissionName, packageName, userId)
4413                == PackageManager.PERMISSION_GRANTED) {
4414            return false;
4415        }
4416
4417        final int flags;
4418
4419        final long identity = Binder.clearCallingIdentity();
4420        try {
4421            flags = getPermissionFlags(permissionName,
4422                    packageName, userId);
4423        } finally {
4424            Binder.restoreCallingIdentity(identity);
4425        }
4426
4427        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4428                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4429                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4430
4431        if ((flags & fixedFlags) != 0) {
4432            return false;
4433        }
4434
4435        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4436    }
4437
4438    @Override
4439    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4440        mContext.enforceCallingOrSelfPermission(
4441                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4442                "addOnPermissionsChangeListener");
4443
4444        synchronized (mPackages) {
4445            mOnPermissionChangeListeners.addListenerLocked(listener);
4446        }
4447    }
4448
4449    @Override
4450    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4451        synchronized (mPackages) {
4452            mOnPermissionChangeListeners.removeListenerLocked(listener);
4453        }
4454    }
4455
4456    @Override
4457    public boolean isProtectedBroadcast(String actionName) {
4458        synchronized (mPackages) {
4459            if (mProtectedBroadcasts.contains(actionName)) {
4460                return true;
4461            } else if (actionName != null) {
4462                // TODO: remove these terrible hacks
4463                if (actionName.startsWith("android.net.netmon.lingerExpired")
4464                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4465                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4466                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4467                    return true;
4468                }
4469            }
4470        }
4471        return false;
4472    }
4473
4474    @Override
4475    public int checkSignatures(String pkg1, String pkg2) {
4476        synchronized (mPackages) {
4477            final PackageParser.Package p1 = mPackages.get(pkg1);
4478            final PackageParser.Package p2 = mPackages.get(pkg2);
4479            if (p1 == null || p1.mExtras == null
4480                    || p2 == null || p2.mExtras == null) {
4481                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4482            }
4483            return compareSignatures(p1.mSignatures, p2.mSignatures);
4484        }
4485    }
4486
4487    @Override
4488    public int checkUidSignatures(int uid1, int uid2) {
4489        // Map to base uids.
4490        uid1 = UserHandle.getAppId(uid1);
4491        uid2 = UserHandle.getAppId(uid2);
4492        // reader
4493        synchronized (mPackages) {
4494            Signature[] s1;
4495            Signature[] s2;
4496            Object obj = mSettings.getUserIdLPr(uid1);
4497            if (obj != null) {
4498                if (obj instanceof SharedUserSetting) {
4499                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4500                } else if (obj instanceof PackageSetting) {
4501                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4502                } else {
4503                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4504                }
4505            } else {
4506                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4507            }
4508            obj = mSettings.getUserIdLPr(uid2);
4509            if (obj != null) {
4510                if (obj instanceof SharedUserSetting) {
4511                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4512                } else if (obj instanceof PackageSetting) {
4513                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4514                } else {
4515                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4516                }
4517            } else {
4518                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4519            }
4520            return compareSignatures(s1, s2);
4521        }
4522    }
4523
4524    /**
4525     * This method should typically only be used when granting or revoking
4526     * permissions, since the app may immediately restart after this call.
4527     * <p>
4528     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4529     * guard your work against the app being relaunched.
4530     */
4531    private void killUid(int appId, int userId, String reason) {
4532        final long identity = Binder.clearCallingIdentity();
4533        try {
4534            IActivityManager am = ActivityManagerNative.getDefault();
4535            if (am != null) {
4536                try {
4537                    am.killUid(appId, userId, reason);
4538                } catch (RemoteException e) {
4539                    /* ignore - same process */
4540                }
4541            }
4542        } finally {
4543            Binder.restoreCallingIdentity(identity);
4544        }
4545    }
4546
4547    /**
4548     * Compares two sets of signatures. Returns:
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4555     * <br />
4556     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4557     * <br />
4558     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4559     */
4560    static int compareSignatures(Signature[] s1, Signature[] s2) {
4561        if (s1 == null) {
4562            return s2 == null
4563                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4564                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4565        }
4566
4567        if (s2 == null) {
4568            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4569        }
4570
4571        if (s1.length != s2.length) {
4572            return PackageManager.SIGNATURE_NO_MATCH;
4573        }
4574
4575        // Since both signature sets are of size 1, we can compare without HashSets.
4576        if (s1.length == 1) {
4577            return s1[0].equals(s2[0]) ?
4578                    PackageManager.SIGNATURE_MATCH :
4579                    PackageManager.SIGNATURE_NO_MATCH;
4580        }
4581
4582        ArraySet<Signature> set1 = new ArraySet<Signature>();
4583        for (Signature sig : s1) {
4584            set1.add(sig);
4585        }
4586        ArraySet<Signature> set2 = new ArraySet<Signature>();
4587        for (Signature sig : s2) {
4588            set2.add(sig);
4589        }
4590        // Make sure s2 contains all signatures in s1.
4591        if (set1.equals(set2)) {
4592            return PackageManager.SIGNATURE_MATCH;
4593        }
4594        return PackageManager.SIGNATURE_NO_MATCH;
4595    }
4596
4597    /**
4598     * If the database version for this type of package (internal storage or
4599     * external storage) is less than the version where package signatures
4600     * were updated, return true.
4601     */
4602    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4603        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4604        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4605    }
4606
4607    /**
4608     * Used for backward compatibility to make sure any packages with
4609     * certificate chains get upgraded to the new style. {@code existingSigs}
4610     * will be in the old format (since they were stored on disk from before the
4611     * system upgrade) and {@code scannedSigs} will be in the newer format.
4612     */
4613    private int compareSignaturesCompat(PackageSignatures existingSigs,
4614            PackageParser.Package scannedPkg) {
4615        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4616            return PackageManager.SIGNATURE_NO_MATCH;
4617        }
4618
4619        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4620        for (Signature sig : existingSigs.mSignatures) {
4621            existingSet.add(sig);
4622        }
4623        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4624        for (Signature sig : scannedPkg.mSignatures) {
4625            try {
4626                Signature[] chainSignatures = sig.getChainSignatures();
4627                for (Signature chainSig : chainSignatures) {
4628                    scannedCompatSet.add(chainSig);
4629                }
4630            } catch (CertificateEncodingException e) {
4631                scannedCompatSet.add(sig);
4632            }
4633        }
4634        /*
4635         * Make sure the expanded scanned set contains all signatures in the
4636         * existing one.
4637         */
4638        if (scannedCompatSet.equals(existingSet)) {
4639            // Migrate the old signatures to the new scheme.
4640            existingSigs.assignSignatures(scannedPkg.mSignatures);
4641            // The new KeySets will be re-added later in the scanning process.
4642            synchronized (mPackages) {
4643                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4644            }
4645            return PackageManager.SIGNATURE_MATCH;
4646        }
4647        return PackageManager.SIGNATURE_NO_MATCH;
4648    }
4649
4650    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4651        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4652        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4653    }
4654
4655    private int compareSignaturesRecover(PackageSignatures existingSigs,
4656            PackageParser.Package scannedPkg) {
4657        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4658            return PackageManager.SIGNATURE_NO_MATCH;
4659        }
4660
4661        String msg = null;
4662        try {
4663            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4664                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4665                        + scannedPkg.packageName);
4666                return PackageManager.SIGNATURE_MATCH;
4667            }
4668        } catch (CertificateException e) {
4669            msg = e.getMessage();
4670        }
4671
4672        logCriticalInfo(Log.INFO,
4673                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4674        return PackageManager.SIGNATURE_NO_MATCH;
4675    }
4676
4677    @Override
4678    public List<String> getAllPackages() {
4679        synchronized (mPackages) {
4680            return new ArrayList<String>(mPackages.keySet());
4681        }
4682    }
4683
4684    @Override
4685    public String[] getPackagesForUid(int uid) {
4686        uid = UserHandle.getAppId(uid);
4687        // reader
4688        synchronized (mPackages) {
4689            Object obj = mSettings.getUserIdLPr(uid);
4690            if (obj instanceof SharedUserSetting) {
4691                final SharedUserSetting sus = (SharedUserSetting) obj;
4692                final int N = sus.packages.size();
4693                final String[] res = new String[N];
4694                final Iterator<PackageSetting> it = sus.packages.iterator();
4695                int i = 0;
4696                while (it.hasNext()) {
4697                    res[i++] = it.next().name;
4698                }
4699                return res;
4700            } else if (obj instanceof PackageSetting) {
4701                final PackageSetting ps = (PackageSetting) obj;
4702                return new String[] { ps.name };
4703            }
4704        }
4705        return null;
4706    }
4707
4708    @Override
4709    public String getNameForUid(int uid) {
4710        // reader
4711        synchronized (mPackages) {
4712            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4713            if (obj instanceof SharedUserSetting) {
4714                final SharedUserSetting sus = (SharedUserSetting) obj;
4715                return sus.name + ":" + sus.userId;
4716            } else if (obj instanceof PackageSetting) {
4717                final PackageSetting ps = (PackageSetting) obj;
4718                return ps.name;
4719            }
4720        }
4721        return null;
4722    }
4723
4724    @Override
4725    public int getUidForSharedUser(String sharedUserName) {
4726        if(sharedUserName == null) {
4727            return -1;
4728        }
4729        // reader
4730        synchronized (mPackages) {
4731            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4732            if (suid == null) {
4733                return -1;
4734            }
4735            return suid.userId;
4736        }
4737    }
4738
4739    @Override
4740    public int getFlagsForUid(int uid) {
4741        synchronized (mPackages) {
4742            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4743            if (obj instanceof SharedUserSetting) {
4744                final SharedUserSetting sus = (SharedUserSetting) obj;
4745                return sus.pkgFlags;
4746            } else if (obj instanceof PackageSetting) {
4747                final PackageSetting ps = (PackageSetting) obj;
4748                return ps.pkgFlags;
4749            }
4750        }
4751        return 0;
4752    }
4753
4754    @Override
4755    public int getPrivateFlagsForUid(int uid) {
4756        synchronized (mPackages) {
4757            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4758            if (obj instanceof SharedUserSetting) {
4759                final SharedUserSetting sus = (SharedUserSetting) obj;
4760                return sus.pkgPrivateFlags;
4761            } else if (obj instanceof PackageSetting) {
4762                final PackageSetting ps = (PackageSetting) obj;
4763                return ps.pkgPrivateFlags;
4764            }
4765        }
4766        return 0;
4767    }
4768
4769    @Override
4770    public boolean isUidPrivileged(int uid) {
4771        uid = UserHandle.getAppId(uid);
4772        // reader
4773        synchronized (mPackages) {
4774            Object obj = mSettings.getUserIdLPr(uid);
4775            if (obj instanceof SharedUserSetting) {
4776                final SharedUserSetting sus = (SharedUserSetting) obj;
4777                final Iterator<PackageSetting> it = sus.packages.iterator();
4778                while (it.hasNext()) {
4779                    if (it.next().isPrivileged()) {
4780                        return true;
4781                    }
4782                }
4783            } else if (obj instanceof PackageSetting) {
4784                final PackageSetting ps = (PackageSetting) obj;
4785                return ps.isPrivileged();
4786            }
4787        }
4788        return false;
4789    }
4790
4791    @Override
4792    public String[] getAppOpPermissionPackages(String permissionName) {
4793        synchronized (mPackages) {
4794            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4795            if (pkgs == null) {
4796                return null;
4797            }
4798            return pkgs.toArray(new String[pkgs.size()]);
4799        }
4800    }
4801
4802    @Override
4803    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4804            int flags, int userId) {
4805        try {
4806            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4807
4808            if (!sUserManager.exists(userId)) return null;
4809            flags = updateFlagsForResolve(flags, userId, intent);
4810            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4811                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4812
4813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4814            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4815                    flags, userId);
4816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4817
4818            final ResolveInfo bestChoice =
4819                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4820
4821            if (isEphemeralAllowed(intent, query, userId)) {
4822                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4823                final EphemeralResolveInfo ai =
4824                        getEphemeralResolveInfo(intent, resolvedType, userId);
4825                if (ai != null) {
4826                    if (DEBUG_EPHEMERAL) {
4827                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4828                    }
4829                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4830                    bestChoice.ephemeralResolveInfo = ai;
4831                }
4832                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4833            }
4834            return bestChoice;
4835        } finally {
4836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4837        }
4838    }
4839
4840    @Override
4841    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4842            IntentFilter filter, int match, ComponentName activity) {
4843        final int userId = UserHandle.getCallingUserId();
4844        if (DEBUG_PREFERRED) {
4845            Log.v(TAG, "setLastChosenActivity intent=" + intent
4846                + " resolvedType=" + resolvedType
4847                + " flags=" + flags
4848                + " filter=" + filter
4849                + " match=" + match
4850                + " activity=" + activity);
4851            filter.dump(new PrintStreamPrinter(System.out), "    ");
4852        }
4853        intent.setComponent(null);
4854        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4855                userId);
4856        // Find any earlier preferred or last chosen entries and nuke them
4857        findPreferredActivity(intent, resolvedType,
4858                flags, query, 0, false, true, false, userId);
4859        // Add the new activity as the last chosen for this filter
4860        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4861                "Setting last chosen");
4862    }
4863
4864    @Override
4865    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4866        final int userId = UserHandle.getCallingUserId();
4867        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4868        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4869                userId);
4870        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4871                false, false, false, userId);
4872    }
4873
4874
4875    private boolean isEphemeralAllowed(
4876            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4877        // Short circuit and return early if possible.
4878        if (DISABLE_EPHEMERAL_APPS) {
4879            return false;
4880        }
4881        final int callingUser = UserHandle.getCallingUserId();
4882        if (callingUser != UserHandle.USER_SYSTEM) {
4883            return false;
4884        }
4885        if (mEphemeralResolverConnection == null) {
4886            return false;
4887        }
4888        if (intent.getComponent() != null) {
4889            return false;
4890        }
4891        if (intent.getPackage() != null) {
4892            return false;
4893        }
4894        final boolean isWebUri = hasWebURI(intent);
4895        if (!isWebUri) {
4896            return false;
4897        }
4898        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4899        synchronized (mPackages) {
4900            final int count = resolvedActivites.size();
4901            for (int n = 0; n < count; n++) {
4902                ResolveInfo info = resolvedActivites.get(n);
4903                String packageName = info.activityInfo.packageName;
4904                PackageSetting ps = mSettings.mPackages.get(packageName);
4905                if (ps != null) {
4906                    // Try to get the status from User settings first
4907                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4908                    int status = (int) (packedStatus >> 32);
4909                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4910                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4911                        if (DEBUG_EPHEMERAL) {
4912                            Slog.v(TAG, "DENY ephemeral apps;"
4913                                + " pkg: " + packageName + ", status: " + status);
4914                        }
4915                        return false;
4916                    }
4917                }
4918            }
4919        }
4920        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4921        return true;
4922    }
4923
4924    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4925            int userId) {
4926        MessageDigest digest = null;
4927        try {
4928            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4929        } catch (NoSuchAlgorithmException e) {
4930            // If we can't create a digest, ignore ephemeral apps.
4931            return null;
4932        }
4933
4934        final byte[] hostBytes = intent.getData().getHost().getBytes();
4935        final byte[] digestBytes = digest.digest(hostBytes);
4936        int shaPrefix =
4937                digestBytes[0] << 24
4938                | digestBytes[1] << 16
4939                | digestBytes[2] << 8
4940                | digestBytes[3] << 0;
4941        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4942                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4943        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4944            // No hash prefix match; there are no ephemeral apps for this domain.
4945            return null;
4946        }
4947        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4948            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4949            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4950                continue;
4951            }
4952            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4953            // No filters; this should never happen.
4954            if (filters.isEmpty()) {
4955                continue;
4956            }
4957            // We have a domain match; resolve the filters to see if anything matches.
4958            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4959            for (int j = filters.size() - 1; j >= 0; --j) {
4960                final EphemeralResolveIntentInfo intentInfo =
4961                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4962                ephemeralResolver.addFilter(intentInfo);
4963            }
4964            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4965                    intent, resolvedType, false /*defaultOnly*/, userId);
4966            if (!matchedResolveInfoList.isEmpty()) {
4967                return matchedResolveInfoList.get(0);
4968            }
4969        }
4970        // Hash or filter mis-match; no ephemeral apps for this domain.
4971        return null;
4972    }
4973
4974    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4975            int flags, List<ResolveInfo> query, int userId) {
4976        if (query != null) {
4977            final int N = query.size();
4978            if (N == 1) {
4979                return query.get(0);
4980            } else if (N > 1) {
4981                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4982                // If there is more than one activity with the same priority,
4983                // then let the user decide between them.
4984                ResolveInfo r0 = query.get(0);
4985                ResolveInfo r1 = query.get(1);
4986                if (DEBUG_INTENT_MATCHING || debug) {
4987                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4988                            + r1.activityInfo.name + "=" + r1.priority);
4989                }
4990                // If the first activity has a higher priority, or a different
4991                // default, then it is always desirable to pick it.
4992                if (r0.priority != r1.priority
4993                        || r0.preferredOrder != r1.preferredOrder
4994                        || r0.isDefault != r1.isDefault) {
4995                    return query.get(0);
4996                }
4997                // If we have saved a preference for a preferred activity for
4998                // this Intent, use that.
4999                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5000                        flags, query, r0.priority, true, false, debug, userId);
5001                if (ri != null) {
5002                    return ri;
5003                }
5004                ri = new ResolveInfo(mResolveInfo);
5005                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5006                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5007                ri.activityInfo.applicationInfo = new ApplicationInfo(
5008                        ri.activityInfo.applicationInfo);
5009                if (userId != 0) {
5010                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5011                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5012                }
5013                // Make sure that the resolver is displayable in car mode
5014                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5015                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5016                return ri;
5017            }
5018        }
5019        return null;
5020    }
5021
5022    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5023            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5024        final int N = query.size();
5025        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5026                .get(userId);
5027        // Get the list of persistent preferred activities that handle the intent
5028        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5029        List<PersistentPreferredActivity> pprefs = ppir != null
5030                ? ppir.queryIntent(intent, resolvedType,
5031                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5032                : null;
5033        if (pprefs != null && pprefs.size() > 0) {
5034            final int M = pprefs.size();
5035            for (int i=0; i<M; i++) {
5036                final PersistentPreferredActivity ppa = pprefs.get(i);
5037                if (DEBUG_PREFERRED || debug) {
5038                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5039                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5040                            + "\n  component=" + ppa.mComponent);
5041                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5042                }
5043                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5044                        flags | MATCH_DISABLED_COMPONENTS, userId);
5045                if (DEBUG_PREFERRED || debug) {
5046                    Slog.v(TAG, "Found persistent preferred activity:");
5047                    if (ai != null) {
5048                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5049                    } else {
5050                        Slog.v(TAG, "  null");
5051                    }
5052                }
5053                if (ai == null) {
5054                    // This previously registered persistent preferred activity
5055                    // component is no longer known. Ignore it and do NOT remove it.
5056                    continue;
5057                }
5058                for (int j=0; j<N; j++) {
5059                    final ResolveInfo ri = query.get(j);
5060                    if (!ri.activityInfo.applicationInfo.packageName
5061                            .equals(ai.applicationInfo.packageName)) {
5062                        continue;
5063                    }
5064                    if (!ri.activityInfo.name.equals(ai.name)) {
5065                        continue;
5066                    }
5067                    //  Found a persistent preference that can handle the intent.
5068                    if (DEBUG_PREFERRED || debug) {
5069                        Slog.v(TAG, "Returning persistent preferred activity: " +
5070                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5071                    }
5072                    return ri;
5073                }
5074            }
5075        }
5076        return null;
5077    }
5078
5079    // TODO: handle preferred activities missing while user has amnesia
5080    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5081            List<ResolveInfo> query, int priority, boolean always,
5082            boolean removeMatches, boolean debug, int userId) {
5083        if (!sUserManager.exists(userId)) return null;
5084        flags = updateFlagsForResolve(flags, userId, intent);
5085        // writer
5086        synchronized (mPackages) {
5087            if (intent.getSelector() != null) {
5088                intent = intent.getSelector();
5089            }
5090            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5091
5092            // Try to find a matching persistent preferred activity.
5093            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5094                    debug, userId);
5095
5096            // If a persistent preferred activity matched, use it.
5097            if (pri != null) {
5098                return pri;
5099            }
5100
5101            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5102            // Get the list of preferred activities that handle the intent
5103            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5104            List<PreferredActivity> prefs = pir != null
5105                    ? pir.queryIntent(intent, resolvedType,
5106                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5107                    : null;
5108            if (prefs != null && prefs.size() > 0) {
5109                boolean changed = false;
5110                try {
5111                    // First figure out how good the original match set is.
5112                    // We will only allow preferred activities that came
5113                    // from the same match quality.
5114                    int match = 0;
5115
5116                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5117
5118                    final int N = query.size();
5119                    for (int j=0; j<N; j++) {
5120                        final ResolveInfo ri = query.get(j);
5121                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5122                                + ": 0x" + Integer.toHexString(match));
5123                        if (ri.match > match) {
5124                            match = ri.match;
5125                        }
5126                    }
5127
5128                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5129                            + Integer.toHexString(match));
5130
5131                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5132                    final int M = prefs.size();
5133                    for (int i=0; i<M; i++) {
5134                        final PreferredActivity pa = prefs.get(i);
5135                        if (DEBUG_PREFERRED || debug) {
5136                            Slog.v(TAG, "Checking PreferredActivity ds="
5137                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5138                                    + "\n  component=" + pa.mPref.mComponent);
5139                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5140                        }
5141                        if (pa.mPref.mMatch != match) {
5142                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5143                                    + Integer.toHexString(pa.mPref.mMatch));
5144                            continue;
5145                        }
5146                        // If it's not an "always" type preferred activity and that's what we're
5147                        // looking for, skip it.
5148                        if (always && !pa.mPref.mAlways) {
5149                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5150                            continue;
5151                        }
5152                        final ActivityInfo ai = getActivityInfo(
5153                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5154                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5155                                userId);
5156                        if (DEBUG_PREFERRED || debug) {
5157                            Slog.v(TAG, "Found preferred activity:");
5158                            if (ai != null) {
5159                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5160                            } else {
5161                                Slog.v(TAG, "  null");
5162                            }
5163                        }
5164                        if (ai == null) {
5165                            // This previously registered preferred activity
5166                            // component is no longer known.  Most likely an update
5167                            // to the app was installed and in the new version this
5168                            // component no longer exists.  Clean it up by removing
5169                            // it from the preferred activities list, and skip it.
5170                            Slog.w(TAG, "Removing dangling preferred activity: "
5171                                    + pa.mPref.mComponent);
5172                            pir.removeFilter(pa);
5173                            changed = true;
5174                            continue;
5175                        }
5176                        for (int j=0; j<N; j++) {
5177                            final ResolveInfo ri = query.get(j);
5178                            if (!ri.activityInfo.applicationInfo.packageName
5179                                    .equals(ai.applicationInfo.packageName)) {
5180                                continue;
5181                            }
5182                            if (!ri.activityInfo.name.equals(ai.name)) {
5183                                continue;
5184                            }
5185
5186                            if (removeMatches) {
5187                                pir.removeFilter(pa);
5188                                changed = true;
5189                                if (DEBUG_PREFERRED) {
5190                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5191                                }
5192                                break;
5193                            }
5194
5195                            // Okay we found a previously set preferred or last chosen app.
5196                            // If the result set is different from when this
5197                            // was created, we need to clear it and re-ask the
5198                            // user their preference, if we're looking for an "always" type entry.
5199                            if (always && !pa.mPref.sameSet(query)) {
5200                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5201                                        + intent + " type " + resolvedType);
5202                                if (DEBUG_PREFERRED) {
5203                                    Slog.v(TAG, "Removing preferred activity since set changed "
5204                                            + pa.mPref.mComponent);
5205                                }
5206                                pir.removeFilter(pa);
5207                                // Re-add the filter as a "last chosen" entry (!always)
5208                                PreferredActivity lastChosen = new PreferredActivity(
5209                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5210                                pir.addFilter(lastChosen);
5211                                changed = true;
5212                                return null;
5213                            }
5214
5215                            // Yay! Either the set matched or we're looking for the last chosen
5216                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5217                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5218                            return ri;
5219                        }
5220                    }
5221                } finally {
5222                    if (changed) {
5223                        if (DEBUG_PREFERRED) {
5224                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5225                        }
5226                        scheduleWritePackageRestrictionsLocked(userId);
5227                    }
5228                }
5229            }
5230        }
5231        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5232        return null;
5233    }
5234
5235    /*
5236     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5237     */
5238    @Override
5239    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5240            int targetUserId) {
5241        mContext.enforceCallingOrSelfPermission(
5242                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5243        List<CrossProfileIntentFilter> matches =
5244                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5245        if (matches != null) {
5246            int size = matches.size();
5247            for (int i = 0; i < size; i++) {
5248                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5249            }
5250        }
5251        if (hasWebURI(intent)) {
5252            // cross-profile app linking works only towards the parent.
5253            final UserInfo parent = getProfileParent(sourceUserId);
5254            synchronized(mPackages) {
5255                int flags = updateFlagsForResolve(0, parent.id, intent);
5256                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5257                        intent, resolvedType, flags, sourceUserId, parent.id);
5258                return xpDomainInfo != null;
5259            }
5260        }
5261        return false;
5262    }
5263
5264    private UserInfo getProfileParent(int userId) {
5265        final long identity = Binder.clearCallingIdentity();
5266        try {
5267            return sUserManager.getProfileParent(userId);
5268        } finally {
5269            Binder.restoreCallingIdentity(identity);
5270        }
5271    }
5272
5273    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5274            String resolvedType, int userId) {
5275        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5276        if (resolver != null) {
5277            return resolver.queryIntent(intent, resolvedType, false, userId);
5278        }
5279        return null;
5280    }
5281
5282    @Override
5283    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5284            String resolvedType, int flags, int userId) {
5285        try {
5286            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5287
5288            return new ParceledListSlice<>(
5289                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5290        } finally {
5291            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5292        }
5293    }
5294
5295    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5296            String resolvedType, int flags, int userId) {
5297        if (!sUserManager.exists(userId)) return Collections.emptyList();
5298        flags = updateFlagsForResolve(flags, userId, intent);
5299        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5300                false /* requireFullPermission */, false /* checkShell */,
5301                "query intent activities");
5302        ComponentName comp = intent.getComponent();
5303        if (comp == null) {
5304            if (intent.getSelector() != null) {
5305                intent = intent.getSelector();
5306                comp = intent.getComponent();
5307            }
5308        }
5309
5310        if (comp != null) {
5311            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5312            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5313            if (ai != null) {
5314                final ResolveInfo ri = new ResolveInfo();
5315                ri.activityInfo = ai;
5316                list.add(ri);
5317            }
5318            return list;
5319        }
5320
5321        // reader
5322        synchronized (mPackages) {
5323            final String pkgName = intent.getPackage();
5324            if (pkgName == null) {
5325                List<CrossProfileIntentFilter> matchingFilters =
5326                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5327                // Check for results that need to skip the current profile.
5328                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5329                        resolvedType, flags, userId);
5330                if (xpResolveInfo != null) {
5331                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5332                    result.add(xpResolveInfo);
5333                    return filterIfNotSystemUser(result, userId);
5334                }
5335
5336                // Check for results in the current profile.
5337                List<ResolveInfo> result = mActivities.queryIntent(
5338                        intent, resolvedType, flags, userId);
5339                result = filterIfNotSystemUser(result, userId);
5340
5341                // Check for cross profile results.
5342                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5343                xpResolveInfo = queryCrossProfileIntents(
5344                        matchingFilters, intent, resolvedType, flags, userId,
5345                        hasNonNegativePriorityResult);
5346                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5347                    boolean isVisibleToUser = filterIfNotSystemUser(
5348                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5349                    if (isVisibleToUser) {
5350                        result.add(xpResolveInfo);
5351                        Collections.sort(result, mResolvePrioritySorter);
5352                    }
5353                }
5354                if (hasWebURI(intent)) {
5355                    CrossProfileDomainInfo xpDomainInfo = null;
5356                    final UserInfo parent = getProfileParent(userId);
5357                    if (parent != null) {
5358                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5359                                flags, userId, parent.id);
5360                    }
5361                    if (xpDomainInfo != null) {
5362                        if (xpResolveInfo != null) {
5363                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5364                            // in the result.
5365                            result.remove(xpResolveInfo);
5366                        }
5367                        if (result.size() == 0) {
5368                            result.add(xpDomainInfo.resolveInfo);
5369                            return result;
5370                        }
5371                    } else if (result.size() <= 1) {
5372                        return result;
5373                    }
5374                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5375                            xpDomainInfo, userId);
5376                    Collections.sort(result, mResolvePrioritySorter);
5377                }
5378                return result;
5379            }
5380            final PackageParser.Package pkg = mPackages.get(pkgName);
5381            if (pkg != null) {
5382                return filterIfNotSystemUser(
5383                        mActivities.queryIntentForPackage(
5384                                intent, resolvedType, flags, pkg.activities, userId),
5385                        userId);
5386            }
5387            return new ArrayList<ResolveInfo>();
5388        }
5389    }
5390
5391    private static class CrossProfileDomainInfo {
5392        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5393        ResolveInfo resolveInfo;
5394        /* Best domain verification status of the activities found in the other profile */
5395        int bestDomainVerificationStatus;
5396    }
5397
5398    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5399            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5400        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5401                sourceUserId)) {
5402            return null;
5403        }
5404        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5405                resolvedType, flags, parentUserId);
5406
5407        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5408            return null;
5409        }
5410        CrossProfileDomainInfo result = null;
5411        int size = resultTargetUser.size();
5412        for (int i = 0; i < size; i++) {
5413            ResolveInfo riTargetUser = resultTargetUser.get(i);
5414            // Intent filter verification is only for filters that specify a host. So don't return
5415            // those that handle all web uris.
5416            if (riTargetUser.handleAllWebDataURI) {
5417                continue;
5418            }
5419            String packageName = riTargetUser.activityInfo.packageName;
5420            PackageSetting ps = mSettings.mPackages.get(packageName);
5421            if (ps == null) {
5422                continue;
5423            }
5424            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5425            int status = (int)(verificationState >> 32);
5426            if (result == null) {
5427                result = new CrossProfileDomainInfo();
5428                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5429                        sourceUserId, parentUserId);
5430                result.bestDomainVerificationStatus = status;
5431            } else {
5432                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5433                        result.bestDomainVerificationStatus);
5434            }
5435        }
5436        // Don't consider matches with status NEVER across profiles.
5437        if (result != null && result.bestDomainVerificationStatus
5438                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5439            return null;
5440        }
5441        return result;
5442    }
5443
5444    /**
5445     * Verification statuses are ordered from the worse to the best, except for
5446     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5447     */
5448    private int bestDomainVerificationStatus(int status1, int status2) {
5449        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5450            return status2;
5451        }
5452        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5453            return status1;
5454        }
5455        return (int) MathUtils.max(status1, status2);
5456    }
5457
5458    private boolean isUserEnabled(int userId) {
5459        long callingId = Binder.clearCallingIdentity();
5460        try {
5461            UserInfo userInfo = sUserManager.getUserInfo(userId);
5462            return userInfo != null && userInfo.isEnabled();
5463        } finally {
5464            Binder.restoreCallingIdentity(callingId);
5465        }
5466    }
5467
5468    /**
5469     * Filter out activities with systemUserOnly flag set, when current user is not System.
5470     *
5471     * @return filtered list
5472     */
5473    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5474        if (userId == UserHandle.USER_SYSTEM) {
5475            return resolveInfos;
5476        }
5477        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5478            ResolveInfo info = resolveInfos.get(i);
5479            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5480                resolveInfos.remove(i);
5481            }
5482        }
5483        return resolveInfos;
5484    }
5485
5486    /**
5487     * @param resolveInfos list of resolve infos in descending priority order
5488     * @return if the list contains a resolve info with non-negative priority
5489     */
5490    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5491        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5492    }
5493
5494    private static boolean hasWebURI(Intent intent) {
5495        if (intent.getData() == null) {
5496            return false;
5497        }
5498        final String scheme = intent.getScheme();
5499        if (TextUtils.isEmpty(scheme)) {
5500            return false;
5501        }
5502        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5503    }
5504
5505    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5506            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5507            int userId) {
5508        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5509
5510        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5511            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5512                    candidates.size());
5513        }
5514
5515        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5516        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5517        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5518        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5519        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5520        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5521
5522        synchronized (mPackages) {
5523            final int count = candidates.size();
5524            // First, try to use linked apps. Partition the candidates into four lists:
5525            // one for the final results, one for the "do not use ever", one for "undefined status"
5526            // and finally one for "browser app type".
5527            for (int n=0; n<count; n++) {
5528                ResolveInfo info = candidates.get(n);
5529                String packageName = info.activityInfo.packageName;
5530                PackageSetting ps = mSettings.mPackages.get(packageName);
5531                if (ps != null) {
5532                    // Add to the special match all list (Browser use case)
5533                    if (info.handleAllWebDataURI) {
5534                        matchAllList.add(info);
5535                        continue;
5536                    }
5537                    // Try to get the status from User settings first
5538                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5539                    int status = (int)(packedStatus >> 32);
5540                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5541                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5542                        if (DEBUG_DOMAIN_VERIFICATION) {
5543                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5544                                    + " : linkgen=" + linkGeneration);
5545                        }
5546                        // Use link-enabled generation as preferredOrder, i.e.
5547                        // prefer newly-enabled over earlier-enabled.
5548                        info.preferredOrder = linkGeneration;
5549                        alwaysList.add(info);
5550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5551                        if (DEBUG_DOMAIN_VERIFICATION) {
5552                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5553                        }
5554                        neverList.add(info);
5555                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5556                        if (DEBUG_DOMAIN_VERIFICATION) {
5557                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5558                        }
5559                        alwaysAskList.add(info);
5560                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5561                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5562                        if (DEBUG_DOMAIN_VERIFICATION) {
5563                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5564                        }
5565                        undefinedList.add(info);
5566                    }
5567                }
5568            }
5569
5570            // We'll want to include browser possibilities in a few cases
5571            boolean includeBrowser = false;
5572
5573            // First try to add the "always" resolution(s) for the current user, if any
5574            if (alwaysList.size() > 0) {
5575                result.addAll(alwaysList);
5576            } else {
5577                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5578                result.addAll(undefinedList);
5579                // Maybe add one for the other profile.
5580                if (xpDomainInfo != null && (
5581                        xpDomainInfo.bestDomainVerificationStatus
5582                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5583                    result.add(xpDomainInfo.resolveInfo);
5584                }
5585                includeBrowser = true;
5586            }
5587
5588            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5589            // If there were 'always' entries their preferred order has been set, so we also
5590            // back that off to make the alternatives equivalent
5591            if (alwaysAskList.size() > 0) {
5592                for (ResolveInfo i : result) {
5593                    i.preferredOrder = 0;
5594                }
5595                result.addAll(alwaysAskList);
5596                includeBrowser = true;
5597            }
5598
5599            if (includeBrowser) {
5600                // Also add browsers (all of them or only the default one)
5601                if (DEBUG_DOMAIN_VERIFICATION) {
5602                    Slog.v(TAG, "   ...including browsers in candidate set");
5603                }
5604                if ((matchFlags & MATCH_ALL) != 0) {
5605                    result.addAll(matchAllList);
5606                } else {
5607                    // Browser/generic handling case.  If there's a default browser, go straight
5608                    // to that (but only if there is no other higher-priority match).
5609                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5610                    int maxMatchPrio = 0;
5611                    ResolveInfo defaultBrowserMatch = null;
5612                    final int numCandidates = matchAllList.size();
5613                    for (int n = 0; n < numCandidates; n++) {
5614                        ResolveInfo info = matchAllList.get(n);
5615                        // track the highest overall match priority...
5616                        if (info.priority > maxMatchPrio) {
5617                            maxMatchPrio = info.priority;
5618                        }
5619                        // ...and the highest-priority default browser match
5620                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5621                            if (defaultBrowserMatch == null
5622                                    || (defaultBrowserMatch.priority < info.priority)) {
5623                                if (debug) {
5624                                    Slog.v(TAG, "Considering default browser match " + info);
5625                                }
5626                                defaultBrowserMatch = info;
5627                            }
5628                        }
5629                    }
5630                    if (defaultBrowserMatch != null
5631                            && defaultBrowserMatch.priority >= maxMatchPrio
5632                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5633                    {
5634                        if (debug) {
5635                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5636                        }
5637                        result.add(defaultBrowserMatch);
5638                    } else {
5639                        result.addAll(matchAllList);
5640                    }
5641                }
5642
5643                // If there is nothing selected, add all candidates and remove the ones that the user
5644                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5645                if (result.size() == 0) {
5646                    result.addAll(candidates);
5647                    result.removeAll(neverList);
5648                }
5649            }
5650        }
5651        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5652            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5653                    result.size());
5654            for (ResolveInfo info : result) {
5655                Slog.v(TAG, "  + " + info.activityInfo);
5656            }
5657        }
5658        return result;
5659    }
5660
5661    // Returns a packed value as a long:
5662    //
5663    // high 'int'-sized word: link status: undefined/ask/never/always.
5664    // low 'int'-sized word: relative priority among 'always' results.
5665    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5666        long result = ps.getDomainVerificationStatusForUser(userId);
5667        // if none available, get the master status
5668        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5669            if (ps.getIntentFilterVerificationInfo() != null) {
5670                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5671            }
5672        }
5673        return result;
5674    }
5675
5676    private ResolveInfo querySkipCurrentProfileIntents(
5677            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5678            int flags, int sourceUserId) {
5679        if (matchingFilters != null) {
5680            int size = matchingFilters.size();
5681            for (int i = 0; i < size; i ++) {
5682                CrossProfileIntentFilter filter = matchingFilters.get(i);
5683                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5684                    // Checking if there are activities in the target user that can handle the
5685                    // intent.
5686                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5687                            resolvedType, flags, sourceUserId);
5688                    if (resolveInfo != null) {
5689                        return resolveInfo;
5690                    }
5691                }
5692            }
5693        }
5694        return null;
5695    }
5696
5697    // Return matching ResolveInfo in target user if any.
5698    private ResolveInfo queryCrossProfileIntents(
5699            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5700            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5701        if (matchingFilters != null) {
5702            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5703            // match the same intent. For performance reasons, it is better not to
5704            // run queryIntent twice for the same userId
5705            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5706            int size = matchingFilters.size();
5707            for (int i = 0; i < size; i++) {
5708                CrossProfileIntentFilter filter = matchingFilters.get(i);
5709                int targetUserId = filter.getTargetUserId();
5710                boolean skipCurrentProfile =
5711                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5712                boolean skipCurrentProfileIfNoMatchFound =
5713                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5714                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5715                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5716                    // Checking if there are activities in the target user that can handle the
5717                    // intent.
5718                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5719                            resolvedType, flags, sourceUserId);
5720                    if (resolveInfo != null) return resolveInfo;
5721                    alreadyTriedUserIds.put(targetUserId, true);
5722                }
5723            }
5724        }
5725        return null;
5726    }
5727
5728    /**
5729     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5730     * will forward the intent to the filter's target user.
5731     * Otherwise, returns null.
5732     */
5733    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5734            String resolvedType, int flags, int sourceUserId) {
5735        int targetUserId = filter.getTargetUserId();
5736        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5737                resolvedType, flags, targetUserId);
5738        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5739            // If all the matches in the target profile are suspended, return null.
5740            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5741                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5742                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5743                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5744                            targetUserId);
5745                }
5746            }
5747        }
5748        return null;
5749    }
5750
5751    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5752            int sourceUserId, int targetUserId) {
5753        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5754        long ident = Binder.clearCallingIdentity();
5755        boolean targetIsProfile;
5756        try {
5757            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5758        } finally {
5759            Binder.restoreCallingIdentity(ident);
5760        }
5761        String className;
5762        if (targetIsProfile) {
5763            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5764        } else {
5765            className = FORWARD_INTENT_TO_PARENT;
5766        }
5767        ComponentName forwardingActivityComponentName = new ComponentName(
5768                mAndroidApplication.packageName, className);
5769        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5770                sourceUserId);
5771        if (!targetIsProfile) {
5772            forwardingActivityInfo.showUserIcon = targetUserId;
5773            forwardingResolveInfo.noResourceId = true;
5774        }
5775        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5776        forwardingResolveInfo.priority = 0;
5777        forwardingResolveInfo.preferredOrder = 0;
5778        forwardingResolveInfo.match = 0;
5779        forwardingResolveInfo.isDefault = true;
5780        forwardingResolveInfo.filter = filter;
5781        forwardingResolveInfo.targetUserId = targetUserId;
5782        return forwardingResolveInfo;
5783    }
5784
5785    @Override
5786    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5787            Intent[] specifics, String[] specificTypes, Intent intent,
5788            String resolvedType, int flags, int userId) {
5789        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5790                specificTypes, intent, resolvedType, flags, userId));
5791    }
5792
5793    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5794            Intent[] specifics, String[] specificTypes, Intent intent,
5795            String resolvedType, int flags, int userId) {
5796        if (!sUserManager.exists(userId)) return Collections.emptyList();
5797        flags = updateFlagsForResolve(flags, userId, intent);
5798        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5799                false /* requireFullPermission */, false /* checkShell */,
5800                "query intent activity options");
5801        final String resultsAction = intent.getAction();
5802
5803        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5804                | PackageManager.GET_RESOLVED_FILTER, userId);
5805
5806        if (DEBUG_INTENT_MATCHING) {
5807            Log.v(TAG, "Query " + intent + ": " + results);
5808        }
5809
5810        int specificsPos = 0;
5811        int N;
5812
5813        // todo: note that the algorithm used here is O(N^2).  This
5814        // isn't a problem in our current environment, but if we start running
5815        // into situations where we have more than 5 or 10 matches then this
5816        // should probably be changed to something smarter...
5817
5818        // First we go through and resolve each of the specific items
5819        // that were supplied, taking care of removing any corresponding
5820        // duplicate items in the generic resolve list.
5821        if (specifics != null) {
5822            for (int i=0; i<specifics.length; i++) {
5823                final Intent sintent = specifics[i];
5824                if (sintent == null) {
5825                    continue;
5826                }
5827
5828                if (DEBUG_INTENT_MATCHING) {
5829                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5830                }
5831
5832                String action = sintent.getAction();
5833                if (resultsAction != null && resultsAction.equals(action)) {
5834                    // If this action was explicitly requested, then don't
5835                    // remove things that have it.
5836                    action = null;
5837                }
5838
5839                ResolveInfo ri = null;
5840                ActivityInfo ai = null;
5841
5842                ComponentName comp = sintent.getComponent();
5843                if (comp == null) {
5844                    ri = resolveIntent(
5845                        sintent,
5846                        specificTypes != null ? specificTypes[i] : null,
5847                            flags, userId);
5848                    if (ri == null) {
5849                        continue;
5850                    }
5851                    if (ri == mResolveInfo) {
5852                        // ACK!  Must do something better with this.
5853                    }
5854                    ai = ri.activityInfo;
5855                    comp = new ComponentName(ai.applicationInfo.packageName,
5856                            ai.name);
5857                } else {
5858                    ai = getActivityInfo(comp, flags, userId);
5859                    if (ai == null) {
5860                        continue;
5861                    }
5862                }
5863
5864                // Look for any generic query activities that are duplicates
5865                // of this specific one, and remove them from the results.
5866                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5867                N = results.size();
5868                int j;
5869                for (j=specificsPos; j<N; j++) {
5870                    ResolveInfo sri = results.get(j);
5871                    if ((sri.activityInfo.name.equals(comp.getClassName())
5872                            && sri.activityInfo.applicationInfo.packageName.equals(
5873                                    comp.getPackageName()))
5874                        || (action != null && sri.filter.matchAction(action))) {
5875                        results.remove(j);
5876                        if (DEBUG_INTENT_MATCHING) Log.v(
5877                            TAG, "Removing duplicate item from " + j
5878                            + " due to specific " + specificsPos);
5879                        if (ri == null) {
5880                            ri = sri;
5881                        }
5882                        j--;
5883                        N--;
5884                    }
5885                }
5886
5887                // Add this specific item to its proper place.
5888                if (ri == null) {
5889                    ri = new ResolveInfo();
5890                    ri.activityInfo = ai;
5891                }
5892                results.add(specificsPos, ri);
5893                ri.specificIndex = i;
5894                specificsPos++;
5895            }
5896        }
5897
5898        // Now we go through the remaining generic results and remove any
5899        // duplicate actions that are found here.
5900        N = results.size();
5901        for (int i=specificsPos; i<N-1; i++) {
5902            final ResolveInfo rii = results.get(i);
5903            if (rii.filter == null) {
5904                continue;
5905            }
5906
5907            // Iterate over all of the actions of this result's intent
5908            // filter...  typically this should be just one.
5909            final Iterator<String> it = rii.filter.actionsIterator();
5910            if (it == null) {
5911                continue;
5912            }
5913            while (it.hasNext()) {
5914                final String action = it.next();
5915                if (resultsAction != null && resultsAction.equals(action)) {
5916                    // If this action was explicitly requested, then don't
5917                    // remove things that have it.
5918                    continue;
5919                }
5920                for (int j=i+1; j<N; j++) {
5921                    final ResolveInfo rij = results.get(j);
5922                    if (rij.filter != null && rij.filter.hasAction(action)) {
5923                        results.remove(j);
5924                        if (DEBUG_INTENT_MATCHING) Log.v(
5925                            TAG, "Removing duplicate item from " + j
5926                            + " due to action " + action + " at " + i);
5927                        j--;
5928                        N--;
5929                    }
5930                }
5931            }
5932
5933            // If the caller didn't request filter information, drop it now
5934            // so we don't have to marshall/unmarshall it.
5935            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5936                rii.filter = null;
5937            }
5938        }
5939
5940        // Filter out the caller activity if so requested.
5941        if (caller != null) {
5942            N = results.size();
5943            for (int i=0; i<N; i++) {
5944                ActivityInfo ainfo = results.get(i).activityInfo;
5945                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5946                        && caller.getClassName().equals(ainfo.name)) {
5947                    results.remove(i);
5948                    break;
5949                }
5950            }
5951        }
5952
5953        // If the caller didn't request filter information,
5954        // drop them now so we don't have to
5955        // marshall/unmarshall it.
5956        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5957            N = results.size();
5958            for (int i=0; i<N; i++) {
5959                results.get(i).filter = null;
5960            }
5961        }
5962
5963        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5964        return results;
5965    }
5966
5967    @Override
5968    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5969            String resolvedType, int flags, int userId) {
5970        return new ParceledListSlice<>(
5971                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5972    }
5973
5974    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5975            String resolvedType, int flags, int userId) {
5976        if (!sUserManager.exists(userId)) return Collections.emptyList();
5977        flags = updateFlagsForResolve(flags, userId, intent);
5978        ComponentName comp = intent.getComponent();
5979        if (comp == null) {
5980            if (intent.getSelector() != null) {
5981                intent = intent.getSelector();
5982                comp = intent.getComponent();
5983            }
5984        }
5985        if (comp != null) {
5986            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5987            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5988            if (ai != null) {
5989                ResolveInfo ri = new ResolveInfo();
5990                ri.activityInfo = ai;
5991                list.add(ri);
5992            }
5993            return list;
5994        }
5995
5996        // reader
5997        synchronized (mPackages) {
5998            String pkgName = intent.getPackage();
5999            if (pkgName == null) {
6000                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6001            }
6002            final PackageParser.Package pkg = mPackages.get(pkgName);
6003            if (pkg != null) {
6004                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6005                        userId);
6006            }
6007            return Collections.emptyList();
6008        }
6009    }
6010
6011    @Override
6012    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6013        if (!sUserManager.exists(userId)) return null;
6014        flags = updateFlagsForResolve(flags, userId, intent);
6015        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6016        if (query != null) {
6017            if (query.size() >= 1) {
6018                // If there is more than one service with the same priority,
6019                // just arbitrarily pick the first one.
6020                return query.get(0);
6021            }
6022        }
6023        return null;
6024    }
6025
6026    @Override
6027    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6028            String resolvedType, int flags, int userId) {
6029        return new ParceledListSlice<>(
6030                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6031    }
6032
6033    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6034            String resolvedType, int flags, int userId) {
6035        if (!sUserManager.exists(userId)) return Collections.emptyList();
6036        flags = updateFlagsForResolve(flags, userId, intent);
6037        ComponentName comp = intent.getComponent();
6038        if (comp == null) {
6039            if (intent.getSelector() != null) {
6040                intent = intent.getSelector();
6041                comp = intent.getComponent();
6042            }
6043        }
6044        if (comp != null) {
6045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6046            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6047            if (si != null) {
6048                final ResolveInfo ri = new ResolveInfo();
6049                ri.serviceInfo = si;
6050                list.add(ri);
6051            }
6052            return list;
6053        }
6054
6055        // reader
6056        synchronized (mPackages) {
6057            String pkgName = intent.getPackage();
6058            if (pkgName == null) {
6059                return mServices.queryIntent(intent, resolvedType, flags, userId);
6060            }
6061            final PackageParser.Package pkg = mPackages.get(pkgName);
6062            if (pkg != null) {
6063                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6064                        userId);
6065            }
6066            return Collections.emptyList();
6067        }
6068    }
6069
6070    @Override
6071    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6072            String resolvedType, int flags, int userId) {
6073        return new ParceledListSlice<>(
6074                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6075    }
6076
6077    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6078            Intent intent, String resolvedType, int flags, int userId) {
6079        if (!sUserManager.exists(userId)) return Collections.emptyList();
6080        flags = updateFlagsForResolve(flags, userId, intent);
6081        ComponentName comp = intent.getComponent();
6082        if (comp == null) {
6083            if (intent.getSelector() != null) {
6084                intent = intent.getSelector();
6085                comp = intent.getComponent();
6086            }
6087        }
6088        if (comp != null) {
6089            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6090            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6091            if (pi != null) {
6092                final ResolveInfo ri = new ResolveInfo();
6093                ri.providerInfo = pi;
6094                list.add(ri);
6095            }
6096            return list;
6097        }
6098
6099        // reader
6100        synchronized (mPackages) {
6101            String pkgName = intent.getPackage();
6102            if (pkgName == null) {
6103                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6104            }
6105            final PackageParser.Package pkg = mPackages.get(pkgName);
6106            if (pkg != null) {
6107                return mProviders.queryIntentForPackage(
6108                        intent, resolvedType, flags, pkg.providers, userId);
6109            }
6110            return Collections.emptyList();
6111        }
6112    }
6113
6114    @Override
6115    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6116        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6117        flags = updateFlagsForPackage(flags, userId, null);
6118        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6120                true /* requireFullPermission */, false /* checkShell */,
6121                "get installed packages");
6122
6123        // writer
6124        synchronized (mPackages) {
6125            ArrayList<PackageInfo> list;
6126            if (listUninstalled) {
6127                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6128                for (PackageSetting ps : mSettings.mPackages.values()) {
6129                    final PackageInfo pi;
6130                    if (ps.pkg != null) {
6131                        pi = generatePackageInfo(ps, flags, userId);
6132                    } else {
6133                        pi = generatePackageInfo(ps, flags, userId);
6134                    }
6135                    if (pi != null) {
6136                        list.add(pi);
6137                    }
6138                }
6139            } else {
6140                list = new ArrayList<PackageInfo>(mPackages.size());
6141                for (PackageParser.Package p : mPackages.values()) {
6142                    final PackageInfo pi =
6143                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6144                    if (pi != null) {
6145                        list.add(pi);
6146                    }
6147                }
6148            }
6149
6150            return new ParceledListSlice<PackageInfo>(list);
6151        }
6152    }
6153
6154    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6155            String[] permissions, boolean[] tmp, int flags, int userId) {
6156        int numMatch = 0;
6157        final PermissionsState permissionsState = ps.getPermissionsState();
6158        for (int i=0; i<permissions.length; i++) {
6159            final String permission = permissions[i];
6160            if (permissionsState.hasPermission(permission, userId)) {
6161                tmp[i] = true;
6162                numMatch++;
6163            } else {
6164                tmp[i] = false;
6165            }
6166        }
6167        if (numMatch == 0) {
6168            return;
6169        }
6170        final PackageInfo pi;
6171        if (ps.pkg != null) {
6172            pi = generatePackageInfo(ps, flags, userId);
6173        } else {
6174            pi = generatePackageInfo(ps, flags, userId);
6175        }
6176        // The above might return null in cases of uninstalled apps or install-state
6177        // skew across users/profiles.
6178        if (pi != null) {
6179            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6180                if (numMatch == permissions.length) {
6181                    pi.requestedPermissions = permissions;
6182                } else {
6183                    pi.requestedPermissions = new String[numMatch];
6184                    numMatch = 0;
6185                    for (int i=0; i<permissions.length; i++) {
6186                        if (tmp[i]) {
6187                            pi.requestedPermissions[numMatch] = permissions[i];
6188                            numMatch++;
6189                        }
6190                    }
6191                }
6192            }
6193            list.add(pi);
6194        }
6195    }
6196
6197    @Override
6198    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6199            String[] permissions, int flags, int userId) {
6200        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6201        flags = updateFlagsForPackage(flags, userId, permissions);
6202        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6203
6204        // writer
6205        synchronized (mPackages) {
6206            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6207            boolean[] tmpBools = new boolean[permissions.length];
6208            if (listUninstalled) {
6209                for (PackageSetting ps : mSettings.mPackages.values()) {
6210                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6211                }
6212            } else {
6213                for (PackageParser.Package pkg : mPackages.values()) {
6214                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6215                    if (ps != null) {
6216                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6217                                userId);
6218                    }
6219                }
6220            }
6221
6222            return new ParceledListSlice<PackageInfo>(list);
6223        }
6224    }
6225
6226    @Override
6227    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6228        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6229        flags = updateFlagsForApplication(flags, userId, null);
6230        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6231
6232        // writer
6233        synchronized (mPackages) {
6234            ArrayList<ApplicationInfo> list;
6235            if (listUninstalled) {
6236                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6237                for (PackageSetting ps : mSettings.mPackages.values()) {
6238                    ApplicationInfo ai;
6239                    if (ps.pkg != null) {
6240                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6241                                ps.readUserState(userId), userId);
6242                    } else {
6243                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6244                    }
6245                    if (ai != null) {
6246                        list.add(ai);
6247                    }
6248                }
6249            } else {
6250                list = new ArrayList<ApplicationInfo>(mPackages.size());
6251                for (PackageParser.Package p : mPackages.values()) {
6252                    if (p.mExtras != null) {
6253                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6254                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6255                        if (ai != null) {
6256                            list.add(ai);
6257                        }
6258                    }
6259                }
6260            }
6261
6262            return new ParceledListSlice<ApplicationInfo>(list);
6263        }
6264    }
6265
6266    @Override
6267    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6268        if (DISABLE_EPHEMERAL_APPS) {
6269            return null;
6270        }
6271
6272        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6273                "getEphemeralApplications");
6274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6275                true /* requireFullPermission */, false /* checkShell */,
6276                "getEphemeralApplications");
6277        synchronized (mPackages) {
6278            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6279                    .getEphemeralApplicationsLPw(userId);
6280            if (ephemeralApps != null) {
6281                return new ParceledListSlice<>(ephemeralApps);
6282            }
6283        }
6284        return null;
6285    }
6286
6287    @Override
6288    public boolean isEphemeralApplication(String packageName, int userId) {
6289        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6290                true /* requireFullPermission */, false /* checkShell */,
6291                "isEphemeral");
6292        if (DISABLE_EPHEMERAL_APPS) {
6293            return false;
6294        }
6295
6296        if (!isCallerSameApp(packageName)) {
6297            return false;
6298        }
6299        synchronized (mPackages) {
6300            PackageParser.Package pkg = mPackages.get(packageName);
6301            if (pkg != null) {
6302                return pkg.applicationInfo.isEphemeralApp();
6303            }
6304        }
6305        return false;
6306    }
6307
6308    @Override
6309    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6310        if (DISABLE_EPHEMERAL_APPS) {
6311            return null;
6312        }
6313
6314        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6315                true /* requireFullPermission */, false /* checkShell */,
6316                "getCookie");
6317        if (!isCallerSameApp(packageName)) {
6318            return null;
6319        }
6320        synchronized (mPackages) {
6321            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6322                    packageName, userId);
6323        }
6324    }
6325
6326    @Override
6327    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6328        if (DISABLE_EPHEMERAL_APPS) {
6329            return true;
6330        }
6331
6332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6333                true /* requireFullPermission */, true /* checkShell */,
6334                "setCookie");
6335        if (!isCallerSameApp(packageName)) {
6336            return false;
6337        }
6338        synchronized (mPackages) {
6339            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6340                    packageName, cookie, userId);
6341        }
6342    }
6343
6344    @Override
6345    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6346        if (DISABLE_EPHEMERAL_APPS) {
6347            return null;
6348        }
6349
6350        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6351                "getEphemeralApplicationIcon");
6352        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6353                true /* requireFullPermission */, false /* checkShell */,
6354                "getEphemeralApplicationIcon");
6355        synchronized (mPackages) {
6356            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6357                    packageName, userId);
6358        }
6359    }
6360
6361    private boolean isCallerSameApp(String packageName) {
6362        PackageParser.Package pkg = mPackages.get(packageName);
6363        return pkg != null
6364                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6365    }
6366
6367    @Override
6368    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6369        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6370    }
6371
6372    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6373        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6374
6375        // reader
6376        synchronized (mPackages) {
6377            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6378            final int userId = UserHandle.getCallingUserId();
6379            while (i.hasNext()) {
6380                final PackageParser.Package p = i.next();
6381                if (p.applicationInfo == null) continue;
6382
6383                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6384                        && !p.applicationInfo.isDirectBootAware();
6385                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6386                        && p.applicationInfo.isDirectBootAware();
6387
6388                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6389                        && (!mSafeMode || isSystemApp(p))
6390                        && (matchesUnaware || matchesAware)) {
6391                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6392                    if (ps != null) {
6393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6394                                ps.readUserState(userId), userId);
6395                        if (ai != null) {
6396                            finalList.add(ai);
6397                        }
6398                    }
6399                }
6400            }
6401        }
6402
6403        return finalList;
6404    }
6405
6406    @Override
6407    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6408        if (!sUserManager.exists(userId)) return null;
6409        flags = updateFlagsForComponent(flags, userId, name);
6410        // reader
6411        synchronized (mPackages) {
6412            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6413            PackageSetting ps = provider != null
6414                    ? mSettings.mPackages.get(provider.owner.packageName)
6415                    : null;
6416            return ps != null
6417                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6418                    ? PackageParser.generateProviderInfo(provider, flags,
6419                            ps.readUserState(userId), userId)
6420                    : null;
6421        }
6422    }
6423
6424    /**
6425     * @deprecated
6426     */
6427    @Deprecated
6428    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6429        // reader
6430        synchronized (mPackages) {
6431            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6432                    .entrySet().iterator();
6433            final int userId = UserHandle.getCallingUserId();
6434            while (i.hasNext()) {
6435                Map.Entry<String, PackageParser.Provider> entry = i.next();
6436                PackageParser.Provider p = entry.getValue();
6437                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6438
6439                if (ps != null && p.syncable
6440                        && (!mSafeMode || (p.info.applicationInfo.flags
6441                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6442                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6443                            ps.readUserState(userId), userId);
6444                    if (info != null) {
6445                        outNames.add(entry.getKey());
6446                        outInfo.add(info);
6447                    }
6448                }
6449            }
6450        }
6451    }
6452
6453    @Override
6454    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6455            int uid, int flags) {
6456        final int userId = processName != null ? UserHandle.getUserId(uid)
6457                : UserHandle.getCallingUserId();
6458        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6459        flags = updateFlagsForComponent(flags, userId, processName);
6460
6461        ArrayList<ProviderInfo> finalList = null;
6462        // reader
6463        synchronized (mPackages) {
6464            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6465            while (i.hasNext()) {
6466                final PackageParser.Provider p = i.next();
6467                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6468                if (ps != null && p.info.authority != null
6469                        && (processName == null
6470                                || (p.info.processName.equals(processName)
6471                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6472                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6473                    if (finalList == null) {
6474                        finalList = new ArrayList<ProviderInfo>(3);
6475                    }
6476                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6477                            ps.readUserState(userId), userId);
6478                    if (info != null) {
6479                        finalList.add(info);
6480                    }
6481                }
6482            }
6483        }
6484
6485        if (finalList != null) {
6486            Collections.sort(finalList, mProviderInitOrderSorter);
6487            return new ParceledListSlice<ProviderInfo>(finalList);
6488        }
6489
6490        return ParceledListSlice.emptyList();
6491    }
6492
6493    @Override
6494    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6495        // reader
6496        synchronized (mPackages) {
6497            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6498            return PackageParser.generateInstrumentationInfo(i, flags);
6499        }
6500    }
6501
6502    @Override
6503    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6504            String targetPackage, int flags) {
6505        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6506    }
6507
6508    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6509            int flags) {
6510        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6511
6512        // reader
6513        synchronized (mPackages) {
6514            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6515            while (i.hasNext()) {
6516                final PackageParser.Instrumentation p = i.next();
6517                if (targetPackage == null
6518                        || targetPackage.equals(p.info.targetPackage)) {
6519                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6520                            flags);
6521                    if (ii != null) {
6522                        finalList.add(ii);
6523                    }
6524                }
6525            }
6526        }
6527
6528        return finalList;
6529    }
6530
6531    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6532        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6533        if (overlays == null) {
6534            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6535            return;
6536        }
6537        for (PackageParser.Package opkg : overlays.values()) {
6538            // Not much to do if idmap fails: we already logged the error
6539            // and we certainly don't want to abort installation of pkg simply
6540            // because an overlay didn't fit properly. For these reasons,
6541            // ignore the return value of createIdmapForPackagePairLI.
6542            createIdmapForPackagePairLI(pkg, opkg);
6543        }
6544    }
6545
6546    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6547            PackageParser.Package opkg) {
6548        if (!opkg.mTrustedOverlay) {
6549            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6550                    opkg.baseCodePath + ": overlay not trusted");
6551            return false;
6552        }
6553        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6554        if (overlaySet == null) {
6555            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6556                    opkg.baseCodePath + " but target package has no known overlays");
6557            return false;
6558        }
6559        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6560        // TODO: generate idmap for split APKs
6561        try {
6562            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6563        } catch (InstallerException e) {
6564            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6565                    + opkg.baseCodePath);
6566            return false;
6567        }
6568        PackageParser.Package[] overlayArray =
6569            overlaySet.values().toArray(new PackageParser.Package[0]);
6570        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6571            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6572                return p1.mOverlayPriority - p2.mOverlayPriority;
6573            }
6574        };
6575        Arrays.sort(overlayArray, cmp);
6576
6577        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6578        int i = 0;
6579        for (PackageParser.Package p : overlayArray) {
6580            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6581        }
6582        return true;
6583    }
6584
6585    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6586        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6587        try {
6588            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6589        } finally {
6590            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6591        }
6592    }
6593
6594    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6595        final File[] files = dir.listFiles();
6596        if (ArrayUtils.isEmpty(files)) {
6597            Log.d(TAG, "No files in app dir " + dir);
6598            return;
6599        }
6600
6601        if (DEBUG_PACKAGE_SCANNING) {
6602            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6603                    + " flags=0x" + Integer.toHexString(parseFlags));
6604        }
6605
6606        for (File file : files) {
6607            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6608                    && !PackageInstallerService.isStageName(file.getName());
6609            if (!isPackage) {
6610                // Ignore entries which are not packages
6611                continue;
6612            }
6613            try {
6614                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6615                        scanFlags, currentTime, null);
6616            } catch (PackageManagerException e) {
6617                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6618
6619                // Delete invalid userdata apps
6620                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6621                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6622                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6623                    removeCodePathLI(file);
6624                }
6625            }
6626        }
6627    }
6628
6629    private static File getSettingsProblemFile() {
6630        File dataDir = Environment.getDataDirectory();
6631        File systemDir = new File(dataDir, "system");
6632        File fname = new File(systemDir, "uiderrors.txt");
6633        return fname;
6634    }
6635
6636    static void reportSettingsProblem(int priority, String msg) {
6637        logCriticalInfo(priority, msg);
6638    }
6639
6640    static void logCriticalInfo(int priority, String msg) {
6641        Slog.println(priority, TAG, msg);
6642        EventLogTags.writePmCriticalInfo(msg);
6643        try {
6644            File fname = getSettingsProblemFile();
6645            FileOutputStream out = new FileOutputStream(fname, true);
6646            PrintWriter pw = new FastPrintWriter(out);
6647            SimpleDateFormat formatter = new SimpleDateFormat();
6648            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6649            pw.println(dateString + ": " + msg);
6650            pw.close();
6651            FileUtils.setPermissions(
6652                    fname.toString(),
6653                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6654                    -1, -1);
6655        } catch (java.io.IOException e) {
6656        }
6657    }
6658
6659    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6660            final int policyFlags) throws PackageManagerException {
6661        if (ps != null
6662                && ps.codePath.equals(srcFile)
6663                && ps.timeStamp == srcFile.lastModified()
6664                && !isCompatSignatureUpdateNeeded(pkg)
6665                && !isRecoverSignatureUpdateNeeded(pkg)) {
6666            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6667            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6668            ArraySet<PublicKey> signingKs;
6669            synchronized (mPackages) {
6670                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6671            }
6672            if (ps.signatures.mSignatures != null
6673                    && ps.signatures.mSignatures.length != 0
6674                    && signingKs != null) {
6675                // Optimization: reuse the existing cached certificates
6676                // if the package appears to be unchanged.
6677                pkg.mSignatures = ps.signatures.mSignatures;
6678                pkg.mSigningKeys = signingKs;
6679                return;
6680            }
6681
6682            Slog.w(TAG, "PackageSetting for " + ps.name
6683                    + " is missing signatures.  Collecting certs again to recover them.");
6684        } else {
6685            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6686        }
6687
6688        try {
6689            PackageParser.collectCertificates(pkg, policyFlags);
6690        } catch (PackageParserException e) {
6691            throw PackageManagerException.from(e);
6692        }
6693    }
6694
6695    /**
6696     *  Traces a package scan.
6697     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6698     */
6699    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6700            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6701        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6702        try {
6703            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6704        } finally {
6705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6706        }
6707    }
6708
6709    /**
6710     *  Scans a package and returns the newly parsed package.
6711     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6712     */
6713    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6714            long currentTime, UserHandle user) throws PackageManagerException {
6715        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6716        PackageParser pp = new PackageParser();
6717        pp.setSeparateProcesses(mSeparateProcesses);
6718        pp.setOnlyCoreApps(mOnlyCore);
6719        pp.setDisplayMetrics(mMetrics);
6720
6721        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6722            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6723        }
6724
6725        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6726        final PackageParser.Package pkg;
6727        try {
6728            pkg = pp.parsePackage(scanFile, parseFlags);
6729        } catch (PackageParserException e) {
6730            throw PackageManagerException.from(e);
6731        } finally {
6732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6733        }
6734
6735        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6736    }
6737
6738    /**
6739     *  Scans a package and returns the newly parsed package.
6740     *  @throws PackageManagerException on a parse error.
6741     */
6742    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6743            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6744            throws PackageManagerException {
6745        // If the package has children and this is the first dive in the function
6746        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6747        // packages (parent and children) would be successfully scanned before the
6748        // actual scan since scanning mutates internal state and we want to atomically
6749        // install the package and its children.
6750        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6751            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6752                scanFlags |= SCAN_CHECK_ONLY;
6753            }
6754        } else {
6755            scanFlags &= ~SCAN_CHECK_ONLY;
6756        }
6757
6758        // Scan the parent
6759        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6760                scanFlags, currentTime, user);
6761
6762        // Scan the children
6763        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6764        for (int i = 0; i < childCount; i++) {
6765            PackageParser.Package childPackage = pkg.childPackages.get(i);
6766            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6767                    currentTime, user);
6768        }
6769
6770
6771        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6772            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6773        }
6774
6775        return scannedPkg;
6776    }
6777
6778    /**
6779     *  Scans a package and returns the newly parsed package.
6780     *  @throws PackageManagerException on a parse error.
6781     */
6782    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6783            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6784            throws PackageManagerException {
6785        PackageSetting ps = null;
6786        PackageSetting updatedPkg;
6787        // reader
6788        synchronized (mPackages) {
6789            // Look to see if we already know about this package.
6790            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6791            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6792                // This package has been renamed to its original name.  Let's
6793                // use that.
6794                ps = mSettings.peekPackageLPr(oldName);
6795            }
6796            // If there was no original package, see one for the real package name.
6797            if (ps == null) {
6798                ps = mSettings.peekPackageLPr(pkg.packageName);
6799            }
6800            // Check to see if this package could be hiding/updating a system
6801            // package.  Must look for it either under the original or real
6802            // package name depending on our state.
6803            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6804            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6805
6806            // If this is a package we don't know about on the system partition, we
6807            // may need to remove disabled child packages on the system partition
6808            // or may need to not add child packages if the parent apk is updated
6809            // on the data partition and no longer defines this child package.
6810            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6811                // If this is a parent package for an updated system app and this system
6812                // app got an OTA update which no longer defines some of the child packages
6813                // we have to prune them from the disabled system packages.
6814                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6815                if (disabledPs != null) {
6816                    final int scannedChildCount = (pkg.childPackages != null)
6817                            ? pkg.childPackages.size() : 0;
6818                    final int disabledChildCount = disabledPs.childPackageNames != null
6819                            ? disabledPs.childPackageNames.size() : 0;
6820                    for (int i = 0; i < disabledChildCount; i++) {
6821                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6822                        boolean disabledPackageAvailable = false;
6823                        for (int j = 0; j < scannedChildCount; j++) {
6824                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6825                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6826                                disabledPackageAvailable = true;
6827                                break;
6828                            }
6829                         }
6830                         if (!disabledPackageAvailable) {
6831                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6832                         }
6833                    }
6834                }
6835            }
6836        }
6837
6838        boolean updatedPkgBetter = false;
6839        // First check if this is a system package that may involve an update
6840        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6841            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6842            // it needs to drop FLAG_PRIVILEGED.
6843            if (locationIsPrivileged(scanFile)) {
6844                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6845            } else {
6846                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6847            }
6848
6849            if (ps != null && !ps.codePath.equals(scanFile)) {
6850                // The path has changed from what was last scanned...  check the
6851                // version of the new path against what we have stored to determine
6852                // what to do.
6853                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6854                if (pkg.mVersionCode <= ps.versionCode) {
6855                    // The system package has been updated and the code path does not match
6856                    // Ignore entry. Skip it.
6857                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6858                            + " ignored: updated version " + ps.versionCode
6859                            + " better than this " + pkg.mVersionCode);
6860                    if (!updatedPkg.codePath.equals(scanFile)) {
6861                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6862                                + ps.name + " changing from " + updatedPkg.codePathString
6863                                + " to " + scanFile);
6864                        updatedPkg.codePath = scanFile;
6865                        updatedPkg.codePathString = scanFile.toString();
6866                        updatedPkg.resourcePath = scanFile;
6867                        updatedPkg.resourcePathString = scanFile.toString();
6868                    }
6869                    updatedPkg.pkg = pkg;
6870                    updatedPkg.versionCode = pkg.mVersionCode;
6871
6872                    // Update the disabled system child packages to point to the package too.
6873                    final int childCount = updatedPkg.childPackageNames != null
6874                            ? updatedPkg.childPackageNames.size() : 0;
6875                    for (int i = 0; i < childCount; i++) {
6876                        String childPackageName = updatedPkg.childPackageNames.get(i);
6877                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6878                                childPackageName);
6879                        if (updatedChildPkg != null) {
6880                            updatedChildPkg.pkg = pkg;
6881                            updatedChildPkg.versionCode = pkg.mVersionCode;
6882                        }
6883                    }
6884
6885                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6886                            + scanFile + " ignored: updated version " + ps.versionCode
6887                            + " better than this " + pkg.mVersionCode);
6888                } else {
6889                    // The current app on the system partition is better than
6890                    // what we have updated to on the data partition; switch
6891                    // back to the system partition version.
6892                    // At this point, its safely assumed that package installation for
6893                    // apps in system partition will go through. If not there won't be a working
6894                    // version of the app
6895                    // writer
6896                    synchronized (mPackages) {
6897                        // Just remove the loaded entries from package lists.
6898                        mPackages.remove(ps.name);
6899                    }
6900
6901                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6902                            + " reverting from " + ps.codePathString
6903                            + ": new version " + pkg.mVersionCode
6904                            + " better than installed " + ps.versionCode);
6905
6906                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6907                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6908                    synchronized (mInstallLock) {
6909                        args.cleanUpResourcesLI();
6910                    }
6911                    synchronized (mPackages) {
6912                        mSettings.enableSystemPackageLPw(ps.name);
6913                    }
6914                    updatedPkgBetter = true;
6915                }
6916            }
6917        }
6918
6919        if (updatedPkg != null) {
6920            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6921            // initially
6922            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6923
6924            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6925            // flag set initially
6926            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6927                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6928            }
6929        }
6930
6931        // Verify certificates against what was last scanned
6932        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6933
6934        /*
6935         * A new system app appeared, but we already had a non-system one of the
6936         * same name installed earlier.
6937         */
6938        boolean shouldHideSystemApp = false;
6939        if (updatedPkg == null && ps != null
6940                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6941            /*
6942             * Check to make sure the signatures match first. If they don't,
6943             * wipe the installed application and its data.
6944             */
6945            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6946                    != PackageManager.SIGNATURE_MATCH) {
6947                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6948                        + " signatures don't match existing userdata copy; removing");
6949                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6950                        "scanPackageInternalLI")) {
6951                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6952                }
6953                ps = null;
6954            } else {
6955                /*
6956                 * If the newly-added system app is an older version than the
6957                 * already installed version, hide it. It will be scanned later
6958                 * and re-added like an update.
6959                 */
6960                if (pkg.mVersionCode <= ps.versionCode) {
6961                    shouldHideSystemApp = true;
6962                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6963                            + " but new version " + pkg.mVersionCode + " better than installed "
6964                            + ps.versionCode + "; hiding system");
6965                } else {
6966                    /*
6967                     * The newly found system app is a newer version that the
6968                     * one previously installed. Simply remove the
6969                     * already-installed application and replace it with our own
6970                     * while keeping the application data.
6971                     */
6972                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6973                            + " reverting from " + ps.codePathString + ": new version "
6974                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6975                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6976                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6977                    synchronized (mInstallLock) {
6978                        args.cleanUpResourcesLI();
6979                    }
6980                }
6981            }
6982        }
6983
6984        // The apk is forward locked (not public) if its code and resources
6985        // are kept in different files. (except for app in either system or
6986        // vendor path).
6987        // TODO grab this value from PackageSettings
6988        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6989            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6990                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6991            }
6992        }
6993
6994        // TODO: extend to support forward-locked splits
6995        String resourcePath = null;
6996        String baseResourcePath = null;
6997        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6998            if (ps != null && ps.resourcePathString != null) {
6999                resourcePath = ps.resourcePathString;
7000                baseResourcePath = ps.resourcePathString;
7001            } else {
7002                // Should not happen at all. Just log an error.
7003                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7004            }
7005        } else {
7006            resourcePath = pkg.codePath;
7007            baseResourcePath = pkg.baseCodePath;
7008        }
7009
7010        // Set application objects path explicitly.
7011        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7012        pkg.setApplicationInfoCodePath(pkg.codePath);
7013        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7014        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7015        pkg.setApplicationInfoResourcePath(resourcePath);
7016        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7017        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7018
7019        // Note that we invoke the following method only if we are about to unpack an application
7020        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7021                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7022
7023        /*
7024         * If the system app should be overridden by a previously installed
7025         * data, hide the system app now and let the /data/app scan pick it up
7026         * again.
7027         */
7028        if (shouldHideSystemApp) {
7029            synchronized (mPackages) {
7030                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7031            }
7032        }
7033
7034        return scannedPkg;
7035    }
7036
7037    private static String fixProcessName(String defProcessName,
7038            String processName, int uid) {
7039        if (processName == null) {
7040            return defProcessName;
7041        }
7042        return processName;
7043    }
7044
7045    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7046            throws PackageManagerException {
7047        if (pkgSetting.signatures.mSignatures != null) {
7048            // Already existing package. Make sure signatures match
7049            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7050                    == PackageManager.SIGNATURE_MATCH;
7051            if (!match) {
7052                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7053                        == PackageManager.SIGNATURE_MATCH;
7054            }
7055            if (!match) {
7056                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7057                        == PackageManager.SIGNATURE_MATCH;
7058            }
7059            if (!match) {
7060                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7061                        + pkg.packageName + " signatures do not match the "
7062                        + "previously installed version; ignoring!");
7063            }
7064        }
7065
7066        // Check for shared user signatures
7067        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7068            // Already existing package. Make sure signatures match
7069            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7070                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7071            if (!match) {
7072                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7073                        == PackageManager.SIGNATURE_MATCH;
7074            }
7075            if (!match) {
7076                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7077                        == PackageManager.SIGNATURE_MATCH;
7078            }
7079            if (!match) {
7080                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7081                        "Package " + pkg.packageName
7082                        + " has no signatures that match those in shared user "
7083                        + pkgSetting.sharedUser.name + "; ignoring!");
7084            }
7085        }
7086    }
7087
7088    /**
7089     * Enforces that only the system UID or root's UID can call a method exposed
7090     * via Binder.
7091     *
7092     * @param message used as message if SecurityException is thrown
7093     * @throws SecurityException if the caller is not system or root
7094     */
7095    private static final void enforceSystemOrRoot(String message) {
7096        final int uid = Binder.getCallingUid();
7097        if (uid != Process.SYSTEM_UID && uid != 0) {
7098            throw new SecurityException(message);
7099        }
7100    }
7101
7102    @Override
7103    public void performFstrimIfNeeded() {
7104        enforceSystemOrRoot("Only the system can request fstrim");
7105
7106        // Before everything else, see whether we need to fstrim.
7107        try {
7108            IMountService ms = PackageHelper.getMountService();
7109            if (ms != null) {
7110                final boolean isUpgrade = isUpgrade();
7111                boolean doTrim = isUpgrade;
7112                if (doTrim) {
7113                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7114                } else {
7115                    final long interval = android.provider.Settings.Global.getLong(
7116                            mContext.getContentResolver(),
7117                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7118                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7119                    if (interval > 0) {
7120                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7121                        if (timeSinceLast > interval) {
7122                            doTrim = true;
7123                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7124                                    + "; running immediately");
7125                        }
7126                    }
7127                }
7128                if (doTrim) {
7129                    if (!isFirstBoot()) {
7130                        try {
7131                            ActivityManagerNative.getDefault().showBootMessage(
7132                                    mContext.getResources().getString(
7133                                            R.string.android_upgrading_fstrim), true);
7134                        } catch (RemoteException e) {
7135                        }
7136                    }
7137                    ms.runMaintenance();
7138                }
7139            } else {
7140                Slog.e(TAG, "Mount service unavailable!");
7141            }
7142        } catch (RemoteException e) {
7143            // Can't happen; MountService is local
7144        }
7145    }
7146
7147    @Override
7148    public void updatePackagesIfNeeded() {
7149        enforceSystemOrRoot("Only the system can request package update");
7150
7151        // We need to re-extract after an OTA.
7152        boolean causeUpgrade = isUpgrade();
7153
7154        // First boot or factory reset.
7155        // Note: we also handle devices that are upgrading to N right now as if it is their
7156        //       first boot, as they do not have profile data.
7157        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7158
7159        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7160        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7161
7162        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7163            return;
7164        }
7165
7166        List<PackageParser.Package> pkgs;
7167        synchronized (mPackages) {
7168            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7169        }
7170
7171        int curr = 0;
7172        int total = pkgs.size();
7173        for (PackageParser.Package pkg : pkgs) {
7174            curr++;
7175
7176            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7177                if (DEBUG_DEXOPT) {
7178                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7179                }
7180                continue;
7181            }
7182
7183            if (DEBUG_DEXOPT) {
7184                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7185            }
7186
7187            if (!isFirstBoot()) {
7188                try {
7189                    ActivityManagerNative.getDefault().showBootMessage(
7190                            mContext.getResources().getString(R.string.android_upgrading_apk,
7191                                    curr, total), true);
7192                } catch (RemoteException e) {
7193                }
7194            }
7195
7196            performDexOpt(pkg.packageName,
7197                    null /* instructionSet */,
7198                    true /* checkProfiles */,
7199                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7200                    false /* force */);
7201        }
7202    }
7203
7204    @Override
7205    public void notifyPackageUse(String packageName, int reason) {
7206        synchronized (mPackages) {
7207            PackageParser.Package p = mPackages.get(packageName);
7208            if (p == null) {
7209                return;
7210            }
7211            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7212        }
7213    }
7214
7215    // TODO: this is not used nor needed. Delete it.
7216    @Override
7217    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7218        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7219                getFullCompilerFilter(), false /* force */);
7220    }
7221
7222    @Override
7223    public boolean performDexOpt(String packageName, String instructionSet,
7224            boolean checkProfiles, int compileReason, boolean force) {
7225        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7226                getCompilerFilterForReason(compileReason), force);
7227    }
7228
7229    @Override
7230    public boolean performDexOptMode(String packageName, String instructionSet,
7231            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7232        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7233                targetCompilerFilter, force);
7234    }
7235
7236    private boolean performDexOptTraced(String packageName, String instructionSet,
7237                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7238        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7239        try {
7240            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7241                    targetCompilerFilter, force);
7242        } finally {
7243            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7244        }
7245    }
7246
7247    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7248    // if the package can now be considered up to date for the given filter.
7249    private boolean performDexOptInternal(String packageName, String instructionSet,
7250                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7251        PackageParser.Package p;
7252        final String targetInstructionSet;
7253        synchronized (mPackages) {
7254            p = mPackages.get(packageName);
7255            if (p == null) {
7256                return false;
7257            }
7258            mPackageUsage.write(false);
7259
7260            targetInstructionSet = instructionSet != null ? instructionSet :
7261                    getPrimaryInstructionSet(p.applicationInfo);
7262        }
7263        long callingId = Binder.clearCallingIdentity();
7264        try {
7265            synchronized (mInstallLock) {
7266                final String[] instructionSets = new String[] { targetInstructionSet };
7267                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7268                        checkProfiles, targetCompilerFilter, force);
7269                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7270            }
7271        } finally {
7272            Binder.restoreCallingIdentity(callingId);
7273        }
7274    }
7275
7276    public ArraySet<String> getOptimizablePackages() {
7277        ArraySet<String> pkgs = new ArraySet<String>();
7278        synchronized (mPackages) {
7279            for (PackageParser.Package p : mPackages.values()) {
7280                if (PackageDexOptimizer.canOptimizePackage(p)) {
7281                    pkgs.add(p.packageName);
7282                }
7283            }
7284        }
7285        return pkgs;
7286    }
7287
7288    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7289            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7290            boolean force) {
7291        // Select the dex optimizer based on the force parameter.
7292        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7293        //       allocate an object here.
7294        PackageDexOptimizer pdo = force
7295                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7296                : mPackageDexOptimizer;
7297
7298        // Optimize all dependencies first. Note: we ignore the return value and march on
7299        // on errors.
7300        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7301        if (!deps.isEmpty()) {
7302            for (PackageParser.Package depPackage : deps) {
7303                // TODO: Analyze and investigate if we (should) profile libraries.
7304                // Currently this will do a full compilation of the library by default.
7305                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7306                        false /* checkProfiles */,
7307                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7308            }
7309        }
7310
7311        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7312                targetCompilerFilter);
7313    }
7314
7315    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7316        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7317            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7318            Set<String> collectedNames = new HashSet<>();
7319            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7320
7321            retValue.remove(p);
7322
7323            return retValue;
7324        } else {
7325            return Collections.emptyList();
7326        }
7327    }
7328
7329    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7330            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7331        if (!collectedNames.contains(p.packageName)) {
7332            collectedNames.add(p.packageName);
7333            collected.add(p);
7334
7335            if (p.usesLibraries != null) {
7336                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7337            }
7338            if (p.usesOptionalLibraries != null) {
7339                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7340                        collectedNames);
7341            }
7342        }
7343    }
7344
7345    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7346            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7347        for (String libName : libs) {
7348            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7349            if (libPkg != null) {
7350                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7351            }
7352        }
7353    }
7354
7355    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7356        synchronized (mPackages) {
7357            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7358            if (lib != null && lib.apk != null) {
7359                return mPackages.get(lib.apk);
7360            }
7361        }
7362        return null;
7363    }
7364
7365    public void shutdown() {
7366        mPackageUsage.write(true);
7367    }
7368
7369    @Override
7370    public void forceDexOpt(String packageName) {
7371        enforceSystemOrRoot("forceDexOpt");
7372
7373        PackageParser.Package pkg;
7374        synchronized (mPackages) {
7375            pkg = mPackages.get(packageName);
7376            if (pkg == null) {
7377                throw new IllegalArgumentException("Unknown package: " + packageName);
7378            }
7379        }
7380
7381        synchronized (mInstallLock) {
7382            final String[] instructionSets = new String[] {
7383                    getPrimaryInstructionSet(pkg.applicationInfo) };
7384
7385            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7386
7387            // Whoever is calling forceDexOpt wants a fully compiled package.
7388            // Don't use profiles since that may cause compilation to be skipped.
7389            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7390                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7391                    true /* force */);
7392
7393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7395                throw new IllegalStateException("Failed to dexopt: " + res);
7396            }
7397        }
7398    }
7399
7400    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7401        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7402            Slog.w(TAG, "Unable to update from " + oldPkg.name
7403                    + " to " + newPkg.packageName
7404                    + ": old package not in system partition");
7405            return false;
7406        } else if (mPackages.get(oldPkg.name) != null) {
7407            Slog.w(TAG, "Unable to update from " + oldPkg.name
7408                    + " to " + newPkg.packageName
7409                    + ": old package still exists");
7410            return false;
7411        }
7412        return true;
7413    }
7414
7415    void removeCodePathLI(File codePath) {
7416        if (codePath.isDirectory()) {
7417            try {
7418                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7419            } catch (InstallerException e) {
7420                Slog.w(TAG, "Failed to remove code path", e);
7421            }
7422        } else {
7423            codePath.delete();
7424        }
7425    }
7426
7427    private int[] resolveUserIds(int userId) {
7428        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7429    }
7430
7431    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7432        if (pkg == null) {
7433            Slog.wtf(TAG, "Package was null!", new Throwable());
7434            return;
7435        }
7436        clearAppDataLeafLIF(pkg, userId, flags);
7437        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7438        for (int i = 0; i < childCount; i++) {
7439            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7440        }
7441    }
7442
7443    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7444        final PackageSetting ps;
7445        synchronized (mPackages) {
7446            ps = mSettings.mPackages.get(pkg.packageName);
7447        }
7448        for (int realUserId : resolveUserIds(userId)) {
7449            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7450            try {
7451                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7452                        ceDataInode);
7453            } catch (InstallerException e) {
7454                Slog.w(TAG, String.valueOf(e));
7455            }
7456        }
7457    }
7458
7459    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7460        if (pkg == null) {
7461            Slog.wtf(TAG, "Package was null!", new Throwable());
7462            return;
7463        }
7464        destroyAppDataLeafLIF(pkg, userId, flags);
7465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7466        for (int i = 0; i < childCount; i++) {
7467            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7468        }
7469    }
7470
7471    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7472        final PackageSetting ps;
7473        synchronized (mPackages) {
7474            ps = mSettings.mPackages.get(pkg.packageName);
7475        }
7476        for (int realUserId : resolveUserIds(userId)) {
7477            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7478            try {
7479                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7480                        ceDataInode);
7481            } catch (InstallerException e) {
7482                Slog.w(TAG, String.valueOf(e));
7483            }
7484        }
7485    }
7486
7487    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7488        if (pkg == null) {
7489            Slog.wtf(TAG, "Package was null!", new Throwable());
7490            return;
7491        }
7492        destroyAppProfilesLeafLIF(pkg);
7493        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7494        for (int i = 0; i < childCount; i++) {
7495            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7496        }
7497    }
7498
7499    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7500        try {
7501            mInstaller.destroyAppProfiles(pkg.packageName);
7502        } catch (InstallerException e) {
7503            Slog.w(TAG, String.valueOf(e));
7504        }
7505    }
7506
7507    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7508        if (pkg == null) {
7509            Slog.wtf(TAG, "Package was null!", new Throwable());
7510            return;
7511        }
7512        clearAppProfilesLeafLIF(pkg);
7513        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7514        for (int i = 0; i < childCount; i++) {
7515            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7516        }
7517    }
7518
7519    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7520        try {
7521            mInstaller.clearAppProfiles(pkg.packageName);
7522        } catch (InstallerException e) {
7523            Slog.w(TAG, String.valueOf(e));
7524        }
7525    }
7526
7527    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7528            long lastUpdateTime) {
7529        // Set parent install/update time
7530        PackageSetting ps = (PackageSetting) pkg.mExtras;
7531        if (ps != null) {
7532            ps.firstInstallTime = firstInstallTime;
7533            ps.lastUpdateTime = lastUpdateTime;
7534        }
7535        // Set children install/update time
7536        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7537        for (int i = 0; i < childCount; i++) {
7538            PackageParser.Package childPkg = pkg.childPackages.get(i);
7539            ps = (PackageSetting) childPkg.mExtras;
7540            if (ps != null) {
7541                ps.firstInstallTime = firstInstallTime;
7542                ps.lastUpdateTime = lastUpdateTime;
7543            }
7544        }
7545    }
7546
7547    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7548            PackageParser.Package changingLib) {
7549        if (file.path != null) {
7550            usesLibraryFiles.add(file.path);
7551            return;
7552        }
7553        PackageParser.Package p = mPackages.get(file.apk);
7554        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7555            // If we are doing this while in the middle of updating a library apk,
7556            // then we need to make sure to use that new apk for determining the
7557            // dependencies here.  (We haven't yet finished committing the new apk
7558            // to the package manager state.)
7559            if (p == null || p.packageName.equals(changingLib.packageName)) {
7560                p = changingLib;
7561            }
7562        }
7563        if (p != null) {
7564            usesLibraryFiles.addAll(p.getAllCodePaths());
7565        }
7566    }
7567
7568    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7569            PackageParser.Package changingLib) throws PackageManagerException {
7570        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7571            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7572            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7573            for (int i=0; i<N; i++) {
7574                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7575                if (file == null) {
7576                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7577                            "Package " + pkg.packageName + " requires unavailable shared library "
7578                            + pkg.usesLibraries.get(i) + "; failing!");
7579                }
7580                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7581            }
7582            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7583            for (int i=0; i<N; i++) {
7584                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7585                if (file == null) {
7586                    Slog.w(TAG, "Package " + pkg.packageName
7587                            + " desires unavailable shared library "
7588                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7589                } else {
7590                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7591                }
7592            }
7593            N = usesLibraryFiles.size();
7594            if (N > 0) {
7595                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7596            } else {
7597                pkg.usesLibraryFiles = null;
7598            }
7599        }
7600    }
7601
7602    private static boolean hasString(List<String> list, List<String> which) {
7603        if (list == null) {
7604            return false;
7605        }
7606        for (int i=list.size()-1; i>=0; i--) {
7607            for (int j=which.size()-1; j>=0; j--) {
7608                if (which.get(j).equals(list.get(i))) {
7609                    return true;
7610                }
7611            }
7612        }
7613        return false;
7614    }
7615
7616    private void updateAllSharedLibrariesLPw() {
7617        for (PackageParser.Package pkg : mPackages.values()) {
7618            try {
7619                updateSharedLibrariesLPw(pkg, null);
7620            } catch (PackageManagerException e) {
7621                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7622            }
7623        }
7624    }
7625
7626    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7627            PackageParser.Package changingPkg) {
7628        ArrayList<PackageParser.Package> res = null;
7629        for (PackageParser.Package pkg : mPackages.values()) {
7630            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7631                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7632                if (res == null) {
7633                    res = new ArrayList<PackageParser.Package>();
7634                }
7635                res.add(pkg);
7636                try {
7637                    updateSharedLibrariesLPw(pkg, changingPkg);
7638                } catch (PackageManagerException e) {
7639                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7640                }
7641            }
7642        }
7643        return res;
7644    }
7645
7646    /**
7647     * Derive the value of the {@code cpuAbiOverride} based on the provided
7648     * value and an optional stored value from the package settings.
7649     */
7650    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7651        String cpuAbiOverride = null;
7652
7653        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7654            cpuAbiOverride = null;
7655        } else if (abiOverride != null) {
7656            cpuAbiOverride = abiOverride;
7657        } else if (settings != null) {
7658            cpuAbiOverride = settings.cpuAbiOverrideString;
7659        }
7660
7661        return cpuAbiOverride;
7662    }
7663
7664    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7665            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7666                    throws PackageManagerException {
7667        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7668        // If the package has children and this is the first dive in the function
7669        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7670        // whether all packages (parent and children) would be successfully scanned
7671        // before the actual scan since scanning mutates internal state and we want
7672        // to atomically install the package and its children.
7673        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7674            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7675                scanFlags |= SCAN_CHECK_ONLY;
7676            }
7677        } else {
7678            scanFlags &= ~SCAN_CHECK_ONLY;
7679        }
7680
7681        final PackageParser.Package scannedPkg;
7682        try {
7683            // Scan the parent
7684            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7685            // Scan the children
7686            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7687            for (int i = 0; i < childCount; i++) {
7688                PackageParser.Package childPkg = pkg.childPackages.get(i);
7689                scanPackageLI(childPkg, policyFlags,
7690                        scanFlags, currentTime, user);
7691            }
7692        } finally {
7693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7694        }
7695
7696        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7697            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7698        }
7699
7700        return scannedPkg;
7701    }
7702
7703    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7704            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7705        boolean success = false;
7706        try {
7707            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7708                    currentTime, user);
7709            success = true;
7710            return res;
7711        } finally {
7712            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7713                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7714                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7715                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7716                destroyAppProfilesLIF(pkg);
7717            }
7718        }
7719    }
7720
7721    /**
7722     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7723     */
7724    private static boolean apkHasCode(String fileName) {
7725        StrictJarFile jarFile = null;
7726        try {
7727            jarFile = new StrictJarFile(fileName,
7728                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7729            return jarFile.findEntry("classes.dex") != null;
7730        } catch (IOException ignore) {
7731        } finally {
7732            try {
7733                jarFile.close();
7734            } catch (IOException ignore) {}
7735        }
7736        return false;
7737    }
7738
7739    /**
7740     * Enforces code policy for the package. This ensures that if an APK has
7741     * declared hasCode="true" in its manifest that the APK actually contains
7742     * code.
7743     *
7744     * @throws PackageManagerException If bytecode could not be found when it should exist
7745     */
7746    private static void enforceCodePolicy(PackageParser.Package pkg)
7747            throws PackageManagerException {
7748        final boolean shouldHaveCode =
7749                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7750        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7751            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7752                    "Package " + pkg.baseCodePath + " code is missing");
7753        }
7754
7755        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7756            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7757                final boolean splitShouldHaveCode =
7758                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7759                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7760                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7761                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7762                }
7763            }
7764        }
7765    }
7766
7767    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7768            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7769            throws PackageManagerException {
7770        final File scanFile = new File(pkg.codePath);
7771        if (pkg.applicationInfo.getCodePath() == null ||
7772                pkg.applicationInfo.getResourcePath() == null) {
7773            // Bail out. The resource and code paths haven't been set.
7774            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7775                    "Code and resource paths haven't been set correctly");
7776        }
7777
7778        // Apply policy
7779        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7780            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7781            if (pkg.applicationInfo.isDirectBootAware()) {
7782                // we're direct boot aware; set for all components
7783                for (PackageParser.Service s : pkg.services) {
7784                    s.info.encryptionAware = s.info.directBootAware = true;
7785                }
7786                for (PackageParser.Provider p : pkg.providers) {
7787                    p.info.encryptionAware = p.info.directBootAware = true;
7788                }
7789                for (PackageParser.Activity a : pkg.activities) {
7790                    a.info.encryptionAware = a.info.directBootAware = true;
7791                }
7792                for (PackageParser.Activity r : pkg.receivers) {
7793                    r.info.encryptionAware = r.info.directBootAware = true;
7794                }
7795            }
7796        } else {
7797            // Only allow system apps to be flagged as core apps.
7798            pkg.coreApp = false;
7799            // clear flags not applicable to regular apps
7800            pkg.applicationInfo.privateFlags &=
7801                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7802            pkg.applicationInfo.privateFlags &=
7803                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7804        }
7805        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7806
7807        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7808            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7809        }
7810
7811        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7812            enforceCodePolicy(pkg);
7813        }
7814
7815        if (mCustomResolverComponentName != null &&
7816                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7817            setUpCustomResolverActivity(pkg);
7818        }
7819
7820        if (pkg.packageName.equals("android")) {
7821            synchronized (mPackages) {
7822                if (mAndroidApplication != null) {
7823                    Slog.w(TAG, "*************************************************");
7824                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7825                    Slog.w(TAG, " file=" + scanFile);
7826                    Slog.w(TAG, "*************************************************");
7827                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7828                            "Core android package being redefined.  Skipping.");
7829                }
7830
7831                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7832                    // Set up information for our fall-back user intent resolution activity.
7833                    mPlatformPackage = pkg;
7834                    pkg.mVersionCode = mSdkVersion;
7835                    mAndroidApplication = pkg.applicationInfo;
7836
7837                    if (!mResolverReplaced) {
7838                        mResolveActivity.applicationInfo = mAndroidApplication;
7839                        mResolveActivity.name = ResolverActivity.class.getName();
7840                        mResolveActivity.packageName = mAndroidApplication.packageName;
7841                        mResolveActivity.processName = "system:ui";
7842                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7843                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7844                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7845                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7846                        mResolveActivity.exported = true;
7847                        mResolveActivity.enabled = true;
7848                        mResolveInfo.activityInfo = mResolveActivity;
7849                        mResolveInfo.priority = 0;
7850                        mResolveInfo.preferredOrder = 0;
7851                        mResolveInfo.match = 0;
7852                        mResolveComponentName = new ComponentName(
7853                                mAndroidApplication.packageName, mResolveActivity.name);
7854                    }
7855                }
7856            }
7857        }
7858
7859        if (DEBUG_PACKAGE_SCANNING) {
7860            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7861                Log.d(TAG, "Scanning package " + pkg.packageName);
7862        }
7863
7864        synchronized (mPackages) {
7865            if (mPackages.containsKey(pkg.packageName)
7866                    || mSharedLibraries.containsKey(pkg.packageName)) {
7867                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7868                        "Application package " + pkg.packageName
7869                                + " already installed.  Skipping duplicate.");
7870            }
7871
7872            // If we're only installing presumed-existing packages, require that the
7873            // scanned APK is both already known and at the path previously established
7874            // for it.  Previously unknown packages we pick up normally, but if we have an
7875            // a priori expectation about this package's install presence, enforce it.
7876            // With a singular exception for new system packages. When an OTA contains
7877            // a new system package, we allow the codepath to change from a system location
7878            // to the user-installed location. If we don't allow this change, any newer,
7879            // user-installed version of the application will be ignored.
7880            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7881                if (mExpectingBetter.containsKey(pkg.packageName)) {
7882                    logCriticalInfo(Log.WARN,
7883                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7884                } else {
7885                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7886                    if (known != null) {
7887                        if (DEBUG_PACKAGE_SCANNING) {
7888                            Log.d(TAG, "Examining " + pkg.codePath
7889                                    + " and requiring known paths " + known.codePathString
7890                                    + " & " + known.resourcePathString);
7891                        }
7892                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7893                                || !pkg.applicationInfo.getResourcePath().equals(
7894                                known.resourcePathString)) {
7895                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7896                                    "Application package " + pkg.packageName
7897                                            + " found at " + pkg.applicationInfo.getCodePath()
7898                                            + " but expected at " + known.codePathString
7899                                            + "; ignoring.");
7900                        }
7901                    }
7902                }
7903            }
7904        }
7905
7906        // Initialize package source and resource directories
7907        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7908        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7909
7910        SharedUserSetting suid = null;
7911        PackageSetting pkgSetting = null;
7912
7913        if (!isSystemApp(pkg)) {
7914            // Only system apps can use these features.
7915            pkg.mOriginalPackages = null;
7916            pkg.mRealPackage = null;
7917            pkg.mAdoptPermissions = null;
7918        }
7919
7920        // Getting the package setting may have a side-effect, so if we
7921        // are only checking if scan would succeed, stash a copy of the
7922        // old setting to restore at the end.
7923        PackageSetting nonMutatedPs = null;
7924
7925        // writer
7926        synchronized (mPackages) {
7927            if (pkg.mSharedUserId != null) {
7928                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7929                if (suid == null) {
7930                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7931                            "Creating application package " + pkg.packageName
7932                            + " for shared user failed");
7933                }
7934                if (DEBUG_PACKAGE_SCANNING) {
7935                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7936                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7937                                + "): packages=" + suid.packages);
7938                }
7939            }
7940
7941            // Check if we are renaming from an original package name.
7942            PackageSetting origPackage = null;
7943            String realName = null;
7944            if (pkg.mOriginalPackages != null) {
7945                // This package may need to be renamed to a previously
7946                // installed name.  Let's check on that...
7947                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7948                if (pkg.mOriginalPackages.contains(renamed)) {
7949                    // This package had originally been installed as the
7950                    // original name, and we have already taken care of
7951                    // transitioning to the new one.  Just update the new
7952                    // one to continue using the old name.
7953                    realName = pkg.mRealPackage;
7954                    if (!pkg.packageName.equals(renamed)) {
7955                        // Callers into this function may have already taken
7956                        // care of renaming the package; only do it here if
7957                        // it is not already done.
7958                        pkg.setPackageName(renamed);
7959                    }
7960
7961                } else {
7962                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7963                        if ((origPackage = mSettings.peekPackageLPr(
7964                                pkg.mOriginalPackages.get(i))) != null) {
7965                            // We do have the package already installed under its
7966                            // original name...  should we use it?
7967                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7968                                // New package is not compatible with original.
7969                                origPackage = null;
7970                                continue;
7971                            } else if (origPackage.sharedUser != null) {
7972                                // Make sure uid is compatible between packages.
7973                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7974                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7975                                            + " to " + pkg.packageName + ": old uid "
7976                                            + origPackage.sharedUser.name
7977                                            + " differs from " + pkg.mSharedUserId);
7978                                    origPackage = null;
7979                                    continue;
7980                                }
7981                                // TODO: Add case when shared user id is added [b/28144775]
7982                            } else {
7983                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7984                                        + pkg.packageName + " to old name " + origPackage.name);
7985                            }
7986                            break;
7987                        }
7988                    }
7989                }
7990            }
7991
7992            if (mTransferedPackages.contains(pkg.packageName)) {
7993                Slog.w(TAG, "Package " + pkg.packageName
7994                        + " was transferred to another, but its .apk remains");
7995            }
7996
7997            // See comments in nonMutatedPs declaration
7998            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7999                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8000                if (foundPs != null) {
8001                    nonMutatedPs = new PackageSetting(foundPs);
8002                }
8003            }
8004
8005            // Just create the setting, don't add it yet. For already existing packages
8006            // the PkgSetting exists already and doesn't have to be created.
8007            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8008                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8009                    pkg.applicationInfo.primaryCpuAbi,
8010                    pkg.applicationInfo.secondaryCpuAbi,
8011                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8012                    user, false);
8013            if (pkgSetting == null) {
8014                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8015                        "Creating application package " + pkg.packageName + " failed");
8016            }
8017
8018            if (pkgSetting.origPackage != null) {
8019                // If we are first transitioning from an original package,
8020                // fix up the new package's name now.  We need to do this after
8021                // looking up the package under its new name, so getPackageLP
8022                // can take care of fiddling things correctly.
8023                pkg.setPackageName(origPackage.name);
8024
8025                // File a report about this.
8026                String msg = "New package " + pkgSetting.realName
8027                        + " renamed to replace old package " + pkgSetting.name;
8028                reportSettingsProblem(Log.WARN, msg);
8029
8030                // Make a note of it.
8031                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8032                    mTransferedPackages.add(origPackage.name);
8033                }
8034
8035                // No longer need to retain this.
8036                pkgSetting.origPackage = null;
8037            }
8038
8039            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8040                // Make a note of it.
8041                mTransferedPackages.add(pkg.packageName);
8042            }
8043
8044            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8045                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8046            }
8047
8048            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8049                // Check all shared libraries and map to their actual file path.
8050                // We only do this here for apps not on a system dir, because those
8051                // are the only ones that can fail an install due to this.  We
8052                // will take care of the system apps by updating all of their
8053                // library paths after the scan is done.
8054                updateSharedLibrariesLPw(pkg, null);
8055            }
8056
8057            if (mFoundPolicyFile) {
8058                SELinuxMMAC.assignSeinfoValue(pkg);
8059            }
8060
8061            pkg.applicationInfo.uid = pkgSetting.appId;
8062            pkg.mExtras = pkgSetting;
8063            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8064                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8065                    // We just determined the app is signed correctly, so bring
8066                    // over the latest parsed certs.
8067                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8068                } else {
8069                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8070                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8071                                "Package " + pkg.packageName + " upgrade keys do not match the "
8072                                + "previously installed version");
8073                    } else {
8074                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8075                        String msg = "System package " + pkg.packageName
8076                            + " signature changed; retaining data.";
8077                        reportSettingsProblem(Log.WARN, msg);
8078                    }
8079                }
8080            } else {
8081                try {
8082                    verifySignaturesLP(pkgSetting, pkg);
8083                    // We just determined the app is signed correctly, so bring
8084                    // over the latest parsed certs.
8085                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8086                } catch (PackageManagerException e) {
8087                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8088                        throw e;
8089                    }
8090                    // The signature has changed, but this package is in the system
8091                    // image...  let's recover!
8092                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8093                    // However...  if this package is part of a shared user, but it
8094                    // doesn't match the signature of the shared user, let's fail.
8095                    // What this means is that you can't change the signatures
8096                    // associated with an overall shared user, which doesn't seem all
8097                    // that unreasonable.
8098                    if (pkgSetting.sharedUser != null) {
8099                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8100                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8101                            throw new PackageManagerException(
8102                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8103                                            "Signature mismatch for shared user: "
8104                                            + pkgSetting.sharedUser);
8105                        }
8106                    }
8107                    // File a report about this.
8108                    String msg = "System package " + pkg.packageName
8109                        + " signature changed; retaining data.";
8110                    reportSettingsProblem(Log.WARN, msg);
8111                }
8112            }
8113            // Verify that this new package doesn't have any content providers
8114            // that conflict with existing packages.  Only do this if the
8115            // package isn't already installed, since we don't want to break
8116            // things that are installed.
8117            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8118                final int N = pkg.providers.size();
8119                int i;
8120                for (i=0; i<N; i++) {
8121                    PackageParser.Provider p = pkg.providers.get(i);
8122                    if (p.info.authority != null) {
8123                        String names[] = p.info.authority.split(";");
8124                        for (int j = 0; j < names.length; j++) {
8125                            if (mProvidersByAuthority.containsKey(names[j])) {
8126                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8127                                final String otherPackageName =
8128                                        ((other != null && other.getComponentName() != null) ?
8129                                                other.getComponentName().getPackageName() : "?");
8130                                throw new PackageManagerException(
8131                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8132                                                "Can't install because provider name " + names[j]
8133                                                + " (in package " + pkg.applicationInfo.packageName
8134                                                + ") is already used by " + otherPackageName);
8135                            }
8136                        }
8137                    }
8138                }
8139            }
8140
8141            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8142                // This package wants to adopt ownership of permissions from
8143                // another package.
8144                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8145                    final String origName = pkg.mAdoptPermissions.get(i);
8146                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8147                    if (orig != null) {
8148                        if (verifyPackageUpdateLPr(orig, pkg)) {
8149                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8150                                    + pkg.packageName);
8151                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8152                        }
8153                    }
8154                }
8155            }
8156        }
8157
8158        final String pkgName = pkg.packageName;
8159
8160        final long scanFileTime = scanFile.lastModified();
8161        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8162        pkg.applicationInfo.processName = fixProcessName(
8163                pkg.applicationInfo.packageName,
8164                pkg.applicationInfo.processName,
8165                pkg.applicationInfo.uid);
8166
8167        if (pkg != mPlatformPackage) {
8168            // Get all of our default paths setup
8169            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8170        }
8171
8172        final String path = scanFile.getPath();
8173        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8174
8175        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8176            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8177
8178            // Some system apps still use directory structure for native libraries
8179            // in which case we might end up not detecting abi solely based on apk
8180            // structure. Try to detect abi based on directory structure.
8181            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8182                    pkg.applicationInfo.primaryCpuAbi == null) {
8183                setBundledAppAbisAndRoots(pkg, pkgSetting);
8184                setNativeLibraryPaths(pkg);
8185            }
8186
8187        } else {
8188            if ((scanFlags & SCAN_MOVE) != 0) {
8189                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8190                // but we already have this packages package info in the PackageSetting. We just
8191                // use that and derive the native library path based on the new codepath.
8192                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8193                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8194            }
8195
8196            // Set native library paths again. For moves, the path will be updated based on the
8197            // ABIs we've determined above. For non-moves, the path will be updated based on the
8198            // ABIs we determined during compilation, but the path will depend on the final
8199            // package path (after the rename away from the stage path).
8200            setNativeLibraryPaths(pkg);
8201        }
8202
8203        // This is a special case for the "system" package, where the ABI is
8204        // dictated by the zygote configuration (and init.rc). We should keep track
8205        // of this ABI so that we can deal with "normal" applications that run under
8206        // the same UID correctly.
8207        if (mPlatformPackage == pkg) {
8208            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8209                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8210        }
8211
8212        // If there's a mismatch between the abi-override in the package setting
8213        // and the abiOverride specified for the install. Warn about this because we
8214        // would've already compiled the app without taking the package setting into
8215        // account.
8216        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8217            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8218                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8219                        " for package " + pkg.packageName);
8220            }
8221        }
8222
8223        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8224        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8225        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8226
8227        // Copy the derived override back to the parsed package, so that we can
8228        // update the package settings accordingly.
8229        pkg.cpuAbiOverride = cpuAbiOverride;
8230
8231        if (DEBUG_ABI_SELECTION) {
8232            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8233                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8234                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8235        }
8236
8237        // Push the derived path down into PackageSettings so we know what to
8238        // clean up at uninstall time.
8239        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8240
8241        if (DEBUG_ABI_SELECTION) {
8242            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8243                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8244                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8245        }
8246
8247        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8248            // We don't do this here during boot because we can do it all
8249            // at once after scanning all existing packages.
8250            //
8251            // We also do this *before* we perform dexopt on this package, so that
8252            // we can avoid redundant dexopts, and also to make sure we've got the
8253            // code and package path correct.
8254            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8255                    pkg, true /* boot complete */);
8256        }
8257
8258        if (mFactoryTest && pkg.requestedPermissions.contains(
8259                android.Manifest.permission.FACTORY_TEST)) {
8260            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8261        }
8262
8263        ArrayList<PackageParser.Package> clientLibPkgs = null;
8264
8265        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8266            if (nonMutatedPs != null) {
8267                synchronized (mPackages) {
8268                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8269                }
8270            }
8271            return pkg;
8272        }
8273
8274        // Only privileged apps and updated privileged apps can add child packages.
8275        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8276            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8277                throw new PackageManagerException("Only privileged apps and updated "
8278                        + "privileged apps can add child packages. Ignoring package "
8279                        + pkg.packageName);
8280            }
8281            final int childCount = pkg.childPackages.size();
8282            for (int i = 0; i < childCount; i++) {
8283                PackageParser.Package childPkg = pkg.childPackages.get(i);
8284                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8285                        childPkg.packageName)) {
8286                    throw new PackageManagerException("Cannot override a child package of "
8287                            + "another disabled system app. Ignoring package " + pkg.packageName);
8288                }
8289            }
8290        }
8291
8292        // writer
8293        synchronized (mPackages) {
8294            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8295                // Only system apps can add new shared libraries.
8296                if (pkg.libraryNames != null) {
8297                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8298                        String name = pkg.libraryNames.get(i);
8299                        boolean allowed = false;
8300                        if (pkg.isUpdatedSystemApp()) {
8301                            // New library entries can only be added through the
8302                            // system image.  This is important to get rid of a lot
8303                            // of nasty edge cases: for example if we allowed a non-
8304                            // system update of the app to add a library, then uninstalling
8305                            // the update would make the library go away, and assumptions
8306                            // we made such as through app install filtering would now
8307                            // have allowed apps on the device which aren't compatible
8308                            // with it.  Better to just have the restriction here, be
8309                            // conservative, and create many fewer cases that can negatively
8310                            // impact the user experience.
8311                            final PackageSetting sysPs = mSettings
8312                                    .getDisabledSystemPkgLPr(pkg.packageName);
8313                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8314                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8315                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8316                                        allowed = true;
8317                                        break;
8318                                    }
8319                                }
8320                            }
8321                        } else {
8322                            allowed = true;
8323                        }
8324                        if (allowed) {
8325                            if (!mSharedLibraries.containsKey(name)) {
8326                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8327                            } else if (!name.equals(pkg.packageName)) {
8328                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8329                                        + name + " already exists; skipping");
8330                            }
8331                        } else {
8332                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8333                                    + name + " that is not declared on system image; skipping");
8334                        }
8335                    }
8336                    if ((scanFlags & SCAN_BOOTING) == 0) {
8337                        // If we are not booting, we need to update any applications
8338                        // that are clients of our shared library.  If we are booting,
8339                        // this will all be done once the scan is complete.
8340                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8341                    }
8342                }
8343            }
8344        }
8345
8346        if ((scanFlags & SCAN_BOOTING) != 0) {
8347            // No apps can run during boot scan, so they don't need to be frozen
8348        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8349            // Caller asked to not kill app, so it's probably not frozen
8350        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8351            // Caller asked us to ignore frozen check for some reason; they
8352            // probably didn't know the package name
8353        } else {
8354            // We're doing major surgery on this package, so it better be frozen
8355            // right now to keep it from launching
8356            checkPackageFrozen(pkgName);
8357        }
8358
8359        // Also need to kill any apps that are dependent on the library.
8360        if (clientLibPkgs != null) {
8361            for (int i=0; i<clientLibPkgs.size(); i++) {
8362                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8363                killApplication(clientPkg.applicationInfo.packageName,
8364                        clientPkg.applicationInfo.uid, "update lib");
8365            }
8366        }
8367
8368        // Make sure we're not adding any bogus keyset info
8369        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8370        ksms.assertScannedPackageValid(pkg);
8371
8372        // writer
8373        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8374
8375        boolean createIdmapFailed = false;
8376        synchronized (mPackages) {
8377            // We don't expect installation to fail beyond this point
8378
8379            // Add the new setting to mSettings
8380            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8381            // Add the new setting to mPackages
8382            mPackages.put(pkg.applicationInfo.packageName, pkg);
8383            // Make sure we don't accidentally delete its data.
8384            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8385            while (iter.hasNext()) {
8386                PackageCleanItem item = iter.next();
8387                if (pkgName.equals(item.packageName)) {
8388                    iter.remove();
8389                }
8390            }
8391
8392            // Take care of first install / last update times.
8393            if (currentTime != 0) {
8394                if (pkgSetting.firstInstallTime == 0) {
8395                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8396                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8397                    pkgSetting.lastUpdateTime = currentTime;
8398                }
8399            } else if (pkgSetting.firstInstallTime == 0) {
8400                // We need *something*.  Take time time stamp of the file.
8401                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8402            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8403                if (scanFileTime != pkgSetting.timeStamp) {
8404                    // A package on the system image has changed; consider this
8405                    // to be an update.
8406                    pkgSetting.lastUpdateTime = scanFileTime;
8407                }
8408            }
8409
8410            // Add the package's KeySets to the global KeySetManagerService
8411            ksms.addScannedPackageLPw(pkg);
8412
8413            int N = pkg.providers.size();
8414            StringBuilder r = null;
8415            int i;
8416            for (i=0; i<N; i++) {
8417                PackageParser.Provider p = pkg.providers.get(i);
8418                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8419                        p.info.processName, pkg.applicationInfo.uid);
8420                mProviders.addProvider(p);
8421                p.syncable = p.info.isSyncable;
8422                if (p.info.authority != null) {
8423                    String names[] = p.info.authority.split(";");
8424                    p.info.authority = null;
8425                    for (int j = 0; j < names.length; j++) {
8426                        if (j == 1 && p.syncable) {
8427                            // We only want the first authority for a provider to possibly be
8428                            // syncable, so if we already added this provider using a different
8429                            // authority clear the syncable flag. We copy the provider before
8430                            // changing it because the mProviders object contains a reference
8431                            // to a provider that we don't want to change.
8432                            // Only do this for the second authority since the resulting provider
8433                            // object can be the same for all future authorities for this provider.
8434                            p = new PackageParser.Provider(p);
8435                            p.syncable = false;
8436                        }
8437                        if (!mProvidersByAuthority.containsKey(names[j])) {
8438                            mProvidersByAuthority.put(names[j], p);
8439                            if (p.info.authority == null) {
8440                                p.info.authority = names[j];
8441                            } else {
8442                                p.info.authority = p.info.authority + ";" + names[j];
8443                            }
8444                            if (DEBUG_PACKAGE_SCANNING) {
8445                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8446                                    Log.d(TAG, "Registered content provider: " + names[j]
8447                                            + ", className = " + p.info.name + ", isSyncable = "
8448                                            + p.info.isSyncable);
8449                            }
8450                        } else {
8451                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8452                            Slog.w(TAG, "Skipping provider name " + names[j] +
8453                                    " (in package " + pkg.applicationInfo.packageName +
8454                                    "): name already used by "
8455                                    + ((other != null && other.getComponentName() != null)
8456                                            ? other.getComponentName().getPackageName() : "?"));
8457                        }
8458                    }
8459                }
8460                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8461                    if (r == null) {
8462                        r = new StringBuilder(256);
8463                    } else {
8464                        r.append(' ');
8465                    }
8466                    r.append(p.info.name);
8467                }
8468            }
8469            if (r != null) {
8470                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8471            }
8472
8473            N = pkg.services.size();
8474            r = null;
8475            for (i=0; i<N; i++) {
8476                PackageParser.Service s = pkg.services.get(i);
8477                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8478                        s.info.processName, pkg.applicationInfo.uid);
8479                mServices.addService(s);
8480                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8481                    if (r == null) {
8482                        r = new StringBuilder(256);
8483                    } else {
8484                        r.append(' ');
8485                    }
8486                    r.append(s.info.name);
8487                }
8488            }
8489            if (r != null) {
8490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8491            }
8492
8493            N = pkg.receivers.size();
8494            r = null;
8495            for (i=0; i<N; i++) {
8496                PackageParser.Activity a = pkg.receivers.get(i);
8497                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8498                        a.info.processName, pkg.applicationInfo.uid);
8499                mReceivers.addActivity(a, "receiver");
8500                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8501                    if (r == null) {
8502                        r = new StringBuilder(256);
8503                    } else {
8504                        r.append(' ');
8505                    }
8506                    r.append(a.info.name);
8507                }
8508            }
8509            if (r != null) {
8510                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8511            }
8512
8513            N = pkg.activities.size();
8514            r = null;
8515            for (i=0; i<N; i++) {
8516                PackageParser.Activity a = pkg.activities.get(i);
8517                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8518                        a.info.processName, pkg.applicationInfo.uid);
8519                mActivities.addActivity(a, "activity");
8520                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8521                    if (r == null) {
8522                        r = new StringBuilder(256);
8523                    } else {
8524                        r.append(' ');
8525                    }
8526                    r.append(a.info.name);
8527                }
8528            }
8529            if (r != null) {
8530                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8531            }
8532
8533            N = pkg.permissionGroups.size();
8534            r = null;
8535            for (i=0; i<N; i++) {
8536                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8537                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8538                if (cur == null) {
8539                    mPermissionGroups.put(pg.info.name, pg);
8540                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8541                        if (r == null) {
8542                            r = new StringBuilder(256);
8543                        } else {
8544                            r.append(' ');
8545                        }
8546                        r.append(pg.info.name);
8547                    }
8548                } else {
8549                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8550                            + pg.info.packageName + " ignored: original from "
8551                            + cur.info.packageName);
8552                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8553                        if (r == null) {
8554                            r = new StringBuilder(256);
8555                        } else {
8556                            r.append(' ');
8557                        }
8558                        r.append("DUP:");
8559                        r.append(pg.info.name);
8560                    }
8561                }
8562            }
8563            if (r != null) {
8564                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8565            }
8566
8567            N = pkg.permissions.size();
8568            r = null;
8569            for (i=0; i<N; i++) {
8570                PackageParser.Permission p = pkg.permissions.get(i);
8571
8572                // Assume by default that we did not install this permission into the system.
8573                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8574
8575                // Now that permission groups have a special meaning, we ignore permission
8576                // groups for legacy apps to prevent unexpected behavior. In particular,
8577                // permissions for one app being granted to someone just becase they happen
8578                // to be in a group defined by another app (before this had no implications).
8579                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8580                    p.group = mPermissionGroups.get(p.info.group);
8581                    // Warn for a permission in an unknown group.
8582                    if (p.info.group != null && p.group == null) {
8583                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8584                                + p.info.packageName + " in an unknown group " + p.info.group);
8585                    }
8586                }
8587
8588                ArrayMap<String, BasePermission> permissionMap =
8589                        p.tree ? mSettings.mPermissionTrees
8590                                : mSettings.mPermissions;
8591                BasePermission bp = permissionMap.get(p.info.name);
8592
8593                // Allow system apps to redefine non-system permissions
8594                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8595                    final boolean currentOwnerIsSystem = (bp.perm != null
8596                            && isSystemApp(bp.perm.owner));
8597                    if (isSystemApp(p.owner)) {
8598                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8599                            // It's a built-in permission and no owner, take ownership now
8600                            bp.packageSetting = pkgSetting;
8601                            bp.perm = p;
8602                            bp.uid = pkg.applicationInfo.uid;
8603                            bp.sourcePackage = p.info.packageName;
8604                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8605                        } else if (!currentOwnerIsSystem) {
8606                            String msg = "New decl " + p.owner + " of permission  "
8607                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8608                            reportSettingsProblem(Log.WARN, msg);
8609                            bp = null;
8610                        }
8611                    }
8612                }
8613
8614                if (bp == null) {
8615                    bp = new BasePermission(p.info.name, p.info.packageName,
8616                            BasePermission.TYPE_NORMAL);
8617                    permissionMap.put(p.info.name, bp);
8618                }
8619
8620                if (bp.perm == null) {
8621                    if (bp.sourcePackage == null
8622                            || bp.sourcePackage.equals(p.info.packageName)) {
8623                        BasePermission tree = findPermissionTreeLP(p.info.name);
8624                        if (tree == null
8625                                || tree.sourcePackage.equals(p.info.packageName)) {
8626                            bp.packageSetting = pkgSetting;
8627                            bp.perm = p;
8628                            bp.uid = pkg.applicationInfo.uid;
8629                            bp.sourcePackage = p.info.packageName;
8630                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8631                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8632                                if (r == null) {
8633                                    r = new StringBuilder(256);
8634                                } else {
8635                                    r.append(' ');
8636                                }
8637                                r.append(p.info.name);
8638                            }
8639                        } else {
8640                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8641                                    + p.info.packageName + " ignored: base tree "
8642                                    + tree.name + " is from package "
8643                                    + tree.sourcePackage);
8644                        }
8645                    } else {
8646                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8647                                + p.info.packageName + " ignored: original from "
8648                                + bp.sourcePackage);
8649                    }
8650                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8651                    if (r == null) {
8652                        r = new StringBuilder(256);
8653                    } else {
8654                        r.append(' ');
8655                    }
8656                    r.append("DUP:");
8657                    r.append(p.info.name);
8658                }
8659                if (bp.perm == p) {
8660                    bp.protectionLevel = p.info.protectionLevel;
8661                }
8662            }
8663
8664            if (r != null) {
8665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8666            }
8667
8668            N = pkg.instrumentation.size();
8669            r = null;
8670            for (i=0; i<N; i++) {
8671                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8672                a.info.packageName = pkg.applicationInfo.packageName;
8673                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8674                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8675                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8676                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8677                a.info.dataDir = pkg.applicationInfo.dataDir;
8678                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8679                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8680
8681                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8682                // need other information about the application, like the ABI and what not ?
8683                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8684                mInstrumentation.put(a.getComponentName(), a);
8685                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8686                    if (r == null) {
8687                        r = new StringBuilder(256);
8688                    } else {
8689                        r.append(' ');
8690                    }
8691                    r.append(a.info.name);
8692                }
8693            }
8694            if (r != null) {
8695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8696            }
8697
8698            if (pkg.protectedBroadcasts != null) {
8699                N = pkg.protectedBroadcasts.size();
8700                for (i=0; i<N; i++) {
8701                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8702                }
8703            }
8704
8705            pkgSetting.setTimeStamp(scanFileTime);
8706
8707            // Create idmap files for pairs of (packages, overlay packages).
8708            // Note: "android", ie framework-res.apk, is handled by native layers.
8709            if (pkg.mOverlayTarget != null) {
8710                // This is an overlay package.
8711                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8712                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8713                        mOverlays.put(pkg.mOverlayTarget,
8714                                new ArrayMap<String, PackageParser.Package>());
8715                    }
8716                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8717                    map.put(pkg.packageName, pkg);
8718                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8719                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8720                        createIdmapFailed = true;
8721                    }
8722                }
8723            } else if (mOverlays.containsKey(pkg.packageName) &&
8724                    !pkg.packageName.equals("android")) {
8725                // This is a regular package, with one or more known overlay packages.
8726                createIdmapsForPackageLI(pkg);
8727            }
8728        }
8729
8730        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8731
8732        if (createIdmapFailed) {
8733            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8734                    "scanPackageLI failed to createIdmap");
8735        }
8736        return pkg;
8737    }
8738
8739    /**
8740     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8741     * is derived purely on the basis of the contents of {@code scanFile} and
8742     * {@code cpuAbiOverride}.
8743     *
8744     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8745     */
8746    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8747                                 String cpuAbiOverride, boolean extractLibs)
8748            throws PackageManagerException {
8749        // TODO: We can probably be smarter about this stuff. For installed apps,
8750        // we can calculate this information at install time once and for all. For
8751        // system apps, we can probably assume that this information doesn't change
8752        // after the first boot scan. As things stand, we do lots of unnecessary work.
8753
8754        // Give ourselves some initial paths; we'll come back for another
8755        // pass once we've determined ABI below.
8756        setNativeLibraryPaths(pkg);
8757
8758        // We would never need to extract libs for forward-locked and external packages,
8759        // since the container service will do it for us. We shouldn't attempt to
8760        // extract libs from system app when it was not updated.
8761        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8762                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8763            extractLibs = false;
8764        }
8765
8766        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8767        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8768
8769        NativeLibraryHelper.Handle handle = null;
8770        try {
8771            handle = NativeLibraryHelper.Handle.create(pkg);
8772            // TODO(multiArch): This can be null for apps that didn't go through the
8773            // usual installation process. We can calculate it again, like we
8774            // do during install time.
8775            //
8776            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8777            // unnecessary.
8778            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8779
8780            // Null out the abis so that they can be recalculated.
8781            pkg.applicationInfo.primaryCpuAbi = null;
8782            pkg.applicationInfo.secondaryCpuAbi = null;
8783            if (isMultiArch(pkg.applicationInfo)) {
8784                // Warn if we've set an abiOverride for multi-lib packages..
8785                // By definition, we need to copy both 32 and 64 bit libraries for
8786                // such packages.
8787                if (pkg.cpuAbiOverride != null
8788                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8789                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8790                }
8791
8792                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8793                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8794                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8795                    if (extractLibs) {
8796                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8797                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8798                                useIsaSpecificSubdirs);
8799                    } else {
8800                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8801                    }
8802                }
8803
8804                maybeThrowExceptionForMultiArchCopy(
8805                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8806
8807                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8808                    if (extractLibs) {
8809                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8810                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8811                                useIsaSpecificSubdirs);
8812                    } else {
8813                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8814                    }
8815                }
8816
8817                maybeThrowExceptionForMultiArchCopy(
8818                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8819
8820                if (abi64 >= 0) {
8821                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8822                }
8823
8824                if (abi32 >= 0) {
8825                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8826                    if (abi64 >= 0) {
8827                        if (pkg.use32bitAbi) {
8828                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8829                            pkg.applicationInfo.primaryCpuAbi = abi;
8830                        } else {
8831                            pkg.applicationInfo.secondaryCpuAbi = abi;
8832                        }
8833                    } else {
8834                        pkg.applicationInfo.primaryCpuAbi = abi;
8835                    }
8836                }
8837
8838            } else {
8839                String[] abiList = (cpuAbiOverride != null) ?
8840                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8841
8842                // Enable gross and lame hacks for apps that are built with old
8843                // SDK tools. We must scan their APKs for renderscript bitcode and
8844                // not launch them if it's present. Don't bother checking on devices
8845                // that don't have 64 bit support.
8846                boolean needsRenderScriptOverride = false;
8847                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8848                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8849                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8850                    needsRenderScriptOverride = true;
8851                }
8852
8853                final int copyRet;
8854                if (extractLibs) {
8855                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8856                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8857                } else {
8858                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8859                }
8860
8861                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8862                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8863                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8864                }
8865
8866                if (copyRet >= 0) {
8867                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8868                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8869                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8870                } else if (needsRenderScriptOverride) {
8871                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8872                }
8873            }
8874        } catch (IOException ioe) {
8875            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8876        } finally {
8877            IoUtils.closeQuietly(handle);
8878        }
8879
8880        // Now that we've calculated the ABIs and determined if it's an internal app,
8881        // we will go ahead and populate the nativeLibraryPath.
8882        setNativeLibraryPaths(pkg);
8883    }
8884
8885    /**
8886     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8887     * i.e, so that all packages can be run inside a single process if required.
8888     *
8889     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8890     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8891     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8892     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8893     * updating a package that belongs to a shared user.
8894     *
8895     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8896     * adds unnecessary complexity.
8897     */
8898    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8899            PackageParser.Package scannedPackage, boolean bootComplete) {
8900        String requiredInstructionSet = null;
8901        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8902            requiredInstructionSet = VMRuntime.getInstructionSet(
8903                     scannedPackage.applicationInfo.primaryCpuAbi);
8904        }
8905
8906        PackageSetting requirer = null;
8907        for (PackageSetting ps : packagesForUser) {
8908            // If packagesForUser contains scannedPackage, we skip it. This will happen
8909            // when scannedPackage is an update of an existing package. Without this check,
8910            // we will never be able to change the ABI of any package belonging to a shared
8911            // user, even if it's compatible with other packages.
8912            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8913                if (ps.primaryCpuAbiString == null) {
8914                    continue;
8915                }
8916
8917                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8918                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8919                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8920                    // this but there's not much we can do.
8921                    String errorMessage = "Instruction set mismatch, "
8922                            + ((requirer == null) ? "[caller]" : requirer)
8923                            + " requires " + requiredInstructionSet + " whereas " + ps
8924                            + " requires " + instructionSet;
8925                    Slog.w(TAG, errorMessage);
8926                }
8927
8928                if (requiredInstructionSet == null) {
8929                    requiredInstructionSet = instructionSet;
8930                    requirer = ps;
8931                }
8932            }
8933        }
8934
8935        if (requiredInstructionSet != null) {
8936            String adjustedAbi;
8937            if (requirer != null) {
8938                // requirer != null implies that either scannedPackage was null or that scannedPackage
8939                // did not require an ABI, in which case we have to adjust scannedPackage to match
8940                // the ABI of the set (which is the same as requirer's ABI)
8941                adjustedAbi = requirer.primaryCpuAbiString;
8942                if (scannedPackage != null) {
8943                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8944                }
8945            } else {
8946                // requirer == null implies that we're updating all ABIs in the set to
8947                // match scannedPackage.
8948                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8949            }
8950
8951            for (PackageSetting ps : packagesForUser) {
8952                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8953                    if (ps.primaryCpuAbiString != null) {
8954                        continue;
8955                    }
8956
8957                    ps.primaryCpuAbiString = adjustedAbi;
8958                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8959                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8960                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8961                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8962                                + " (requirer="
8963                                + (requirer == null ? "null" : requirer.pkg.packageName)
8964                                + ", scannedPackage="
8965                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8966                                + ")");
8967                        try {
8968                            mInstaller.rmdex(ps.codePathString,
8969                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8970                        } catch (InstallerException ignored) {
8971                        }
8972                    }
8973                }
8974            }
8975        }
8976    }
8977
8978    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8979        synchronized (mPackages) {
8980            mResolverReplaced = true;
8981            // Set up information for custom user intent resolution activity.
8982            mResolveActivity.applicationInfo = pkg.applicationInfo;
8983            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8984            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8985            mResolveActivity.processName = pkg.applicationInfo.packageName;
8986            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8987            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8988                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8989            mResolveActivity.theme = 0;
8990            mResolveActivity.exported = true;
8991            mResolveActivity.enabled = true;
8992            mResolveInfo.activityInfo = mResolveActivity;
8993            mResolveInfo.priority = 0;
8994            mResolveInfo.preferredOrder = 0;
8995            mResolveInfo.match = 0;
8996            mResolveComponentName = mCustomResolverComponentName;
8997            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8998                    mResolveComponentName);
8999        }
9000    }
9001
9002    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9003        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9004
9005        // Set up information for ephemeral installer activity
9006        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9007        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9008        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9009        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9010        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9011        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9012                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9013        mEphemeralInstallerActivity.theme = 0;
9014        mEphemeralInstallerActivity.exported = true;
9015        mEphemeralInstallerActivity.enabled = true;
9016        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9017        mEphemeralInstallerInfo.priority = 0;
9018        mEphemeralInstallerInfo.preferredOrder = 0;
9019        mEphemeralInstallerInfo.match = 0;
9020
9021        if (DEBUG_EPHEMERAL) {
9022            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9023        }
9024    }
9025
9026    private static String calculateBundledApkRoot(final String codePathString) {
9027        final File codePath = new File(codePathString);
9028        final File codeRoot;
9029        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9030            codeRoot = Environment.getRootDirectory();
9031        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9032            codeRoot = Environment.getOemDirectory();
9033        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9034            codeRoot = Environment.getVendorDirectory();
9035        } else {
9036            // Unrecognized code path; take its top real segment as the apk root:
9037            // e.g. /something/app/blah.apk => /something
9038            try {
9039                File f = codePath.getCanonicalFile();
9040                File parent = f.getParentFile();    // non-null because codePath is a file
9041                File tmp;
9042                while ((tmp = parent.getParentFile()) != null) {
9043                    f = parent;
9044                    parent = tmp;
9045                }
9046                codeRoot = f;
9047                Slog.w(TAG, "Unrecognized code path "
9048                        + codePath + " - using " + codeRoot);
9049            } catch (IOException e) {
9050                // Can't canonicalize the code path -- shenanigans?
9051                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9052                return Environment.getRootDirectory().getPath();
9053            }
9054        }
9055        return codeRoot.getPath();
9056    }
9057
9058    /**
9059     * Derive and set the location of native libraries for the given package,
9060     * which varies depending on where and how the package was installed.
9061     */
9062    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9063        final ApplicationInfo info = pkg.applicationInfo;
9064        final String codePath = pkg.codePath;
9065        final File codeFile = new File(codePath);
9066        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9067        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9068
9069        info.nativeLibraryRootDir = null;
9070        info.nativeLibraryRootRequiresIsa = false;
9071        info.nativeLibraryDir = null;
9072        info.secondaryNativeLibraryDir = null;
9073
9074        if (isApkFile(codeFile)) {
9075            // Monolithic install
9076            if (bundledApp) {
9077                // If "/system/lib64/apkname" exists, assume that is the per-package
9078                // native library directory to use; otherwise use "/system/lib/apkname".
9079                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9080                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9081                        getPrimaryInstructionSet(info));
9082
9083                // This is a bundled system app so choose the path based on the ABI.
9084                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9085                // is just the default path.
9086                final String apkName = deriveCodePathName(codePath);
9087                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9088                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9089                        apkName).getAbsolutePath();
9090
9091                if (info.secondaryCpuAbi != null) {
9092                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9093                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9094                            secondaryLibDir, apkName).getAbsolutePath();
9095                }
9096            } else if (asecApp) {
9097                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9098                        .getAbsolutePath();
9099            } else {
9100                final String apkName = deriveCodePathName(codePath);
9101                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9102                        .getAbsolutePath();
9103            }
9104
9105            info.nativeLibraryRootRequiresIsa = false;
9106            info.nativeLibraryDir = info.nativeLibraryRootDir;
9107        } else {
9108            // Cluster install
9109            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9110            info.nativeLibraryRootRequiresIsa = true;
9111
9112            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9113                    getPrimaryInstructionSet(info)).getAbsolutePath();
9114
9115            if (info.secondaryCpuAbi != null) {
9116                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9117                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9118            }
9119        }
9120    }
9121
9122    /**
9123     * Calculate the abis and roots for a bundled app. These can uniquely
9124     * be determined from the contents of the system partition, i.e whether
9125     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9126     * of this information, and instead assume that the system was built
9127     * sensibly.
9128     */
9129    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9130                                           PackageSetting pkgSetting) {
9131        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9132
9133        // If "/system/lib64/apkname" exists, assume that is the per-package
9134        // native library directory to use; otherwise use "/system/lib/apkname".
9135        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9136        setBundledAppAbi(pkg, apkRoot, apkName);
9137        // pkgSetting might be null during rescan following uninstall of updates
9138        // to a bundled app, so accommodate that possibility.  The settings in
9139        // that case will be established later from the parsed package.
9140        //
9141        // If the settings aren't null, sync them up with what we've just derived.
9142        // note that apkRoot isn't stored in the package settings.
9143        if (pkgSetting != null) {
9144            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9145            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9146        }
9147    }
9148
9149    /**
9150     * Deduces the ABI of a bundled app and sets the relevant fields on the
9151     * parsed pkg object.
9152     *
9153     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9154     *        under which system libraries are installed.
9155     * @param apkName the name of the installed package.
9156     */
9157    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9158        final File codeFile = new File(pkg.codePath);
9159
9160        final boolean has64BitLibs;
9161        final boolean has32BitLibs;
9162        if (isApkFile(codeFile)) {
9163            // Monolithic install
9164            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9165            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9166        } else {
9167            // Cluster install
9168            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9169            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9170                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9171                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9172                has64BitLibs = (new File(rootDir, isa)).exists();
9173            } else {
9174                has64BitLibs = false;
9175            }
9176            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9177                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9178                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9179                has32BitLibs = (new File(rootDir, isa)).exists();
9180            } else {
9181                has32BitLibs = false;
9182            }
9183        }
9184
9185        if (has64BitLibs && !has32BitLibs) {
9186            // The package has 64 bit libs, but not 32 bit libs. Its primary
9187            // ABI should be 64 bit. We can safely assume here that the bundled
9188            // native libraries correspond to the most preferred ABI in the list.
9189
9190            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9191            pkg.applicationInfo.secondaryCpuAbi = null;
9192        } else if (has32BitLibs && !has64BitLibs) {
9193            // The package has 32 bit libs but not 64 bit libs. Its primary
9194            // ABI should be 32 bit.
9195
9196            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9197            pkg.applicationInfo.secondaryCpuAbi = null;
9198        } else if (has32BitLibs && has64BitLibs) {
9199            // The application has both 64 and 32 bit bundled libraries. We check
9200            // here that the app declares multiArch support, and warn if it doesn't.
9201            //
9202            // We will be lenient here and record both ABIs. The primary will be the
9203            // ABI that's higher on the list, i.e, a device that's configured to prefer
9204            // 64 bit apps will see a 64 bit primary ABI,
9205
9206            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9207                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9208            }
9209
9210            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9211                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9212                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9213            } else {
9214                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9215                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9216            }
9217        } else {
9218            pkg.applicationInfo.primaryCpuAbi = null;
9219            pkg.applicationInfo.secondaryCpuAbi = null;
9220        }
9221    }
9222
9223    private void killApplication(String pkgName, int appId, String reason) {
9224        // Request the ActivityManager to kill the process(only for existing packages)
9225        // so that we do not end up in a confused state while the user is still using the older
9226        // version of the application while the new one gets installed.
9227        final long token = Binder.clearCallingIdentity();
9228        try {
9229            IActivityManager am = ActivityManagerNative.getDefault();
9230            if (am != null) {
9231                try {
9232                    am.killApplicationWithAppId(pkgName, appId, reason);
9233                } catch (RemoteException e) {
9234                }
9235            }
9236        } finally {
9237            Binder.restoreCallingIdentity(token);
9238        }
9239    }
9240
9241    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9242        // Remove the parent package setting
9243        PackageSetting ps = (PackageSetting) pkg.mExtras;
9244        if (ps != null) {
9245            removePackageLI(ps, chatty);
9246        }
9247        // Remove the child package setting
9248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9249        for (int i = 0; i < childCount; i++) {
9250            PackageParser.Package childPkg = pkg.childPackages.get(i);
9251            ps = (PackageSetting) childPkg.mExtras;
9252            if (ps != null) {
9253                removePackageLI(ps, chatty);
9254            }
9255        }
9256    }
9257
9258    void removePackageLI(PackageSetting ps, boolean chatty) {
9259        if (DEBUG_INSTALL) {
9260            if (chatty)
9261                Log.d(TAG, "Removing package " + ps.name);
9262        }
9263
9264        // writer
9265        synchronized (mPackages) {
9266            mPackages.remove(ps.name);
9267            final PackageParser.Package pkg = ps.pkg;
9268            if (pkg != null) {
9269                cleanPackageDataStructuresLILPw(pkg, chatty);
9270            }
9271        }
9272    }
9273
9274    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9275        if (DEBUG_INSTALL) {
9276            if (chatty)
9277                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9278        }
9279
9280        // writer
9281        synchronized (mPackages) {
9282            // Remove the parent package
9283            mPackages.remove(pkg.applicationInfo.packageName);
9284            cleanPackageDataStructuresLILPw(pkg, chatty);
9285
9286            // Remove the child packages
9287            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9288            for (int i = 0; i < childCount; i++) {
9289                PackageParser.Package childPkg = pkg.childPackages.get(i);
9290                mPackages.remove(childPkg.applicationInfo.packageName);
9291                cleanPackageDataStructuresLILPw(childPkg, chatty);
9292            }
9293        }
9294    }
9295
9296    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9297        int N = pkg.providers.size();
9298        StringBuilder r = null;
9299        int i;
9300        for (i=0; i<N; i++) {
9301            PackageParser.Provider p = pkg.providers.get(i);
9302            mProviders.removeProvider(p);
9303            if (p.info.authority == null) {
9304
9305                /* There was another ContentProvider with this authority when
9306                 * this app was installed so this authority is null,
9307                 * Ignore it as we don't have to unregister the provider.
9308                 */
9309                continue;
9310            }
9311            String names[] = p.info.authority.split(";");
9312            for (int j = 0; j < names.length; j++) {
9313                if (mProvidersByAuthority.get(names[j]) == p) {
9314                    mProvidersByAuthority.remove(names[j]);
9315                    if (DEBUG_REMOVE) {
9316                        if (chatty)
9317                            Log.d(TAG, "Unregistered content provider: " + names[j]
9318                                    + ", className = " + p.info.name + ", isSyncable = "
9319                                    + p.info.isSyncable);
9320                    }
9321                }
9322            }
9323            if (DEBUG_REMOVE && chatty) {
9324                if (r == null) {
9325                    r = new StringBuilder(256);
9326                } else {
9327                    r.append(' ');
9328                }
9329                r.append(p.info.name);
9330            }
9331        }
9332        if (r != null) {
9333            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9334        }
9335
9336        N = pkg.services.size();
9337        r = null;
9338        for (i=0; i<N; i++) {
9339            PackageParser.Service s = pkg.services.get(i);
9340            mServices.removeService(s);
9341            if (chatty) {
9342                if (r == null) {
9343                    r = new StringBuilder(256);
9344                } else {
9345                    r.append(' ');
9346                }
9347                r.append(s.info.name);
9348            }
9349        }
9350        if (r != null) {
9351            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9352        }
9353
9354        N = pkg.receivers.size();
9355        r = null;
9356        for (i=0; i<N; i++) {
9357            PackageParser.Activity a = pkg.receivers.get(i);
9358            mReceivers.removeActivity(a, "receiver");
9359            if (DEBUG_REMOVE && chatty) {
9360                if (r == null) {
9361                    r = new StringBuilder(256);
9362                } else {
9363                    r.append(' ');
9364                }
9365                r.append(a.info.name);
9366            }
9367        }
9368        if (r != null) {
9369            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9370        }
9371
9372        N = pkg.activities.size();
9373        r = null;
9374        for (i=0; i<N; i++) {
9375            PackageParser.Activity a = pkg.activities.get(i);
9376            mActivities.removeActivity(a, "activity");
9377            if (DEBUG_REMOVE && chatty) {
9378                if (r == null) {
9379                    r = new StringBuilder(256);
9380                } else {
9381                    r.append(' ');
9382                }
9383                r.append(a.info.name);
9384            }
9385        }
9386        if (r != null) {
9387            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9388        }
9389
9390        N = pkg.permissions.size();
9391        r = null;
9392        for (i=0; i<N; i++) {
9393            PackageParser.Permission p = pkg.permissions.get(i);
9394            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9395            if (bp == null) {
9396                bp = mSettings.mPermissionTrees.get(p.info.name);
9397            }
9398            if (bp != null && bp.perm == p) {
9399                bp.perm = null;
9400                if (DEBUG_REMOVE && chatty) {
9401                    if (r == null) {
9402                        r = new StringBuilder(256);
9403                    } else {
9404                        r.append(' ');
9405                    }
9406                    r.append(p.info.name);
9407                }
9408            }
9409            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9410                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9411                if (appOpPkgs != null) {
9412                    appOpPkgs.remove(pkg.packageName);
9413                }
9414            }
9415        }
9416        if (r != null) {
9417            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9418        }
9419
9420        N = pkg.requestedPermissions.size();
9421        r = null;
9422        for (i=0; i<N; i++) {
9423            String perm = pkg.requestedPermissions.get(i);
9424            BasePermission bp = mSettings.mPermissions.get(perm);
9425            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9426                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9427                if (appOpPkgs != null) {
9428                    appOpPkgs.remove(pkg.packageName);
9429                    if (appOpPkgs.isEmpty()) {
9430                        mAppOpPermissionPackages.remove(perm);
9431                    }
9432                }
9433            }
9434        }
9435        if (r != null) {
9436            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9437        }
9438
9439        N = pkg.instrumentation.size();
9440        r = null;
9441        for (i=0; i<N; i++) {
9442            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9443            mInstrumentation.remove(a.getComponentName());
9444            if (DEBUG_REMOVE && chatty) {
9445                if (r == null) {
9446                    r = new StringBuilder(256);
9447                } else {
9448                    r.append(' ');
9449                }
9450                r.append(a.info.name);
9451            }
9452        }
9453        if (r != null) {
9454            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9455        }
9456
9457        r = null;
9458        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9459            // Only system apps can hold shared libraries.
9460            if (pkg.libraryNames != null) {
9461                for (i=0; i<pkg.libraryNames.size(); i++) {
9462                    String name = pkg.libraryNames.get(i);
9463                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9464                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9465                        mSharedLibraries.remove(name);
9466                        if (DEBUG_REMOVE && chatty) {
9467                            if (r == null) {
9468                                r = new StringBuilder(256);
9469                            } else {
9470                                r.append(' ');
9471                            }
9472                            r.append(name);
9473                        }
9474                    }
9475                }
9476            }
9477        }
9478        if (r != null) {
9479            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9480        }
9481    }
9482
9483    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9484        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9485            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9486                return true;
9487            }
9488        }
9489        return false;
9490    }
9491
9492    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9493    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9494    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9495
9496    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9497        // Update the parent permissions
9498        updatePermissionsLPw(pkg.packageName, pkg, flags);
9499        // Update the child permissions
9500        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9501        for (int i = 0; i < childCount; i++) {
9502            PackageParser.Package childPkg = pkg.childPackages.get(i);
9503            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9504        }
9505    }
9506
9507    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9508            int flags) {
9509        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9510        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9511    }
9512
9513    private void updatePermissionsLPw(String changingPkg,
9514            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9515        // Make sure there are no dangling permission trees.
9516        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9517        while (it.hasNext()) {
9518            final BasePermission bp = it.next();
9519            if (bp.packageSetting == null) {
9520                // We may not yet have parsed the package, so just see if
9521                // we still know about its settings.
9522                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9523            }
9524            if (bp.packageSetting == null) {
9525                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9526                        + " from package " + bp.sourcePackage);
9527                it.remove();
9528            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9529                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9530                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9531                            + " from package " + bp.sourcePackage);
9532                    flags |= UPDATE_PERMISSIONS_ALL;
9533                    it.remove();
9534                }
9535            }
9536        }
9537
9538        // Make sure all dynamic permissions have been assigned to a package,
9539        // and make sure there are no dangling permissions.
9540        it = mSettings.mPermissions.values().iterator();
9541        while (it.hasNext()) {
9542            final BasePermission bp = it.next();
9543            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9544                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9545                        + bp.name + " pkg=" + bp.sourcePackage
9546                        + " info=" + bp.pendingInfo);
9547                if (bp.packageSetting == null && bp.pendingInfo != null) {
9548                    final BasePermission tree = findPermissionTreeLP(bp.name);
9549                    if (tree != null && tree.perm != null) {
9550                        bp.packageSetting = tree.packageSetting;
9551                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9552                                new PermissionInfo(bp.pendingInfo));
9553                        bp.perm.info.packageName = tree.perm.info.packageName;
9554                        bp.perm.info.name = bp.name;
9555                        bp.uid = tree.uid;
9556                    }
9557                }
9558            }
9559            if (bp.packageSetting == null) {
9560                // We may not yet have parsed the package, so just see if
9561                // we still know about its settings.
9562                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9563            }
9564            if (bp.packageSetting == null) {
9565                Slog.w(TAG, "Removing dangling permission: " + bp.name
9566                        + " from package " + bp.sourcePackage);
9567                it.remove();
9568            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9569                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9570                    Slog.i(TAG, "Removing old permission: " + bp.name
9571                            + " from package " + bp.sourcePackage);
9572                    flags |= UPDATE_PERMISSIONS_ALL;
9573                    it.remove();
9574                }
9575            }
9576        }
9577
9578        // Now update the permissions for all packages, in particular
9579        // replace the granted permissions of the system packages.
9580        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9581            for (PackageParser.Package pkg : mPackages.values()) {
9582                if (pkg != pkgInfo) {
9583                    // Only replace for packages on requested volume
9584                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9585                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9586                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9587                    grantPermissionsLPw(pkg, replace, changingPkg);
9588                }
9589            }
9590        }
9591
9592        if (pkgInfo != null) {
9593            // Only replace for packages on requested volume
9594            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9595            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9596                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9597            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9598        }
9599    }
9600
9601    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9602            String packageOfInterest) {
9603        // IMPORTANT: There are two types of permissions: install and runtime.
9604        // Install time permissions are granted when the app is installed to
9605        // all device users and users added in the future. Runtime permissions
9606        // are granted at runtime explicitly to specific users. Normal and signature
9607        // protected permissions are install time permissions. Dangerous permissions
9608        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9609        // otherwise they are runtime permissions. This function does not manage
9610        // runtime permissions except for the case an app targeting Lollipop MR1
9611        // being upgraded to target a newer SDK, in which case dangerous permissions
9612        // are transformed from install time to runtime ones.
9613
9614        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9615        if (ps == null) {
9616            return;
9617        }
9618
9619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9620
9621        PermissionsState permissionsState = ps.getPermissionsState();
9622        PermissionsState origPermissions = permissionsState;
9623
9624        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9625
9626        boolean runtimePermissionsRevoked = false;
9627        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9628
9629        boolean changedInstallPermission = false;
9630
9631        if (replace) {
9632            ps.installPermissionsFixed = false;
9633            if (!ps.isSharedUser()) {
9634                origPermissions = new PermissionsState(permissionsState);
9635                permissionsState.reset();
9636            } else {
9637                // We need to know only about runtime permission changes since the
9638                // calling code always writes the install permissions state but
9639                // the runtime ones are written only if changed. The only cases of
9640                // changed runtime permissions here are promotion of an install to
9641                // runtime and revocation of a runtime from a shared user.
9642                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9643                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9644                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9645                    runtimePermissionsRevoked = true;
9646                }
9647            }
9648        }
9649
9650        permissionsState.setGlobalGids(mGlobalGids);
9651
9652        final int N = pkg.requestedPermissions.size();
9653        for (int i=0; i<N; i++) {
9654            final String name = pkg.requestedPermissions.get(i);
9655            final BasePermission bp = mSettings.mPermissions.get(name);
9656
9657            if (DEBUG_INSTALL) {
9658                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9659            }
9660
9661            if (bp == null || bp.packageSetting == null) {
9662                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9663                    Slog.w(TAG, "Unknown permission " + name
9664                            + " in package " + pkg.packageName);
9665                }
9666                continue;
9667            }
9668
9669            final String perm = bp.name;
9670            boolean allowedSig = false;
9671            int grant = GRANT_DENIED;
9672
9673            // Keep track of app op permissions.
9674            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9675                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9676                if (pkgs == null) {
9677                    pkgs = new ArraySet<>();
9678                    mAppOpPermissionPackages.put(bp.name, pkgs);
9679                }
9680                pkgs.add(pkg.packageName);
9681            }
9682
9683            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9684            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9685                    >= Build.VERSION_CODES.M;
9686            switch (level) {
9687                case PermissionInfo.PROTECTION_NORMAL: {
9688                    // For all apps normal permissions are install time ones.
9689                    grant = GRANT_INSTALL;
9690                } break;
9691
9692                case PermissionInfo.PROTECTION_DANGEROUS: {
9693                    // If a permission review is required for legacy apps we represent
9694                    // their permissions as always granted runtime ones since we need
9695                    // to keep the review required permission flag per user while an
9696                    // install permission's state is shared across all users.
9697                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9698                        // For legacy apps dangerous permissions are install time ones.
9699                        grant = GRANT_INSTALL;
9700                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9701                        // For legacy apps that became modern, install becomes runtime.
9702                        grant = GRANT_UPGRADE;
9703                    } else if (mPromoteSystemApps
9704                            && isSystemApp(ps)
9705                            && mExistingSystemPackages.contains(ps.name)) {
9706                        // For legacy system apps, install becomes runtime.
9707                        // We cannot check hasInstallPermission() for system apps since those
9708                        // permissions were granted implicitly and not persisted pre-M.
9709                        grant = GRANT_UPGRADE;
9710                    } else {
9711                        // For modern apps keep runtime permissions unchanged.
9712                        grant = GRANT_RUNTIME;
9713                    }
9714                } break;
9715
9716                case PermissionInfo.PROTECTION_SIGNATURE: {
9717                    // For all apps signature permissions are install time ones.
9718                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9719                    if (allowedSig) {
9720                        grant = GRANT_INSTALL;
9721                    }
9722                } break;
9723            }
9724
9725            if (DEBUG_INSTALL) {
9726                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9727            }
9728
9729            if (grant != GRANT_DENIED) {
9730                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9731                    // If this is an existing, non-system package, then
9732                    // we can't add any new permissions to it.
9733                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9734                        // Except...  if this is a permission that was added
9735                        // to the platform (note: need to only do this when
9736                        // updating the platform).
9737                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9738                            grant = GRANT_DENIED;
9739                        }
9740                    }
9741                }
9742
9743                switch (grant) {
9744                    case GRANT_INSTALL: {
9745                        // Revoke this as runtime permission to handle the case of
9746                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9747                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9748                            if (origPermissions.getRuntimePermissionState(
9749                                    bp.name, userId) != null) {
9750                                // Revoke the runtime permission and clear the flags.
9751                                origPermissions.revokeRuntimePermission(bp, userId);
9752                                origPermissions.updatePermissionFlags(bp, userId,
9753                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9754                                // If we revoked a permission permission, we have to write.
9755                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9756                                        changedRuntimePermissionUserIds, userId);
9757                            }
9758                        }
9759                        // Grant an install permission.
9760                        if (permissionsState.grantInstallPermission(bp) !=
9761                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9762                            changedInstallPermission = true;
9763                        }
9764                    } break;
9765
9766                    case GRANT_RUNTIME: {
9767                        // Grant previously granted runtime permissions.
9768                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9769                            PermissionState permissionState = origPermissions
9770                                    .getRuntimePermissionState(bp.name, userId);
9771                            int flags = permissionState != null
9772                                    ? permissionState.getFlags() : 0;
9773                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9774                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9775                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9776                                    // If we cannot put the permission as it was, we have to write.
9777                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9778                                            changedRuntimePermissionUserIds, userId);
9779                                }
9780                                // If the app supports runtime permissions no need for a review.
9781                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9782                                        && appSupportsRuntimePermissions
9783                                        && (flags & PackageManager
9784                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9785                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9786                                    // Since we changed the flags, we have to write.
9787                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9788                                            changedRuntimePermissionUserIds, userId);
9789                                }
9790                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9791                                    && !appSupportsRuntimePermissions) {
9792                                // For legacy apps that need a permission review, every new
9793                                // runtime permission is granted but it is pending a review.
9794                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9795                                    permissionsState.grantRuntimePermission(bp, userId);
9796                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9797                                    // We changed the permission and flags, hence have to write.
9798                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9799                                            changedRuntimePermissionUserIds, userId);
9800                                }
9801                            }
9802                            // Propagate the permission flags.
9803                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9804                        }
9805                    } break;
9806
9807                    case GRANT_UPGRADE: {
9808                        // Grant runtime permissions for a previously held install permission.
9809                        PermissionState permissionState = origPermissions
9810                                .getInstallPermissionState(bp.name);
9811                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9812
9813                        if (origPermissions.revokeInstallPermission(bp)
9814                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9815                            // We will be transferring the permission flags, so clear them.
9816                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9817                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9818                            changedInstallPermission = true;
9819                        }
9820
9821                        // If the permission is not to be promoted to runtime we ignore it and
9822                        // also its other flags as they are not applicable to install permissions.
9823                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9824                            for (int userId : currentUserIds) {
9825                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9826                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9827                                    // Transfer the permission flags.
9828                                    permissionsState.updatePermissionFlags(bp, userId,
9829                                            flags, flags);
9830                                    // If we granted the permission, we have to write.
9831                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9832                                            changedRuntimePermissionUserIds, userId);
9833                                }
9834                            }
9835                        }
9836                    } break;
9837
9838                    default: {
9839                        if (packageOfInterest == null
9840                                || packageOfInterest.equals(pkg.packageName)) {
9841                            Slog.w(TAG, "Not granting permission " + perm
9842                                    + " to package " + pkg.packageName
9843                                    + " because it was previously installed without");
9844                        }
9845                    } break;
9846                }
9847            } else {
9848                if (permissionsState.revokeInstallPermission(bp) !=
9849                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9850                    // Also drop the permission flags.
9851                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9852                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9853                    changedInstallPermission = true;
9854                    Slog.i(TAG, "Un-granting permission " + perm
9855                            + " from package " + pkg.packageName
9856                            + " (protectionLevel=" + bp.protectionLevel
9857                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9858                            + ")");
9859                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9860                    // Don't print warning for app op permissions, since it is fine for them
9861                    // not to be granted, there is a UI for the user to decide.
9862                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9863                        Slog.w(TAG, "Not granting permission " + perm
9864                                + " to package " + pkg.packageName
9865                                + " (protectionLevel=" + bp.protectionLevel
9866                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9867                                + ")");
9868                    }
9869                }
9870            }
9871        }
9872
9873        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9874                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9875            // This is the first that we have heard about this package, so the
9876            // permissions we have now selected are fixed until explicitly
9877            // changed.
9878            ps.installPermissionsFixed = true;
9879        }
9880
9881        // Persist the runtime permissions state for users with changes. If permissions
9882        // were revoked because no app in the shared user declares them we have to
9883        // write synchronously to avoid losing runtime permissions state.
9884        for (int userId : changedRuntimePermissionUserIds) {
9885            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9886        }
9887
9888        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9889    }
9890
9891    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9892        boolean allowed = false;
9893        final int NP = PackageParser.NEW_PERMISSIONS.length;
9894        for (int ip=0; ip<NP; ip++) {
9895            final PackageParser.NewPermissionInfo npi
9896                    = PackageParser.NEW_PERMISSIONS[ip];
9897            if (npi.name.equals(perm)
9898                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9899                allowed = true;
9900                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9901                        + pkg.packageName);
9902                break;
9903            }
9904        }
9905        return allowed;
9906    }
9907
9908    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9909            BasePermission bp, PermissionsState origPermissions) {
9910        boolean allowed;
9911        allowed = (compareSignatures(
9912                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9913                        == PackageManager.SIGNATURE_MATCH)
9914                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9915                        == PackageManager.SIGNATURE_MATCH);
9916        if (!allowed && (bp.protectionLevel
9917                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9918            if (isSystemApp(pkg)) {
9919                // For updated system applications, a system permission
9920                // is granted only if it had been defined by the original application.
9921                if (pkg.isUpdatedSystemApp()) {
9922                    final PackageSetting sysPs = mSettings
9923                            .getDisabledSystemPkgLPr(pkg.packageName);
9924                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9925                        // If the original was granted this permission, we take
9926                        // that grant decision as read and propagate it to the
9927                        // update.
9928                        if (sysPs.isPrivileged()) {
9929                            allowed = true;
9930                        }
9931                    } else {
9932                        // The system apk may have been updated with an older
9933                        // version of the one on the data partition, but which
9934                        // granted a new system permission that it didn't have
9935                        // before.  In this case we do want to allow the app to
9936                        // now get the new permission if the ancestral apk is
9937                        // privileged to get it.
9938                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9939                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9940                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9941                                    allowed = true;
9942                                    break;
9943                                }
9944                            }
9945                        }
9946                        // Also if a privileged parent package on the system image or any of
9947                        // its children requested a privileged permission, the updated child
9948                        // packages can also get the permission.
9949                        if (pkg.parentPackage != null) {
9950                            final PackageSetting disabledSysParentPs = mSettings
9951                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9952                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9953                                    && disabledSysParentPs.isPrivileged()) {
9954                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9955                                    allowed = true;
9956                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9957                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9958                                    for (int i = 0; i < count; i++) {
9959                                        PackageParser.Package disabledSysChildPkg =
9960                                                disabledSysParentPs.pkg.childPackages.get(i);
9961                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9962                                                perm)) {
9963                                            allowed = true;
9964                                            break;
9965                                        }
9966                                    }
9967                                }
9968                            }
9969                        }
9970                    }
9971                } else {
9972                    allowed = isPrivilegedApp(pkg);
9973                }
9974            }
9975        }
9976        if (!allowed) {
9977            if (!allowed && (bp.protectionLevel
9978                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9979                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9980                // If this was a previously normal/dangerous permission that got moved
9981                // to a system permission as part of the runtime permission redesign, then
9982                // we still want to blindly grant it to old apps.
9983                allowed = true;
9984            }
9985            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9986                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9987                // If this permission is to be granted to the system installer and
9988                // this app is an installer, then it gets the permission.
9989                allowed = true;
9990            }
9991            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9992                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9993                // If this permission is to be granted to the system verifier and
9994                // this app is a verifier, then it gets the permission.
9995                allowed = true;
9996            }
9997            if (!allowed && (bp.protectionLevel
9998                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9999                    && isSystemApp(pkg)) {
10000                // Any pre-installed system app is allowed to get this permission.
10001                allowed = true;
10002            }
10003            if (!allowed && (bp.protectionLevel
10004                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10005                // For development permissions, a development permission
10006                // is granted only if it was already granted.
10007                allowed = origPermissions.hasInstallPermission(perm);
10008            }
10009            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10010                    && pkg.packageName.equals(mSetupWizardPackage)) {
10011                // If this permission is to be granted to the system setup wizard and
10012                // this app is a setup wizard, then it gets the permission.
10013                allowed = true;
10014            }
10015        }
10016        return allowed;
10017    }
10018
10019    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10020        final int permCount = pkg.requestedPermissions.size();
10021        for (int j = 0; j < permCount; j++) {
10022            String requestedPermission = pkg.requestedPermissions.get(j);
10023            if (permission.equals(requestedPermission)) {
10024                return true;
10025            }
10026        }
10027        return false;
10028    }
10029
10030    final class ActivityIntentResolver
10031            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10032        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10033                boolean defaultOnly, int userId) {
10034            if (!sUserManager.exists(userId)) return null;
10035            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10036            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10037        }
10038
10039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10040                int userId) {
10041            if (!sUserManager.exists(userId)) return null;
10042            mFlags = flags;
10043            return super.queryIntent(intent, resolvedType,
10044                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10045        }
10046
10047        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10048                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10049            if (!sUserManager.exists(userId)) return null;
10050            if (packageActivities == null) {
10051                return null;
10052            }
10053            mFlags = flags;
10054            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10055            final int N = packageActivities.size();
10056            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10057                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10058
10059            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10060            for (int i = 0; i < N; ++i) {
10061                intentFilters = packageActivities.get(i).intents;
10062                if (intentFilters != null && intentFilters.size() > 0) {
10063                    PackageParser.ActivityIntentInfo[] array =
10064                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10065                    intentFilters.toArray(array);
10066                    listCut.add(array);
10067                }
10068            }
10069            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10070        }
10071
10072        /**
10073         * Finds a privileged activity that matches the specified activity names.
10074         */
10075        private PackageParser.Activity findMatchingActivity(
10076                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10077            for (PackageParser.Activity sysActivity : activityList) {
10078                if (sysActivity.info.name.equals(activityInfo.name)) {
10079                    return sysActivity;
10080                }
10081                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10082                    return sysActivity;
10083                }
10084                if (sysActivity.info.targetActivity != null) {
10085                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10086                        return sysActivity;
10087                    }
10088                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10089                        return sysActivity;
10090                    }
10091                }
10092            }
10093            return null;
10094        }
10095
10096        public class IterGenerator<E> {
10097            public Iterator<E> generate(ActivityIntentInfo info) {
10098                return null;
10099            }
10100        }
10101
10102        public class ActionIterGenerator extends IterGenerator<String> {
10103            @Override
10104            public Iterator<String> generate(ActivityIntentInfo info) {
10105                return info.actionsIterator();
10106            }
10107        }
10108
10109        public class CategoriesIterGenerator extends IterGenerator<String> {
10110            @Override
10111            public Iterator<String> generate(ActivityIntentInfo info) {
10112                return info.categoriesIterator();
10113            }
10114        }
10115
10116        public class SchemesIterGenerator extends IterGenerator<String> {
10117            @Override
10118            public Iterator<String> generate(ActivityIntentInfo info) {
10119                return info.schemesIterator();
10120            }
10121        }
10122
10123        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10124            @Override
10125            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10126                return info.authoritiesIterator();
10127            }
10128        }
10129
10130        /**
10131         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10132         * MODIFIED. Do not pass in a list that should not be changed.
10133         */
10134        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10135                IterGenerator<T> generator, Iterator<T> searchIterator) {
10136            // loop through the set of actions; every one must be found in the intent filter
10137            while (searchIterator.hasNext()) {
10138                // we must have at least one filter in the list to consider a match
10139                if (intentList.size() == 0) {
10140                    break;
10141                }
10142
10143                final T searchAction = searchIterator.next();
10144
10145                // loop through the set of intent filters
10146                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10147                while (intentIter.hasNext()) {
10148                    final ActivityIntentInfo intentInfo = intentIter.next();
10149                    boolean selectionFound = false;
10150
10151                    // loop through the intent filter's selection criteria; at least one
10152                    // of them must match the searched criteria
10153                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10154                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10155                        final T intentSelection = intentSelectionIter.next();
10156                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10157                            selectionFound = true;
10158                            break;
10159                        }
10160                    }
10161
10162                    // the selection criteria wasn't found in this filter's set; this filter
10163                    // is not a potential match
10164                    if (!selectionFound) {
10165                        intentIter.remove();
10166                    }
10167                }
10168            }
10169        }
10170
10171        private boolean isProtectedAction(ActivityIntentInfo filter) {
10172            final Iterator<String> actionsIter = filter.actionsIterator();
10173            while (actionsIter != null && actionsIter.hasNext()) {
10174                final String filterAction = actionsIter.next();
10175                if (PROTECTED_ACTIONS.contains(filterAction)) {
10176                    return true;
10177                }
10178            }
10179            return false;
10180        }
10181
10182        /**
10183         * Adjusts the priority of the given intent filter according to policy.
10184         * <p>
10185         * <ul>
10186         * <li>The priority for non privileged applications is capped to '0'</li>
10187         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10188         * <li>The priority for unbundled updates to privileged applications is capped to the
10189         *      priority defined on the system partition</li>
10190         * </ul>
10191         * <p>
10192         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10193         * allowed to obtain any priority on any action.
10194         */
10195        private void adjustPriority(
10196                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10197            // nothing to do; priority is fine as-is
10198            if (intent.getPriority() <= 0) {
10199                return;
10200            }
10201
10202            final ActivityInfo activityInfo = intent.activity.info;
10203            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10204
10205            final boolean privilegedApp =
10206                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10207            if (!privilegedApp) {
10208                // non-privileged applications can never define a priority >0
10209                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10210                        + " package: " + applicationInfo.packageName
10211                        + " activity: " + intent.activity.className
10212                        + " origPrio: " + intent.getPriority());
10213                intent.setPriority(0);
10214                return;
10215            }
10216
10217            if (systemActivities == null) {
10218                // the system package is not disabled; we're parsing the system partition
10219                if (isProtectedAction(intent)) {
10220                    if (mDeferProtectedFilters) {
10221                        // We can't deal with these just yet. No component should ever obtain a
10222                        // >0 priority for a protected actions, with ONE exception -- the setup
10223                        // wizard. The setup wizard, however, cannot be known until we're able to
10224                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10225                        // until all intent filters have been processed. Chicken, meet egg.
10226                        // Let the filter temporarily have a high priority and rectify the
10227                        // priorities after all system packages have been scanned.
10228                        mProtectedFilters.add(intent);
10229                        if (DEBUG_FILTERS) {
10230                            Slog.i(TAG, "Protected action; save for later;"
10231                                    + " package: " + applicationInfo.packageName
10232                                    + " activity: " + intent.activity.className
10233                                    + " origPrio: " + intent.getPriority());
10234                        }
10235                        return;
10236                    } else {
10237                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10238                            Slog.i(TAG, "No setup wizard;"
10239                                + " All protected intents capped to priority 0");
10240                        }
10241                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10242                            if (DEBUG_FILTERS) {
10243                                Slog.i(TAG, "Found setup wizard;"
10244                                    + " allow priority " + intent.getPriority() + ";"
10245                                    + " package: " + intent.activity.info.packageName
10246                                    + " activity: " + intent.activity.className
10247                                    + " priority: " + intent.getPriority());
10248                            }
10249                            // setup wizard gets whatever it wants
10250                            return;
10251                        }
10252                        Slog.w(TAG, "Protected action; cap priority to 0;"
10253                                + " package: " + intent.activity.info.packageName
10254                                + " activity: " + intent.activity.className
10255                                + " origPrio: " + intent.getPriority());
10256                        intent.setPriority(0);
10257                        return;
10258                    }
10259                }
10260                // privileged apps on the system image get whatever priority they request
10261                return;
10262            }
10263
10264            // privileged app unbundled update ... try to find the same activity
10265            final PackageParser.Activity foundActivity =
10266                    findMatchingActivity(systemActivities, activityInfo);
10267            if (foundActivity == null) {
10268                // this is a new activity; it cannot obtain >0 priority
10269                if (DEBUG_FILTERS) {
10270                    Slog.i(TAG, "New activity; cap priority to 0;"
10271                            + " package: " + applicationInfo.packageName
10272                            + " activity: " + intent.activity.className
10273                            + " origPrio: " + intent.getPriority());
10274                }
10275                intent.setPriority(0);
10276                return;
10277            }
10278
10279            // found activity, now check for filter equivalence
10280
10281            // a shallow copy is enough; we modify the list, not its contents
10282            final List<ActivityIntentInfo> intentListCopy =
10283                    new ArrayList<>(foundActivity.intents);
10284            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10285
10286            // find matching action subsets
10287            final Iterator<String> actionsIterator = intent.actionsIterator();
10288            if (actionsIterator != null) {
10289                getIntentListSubset(
10290                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10291                if (intentListCopy.size() == 0) {
10292                    // no more intents to match; we're not equivalent
10293                    if (DEBUG_FILTERS) {
10294                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10295                                + " package: " + applicationInfo.packageName
10296                                + " activity: " + intent.activity.className
10297                                + " origPrio: " + intent.getPriority());
10298                    }
10299                    intent.setPriority(0);
10300                    return;
10301                }
10302            }
10303
10304            // find matching category subsets
10305            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10306            if (categoriesIterator != null) {
10307                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10308                        categoriesIterator);
10309                if (intentListCopy.size() == 0) {
10310                    // no more intents to match; we're not equivalent
10311                    if (DEBUG_FILTERS) {
10312                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10313                                + " package: " + applicationInfo.packageName
10314                                + " activity: " + intent.activity.className
10315                                + " origPrio: " + intent.getPriority());
10316                    }
10317                    intent.setPriority(0);
10318                    return;
10319                }
10320            }
10321
10322            // find matching schemes subsets
10323            final Iterator<String> schemesIterator = intent.schemesIterator();
10324            if (schemesIterator != null) {
10325                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10326                        schemesIterator);
10327                if (intentListCopy.size() == 0) {
10328                    // no more intents to match; we're not equivalent
10329                    if (DEBUG_FILTERS) {
10330                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10331                                + " package: " + applicationInfo.packageName
10332                                + " activity: " + intent.activity.className
10333                                + " origPrio: " + intent.getPriority());
10334                    }
10335                    intent.setPriority(0);
10336                    return;
10337                }
10338            }
10339
10340            // find matching authorities subsets
10341            final Iterator<IntentFilter.AuthorityEntry>
10342                    authoritiesIterator = intent.authoritiesIterator();
10343            if (authoritiesIterator != null) {
10344                getIntentListSubset(intentListCopy,
10345                        new AuthoritiesIterGenerator(),
10346                        authoritiesIterator);
10347                if (intentListCopy.size() == 0) {
10348                    // no more intents to match; we're not equivalent
10349                    if (DEBUG_FILTERS) {
10350                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10351                                + " package: " + applicationInfo.packageName
10352                                + " activity: " + intent.activity.className
10353                                + " origPrio: " + intent.getPriority());
10354                    }
10355                    intent.setPriority(0);
10356                    return;
10357                }
10358            }
10359
10360            // we found matching filter(s); app gets the max priority of all intents
10361            int cappedPriority = 0;
10362            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10363                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10364            }
10365            if (intent.getPriority() > cappedPriority) {
10366                if (DEBUG_FILTERS) {
10367                    Slog.i(TAG, "Found matching filter(s);"
10368                            + " cap priority to " + cappedPriority + ";"
10369                            + " package: " + applicationInfo.packageName
10370                            + " activity: " + intent.activity.className
10371                            + " origPrio: " + intent.getPriority());
10372                }
10373                intent.setPriority(cappedPriority);
10374                return;
10375            }
10376            // all this for nothing; the requested priority was <= what was on the system
10377        }
10378
10379        public final void addActivity(PackageParser.Activity a, String type) {
10380            mActivities.put(a.getComponentName(), a);
10381            if (DEBUG_SHOW_INFO)
10382                Log.v(
10383                TAG, "  " + type + " " +
10384                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10385            if (DEBUG_SHOW_INFO)
10386                Log.v(TAG, "    Class=" + a.info.name);
10387            final int NI = a.intents.size();
10388            for (int j=0; j<NI; j++) {
10389                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10390                if ("activity".equals(type)) {
10391                    final PackageSetting ps =
10392                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10393                    final List<PackageParser.Activity> systemActivities =
10394                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10395                    adjustPriority(systemActivities, intent);
10396                }
10397                if (DEBUG_SHOW_INFO) {
10398                    Log.v(TAG, "    IntentFilter:");
10399                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10400                }
10401                if (!intent.debugCheck()) {
10402                    Log.w(TAG, "==> For Activity " + a.info.name);
10403                }
10404                addFilter(intent);
10405            }
10406        }
10407
10408        public final void removeActivity(PackageParser.Activity a, String type) {
10409            mActivities.remove(a.getComponentName());
10410            if (DEBUG_SHOW_INFO) {
10411                Log.v(TAG, "  " + type + " "
10412                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10413                                : a.info.name) + ":");
10414                Log.v(TAG, "    Class=" + a.info.name);
10415            }
10416            final int NI = a.intents.size();
10417            for (int j=0; j<NI; j++) {
10418                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10419                if (DEBUG_SHOW_INFO) {
10420                    Log.v(TAG, "    IntentFilter:");
10421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10422                }
10423                removeFilter(intent);
10424            }
10425        }
10426
10427        @Override
10428        protected boolean allowFilterResult(
10429                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10430            ActivityInfo filterAi = filter.activity.info;
10431            for (int i=dest.size()-1; i>=0; i--) {
10432                ActivityInfo destAi = dest.get(i).activityInfo;
10433                if (destAi.name == filterAi.name
10434                        && destAi.packageName == filterAi.packageName) {
10435                    return false;
10436                }
10437            }
10438            return true;
10439        }
10440
10441        @Override
10442        protected ActivityIntentInfo[] newArray(int size) {
10443            return new ActivityIntentInfo[size];
10444        }
10445
10446        @Override
10447        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10448            if (!sUserManager.exists(userId)) return true;
10449            PackageParser.Package p = filter.activity.owner;
10450            if (p != null) {
10451                PackageSetting ps = (PackageSetting)p.mExtras;
10452                if (ps != null) {
10453                    // System apps are never considered stopped for purposes of
10454                    // filtering, because there may be no way for the user to
10455                    // actually re-launch them.
10456                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10457                            && ps.getStopped(userId);
10458                }
10459            }
10460            return false;
10461        }
10462
10463        @Override
10464        protected boolean isPackageForFilter(String packageName,
10465                PackageParser.ActivityIntentInfo info) {
10466            return packageName.equals(info.activity.owner.packageName);
10467        }
10468
10469        @Override
10470        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10471                int match, int userId) {
10472            if (!sUserManager.exists(userId)) return null;
10473            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10474                return null;
10475            }
10476            final PackageParser.Activity activity = info.activity;
10477            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10478            if (ps == null) {
10479                return null;
10480            }
10481            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10482                    ps.readUserState(userId), userId);
10483            if (ai == null) {
10484                return null;
10485            }
10486            final ResolveInfo res = new ResolveInfo();
10487            res.activityInfo = ai;
10488            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10489                res.filter = info;
10490            }
10491            if (info != null) {
10492                res.handleAllWebDataURI = info.handleAllWebDataURI();
10493            }
10494            res.priority = info.getPriority();
10495            res.preferredOrder = activity.owner.mPreferredOrder;
10496            //System.out.println("Result: " + res.activityInfo.className +
10497            //                   " = " + res.priority);
10498            res.match = match;
10499            res.isDefault = info.hasDefault;
10500            res.labelRes = info.labelRes;
10501            res.nonLocalizedLabel = info.nonLocalizedLabel;
10502            if (userNeedsBadging(userId)) {
10503                res.noResourceId = true;
10504            } else {
10505                res.icon = info.icon;
10506            }
10507            res.iconResourceId = info.icon;
10508            res.system = res.activityInfo.applicationInfo.isSystemApp();
10509            return res;
10510        }
10511
10512        @Override
10513        protected void sortResults(List<ResolveInfo> results) {
10514            Collections.sort(results, mResolvePrioritySorter);
10515        }
10516
10517        @Override
10518        protected void dumpFilter(PrintWriter out, String prefix,
10519                PackageParser.ActivityIntentInfo filter) {
10520            out.print(prefix); out.print(
10521                    Integer.toHexString(System.identityHashCode(filter.activity)));
10522                    out.print(' ');
10523                    filter.activity.printComponentShortName(out);
10524                    out.print(" filter ");
10525                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10526        }
10527
10528        @Override
10529        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10530            return filter.activity;
10531        }
10532
10533        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10534            PackageParser.Activity activity = (PackageParser.Activity)label;
10535            out.print(prefix); out.print(
10536                    Integer.toHexString(System.identityHashCode(activity)));
10537                    out.print(' ');
10538                    activity.printComponentShortName(out);
10539            if (count > 1) {
10540                out.print(" ("); out.print(count); out.print(" filters)");
10541            }
10542            out.println();
10543        }
10544
10545        // Keys are String (activity class name), values are Activity.
10546        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10547                = new ArrayMap<ComponentName, PackageParser.Activity>();
10548        private int mFlags;
10549    }
10550
10551    private final class ServiceIntentResolver
10552            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10553        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10554                boolean defaultOnly, int userId) {
10555            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10556            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10557        }
10558
10559        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10560                int userId) {
10561            if (!sUserManager.exists(userId)) return null;
10562            mFlags = flags;
10563            return super.queryIntent(intent, resolvedType,
10564                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10565        }
10566
10567        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10568                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10569            if (!sUserManager.exists(userId)) return null;
10570            if (packageServices == null) {
10571                return null;
10572            }
10573            mFlags = flags;
10574            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10575            final int N = packageServices.size();
10576            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10577                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10578
10579            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10580            for (int i = 0; i < N; ++i) {
10581                intentFilters = packageServices.get(i).intents;
10582                if (intentFilters != null && intentFilters.size() > 0) {
10583                    PackageParser.ServiceIntentInfo[] array =
10584                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10585                    intentFilters.toArray(array);
10586                    listCut.add(array);
10587                }
10588            }
10589            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10590        }
10591
10592        public final void addService(PackageParser.Service s) {
10593            mServices.put(s.getComponentName(), s);
10594            if (DEBUG_SHOW_INFO) {
10595                Log.v(TAG, "  "
10596                        + (s.info.nonLocalizedLabel != null
10597                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10598                Log.v(TAG, "    Class=" + s.info.name);
10599            }
10600            final int NI = s.intents.size();
10601            int j;
10602            for (j=0; j<NI; j++) {
10603                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10604                if (DEBUG_SHOW_INFO) {
10605                    Log.v(TAG, "    IntentFilter:");
10606                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10607                }
10608                if (!intent.debugCheck()) {
10609                    Log.w(TAG, "==> For Service " + s.info.name);
10610                }
10611                addFilter(intent);
10612            }
10613        }
10614
10615        public final void removeService(PackageParser.Service s) {
10616            mServices.remove(s.getComponentName());
10617            if (DEBUG_SHOW_INFO) {
10618                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10619                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10620                Log.v(TAG, "    Class=" + s.info.name);
10621            }
10622            final int NI = s.intents.size();
10623            int j;
10624            for (j=0; j<NI; j++) {
10625                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10626                if (DEBUG_SHOW_INFO) {
10627                    Log.v(TAG, "    IntentFilter:");
10628                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10629                }
10630                removeFilter(intent);
10631            }
10632        }
10633
10634        @Override
10635        protected boolean allowFilterResult(
10636                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10637            ServiceInfo filterSi = filter.service.info;
10638            for (int i=dest.size()-1; i>=0; i--) {
10639                ServiceInfo destAi = dest.get(i).serviceInfo;
10640                if (destAi.name == filterSi.name
10641                        && destAi.packageName == filterSi.packageName) {
10642                    return false;
10643                }
10644            }
10645            return true;
10646        }
10647
10648        @Override
10649        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10650            return new PackageParser.ServiceIntentInfo[size];
10651        }
10652
10653        @Override
10654        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10655            if (!sUserManager.exists(userId)) return true;
10656            PackageParser.Package p = filter.service.owner;
10657            if (p != null) {
10658                PackageSetting ps = (PackageSetting)p.mExtras;
10659                if (ps != null) {
10660                    // System apps are never considered stopped for purposes of
10661                    // filtering, because there may be no way for the user to
10662                    // actually re-launch them.
10663                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10664                            && ps.getStopped(userId);
10665                }
10666            }
10667            return false;
10668        }
10669
10670        @Override
10671        protected boolean isPackageForFilter(String packageName,
10672                PackageParser.ServiceIntentInfo info) {
10673            return packageName.equals(info.service.owner.packageName);
10674        }
10675
10676        @Override
10677        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10678                int match, int userId) {
10679            if (!sUserManager.exists(userId)) return null;
10680            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10681            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10682                return null;
10683            }
10684            final PackageParser.Service service = info.service;
10685            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10686            if (ps == null) {
10687                return null;
10688            }
10689            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10690                    ps.readUserState(userId), userId);
10691            if (si == null) {
10692                return null;
10693            }
10694            final ResolveInfo res = new ResolveInfo();
10695            res.serviceInfo = si;
10696            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10697                res.filter = filter;
10698            }
10699            res.priority = info.getPriority();
10700            res.preferredOrder = service.owner.mPreferredOrder;
10701            res.match = match;
10702            res.isDefault = info.hasDefault;
10703            res.labelRes = info.labelRes;
10704            res.nonLocalizedLabel = info.nonLocalizedLabel;
10705            res.icon = info.icon;
10706            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10707            return res;
10708        }
10709
10710        @Override
10711        protected void sortResults(List<ResolveInfo> results) {
10712            Collections.sort(results, mResolvePrioritySorter);
10713        }
10714
10715        @Override
10716        protected void dumpFilter(PrintWriter out, String prefix,
10717                PackageParser.ServiceIntentInfo filter) {
10718            out.print(prefix); out.print(
10719                    Integer.toHexString(System.identityHashCode(filter.service)));
10720                    out.print(' ');
10721                    filter.service.printComponentShortName(out);
10722                    out.print(" filter ");
10723                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10724        }
10725
10726        @Override
10727        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10728            return filter.service;
10729        }
10730
10731        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10732            PackageParser.Service service = (PackageParser.Service)label;
10733            out.print(prefix); out.print(
10734                    Integer.toHexString(System.identityHashCode(service)));
10735                    out.print(' ');
10736                    service.printComponentShortName(out);
10737            if (count > 1) {
10738                out.print(" ("); out.print(count); out.print(" filters)");
10739            }
10740            out.println();
10741        }
10742
10743//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10744//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10745//            final List<ResolveInfo> retList = Lists.newArrayList();
10746//            while (i.hasNext()) {
10747//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10748//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10749//                    retList.add(resolveInfo);
10750//                }
10751//            }
10752//            return retList;
10753//        }
10754
10755        // Keys are String (activity class name), values are Activity.
10756        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10757                = new ArrayMap<ComponentName, PackageParser.Service>();
10758        private int mFlags;
10759    };
10760
10761    private final class ProviderIntentResolver
10762            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10764                boolean defaultOnly, int userId) {
10765            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10766            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10767        }
10768
10769        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10770                int userId) {
10771            if (!sUserManager.exists(userId))
10772                return null;
10773            mFlags = flags;
10774            return super.queryIntent(intent, resolvedType,
10775                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10776        }
10777
10778        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10779                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10780            if (!sUserManager.exists(userId))
10781                return null;
10782            if (packageProviders == null) {
10783                return null;
10784            }
10785            mFlags = flags;
10786            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10787            final int N = packageProviders.size();
10788            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10789                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10790
10791            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10792            for (int i = 0; i < N; ++i) {
10793                intentFilters = packageProviders.get(i).intents;
10794                if (intentFilters != null && intentFilters.size() > 0) {
10795                    PackageParser.ProviderIntentInfo[] array =
10796                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10797                    intentFilters.toArray(array);
10798                    listCut.add(array);
10799                }
10800            }
10801            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10802        }
10803
10804        public final void addProvider(PackageParser.Provider p) {
10805            if (mProviders.containsKey(p.getComponentName())) {
10806                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10807                return;
10808            }
10809
10810            mProviders.put(p.getComponentName(), p);
10811            if (DEBUG_SHOW_INFO) {
10812                Log.v(TAG, "  "
10813                        + (p.info.nonLocalizedLabel != null
10814                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10815                Log.v(TAG, "    Class=" + p.info.name);
10816            }
10817            final int NI = p.intents.size();
10818            int j;
10819            for (j = 0; j < NI; j++) {
10820                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10821                if (DEBUG_SHOW_INFO) {
10822                    Log.v(TAG, "    IntentFilter:");
10823                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10824                }
10825                if (!intent.debugCheck()) {
10826                    Log.w(TAG, "==> For Provider " + p.info.name);
10827                }
10828                addFilter(intent);
10829            }
10830        }
10831
10832        public final void removeProvider(PackageParser.Provider p) {
10833            mProviders.remove(p.getComponentName());
10834            if (DEBUG_SHOW_INFO) {
10835                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10836                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10837                Log.v(TAG, "    Class=" + p.info.name);
10838            }
10839            final int NI = p.intents.size();
10840            int j;
10841            for (j = 0; j < NI; j++) {
10842                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10843                if (DEBUG_SHOW_INFO) {
10844                    Log.v(TAG, "    IntentFilter:");
10845                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10846                }
10847                removeFilter(intent);
10848            }
10849        }
10850
10851        @Override
10852        protected boolean allowFilterResult(
10853                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10854            ProviderInfo filterPi = filter.provider.info;
10855            for (int i = dest.size() - 1; i >= 0; i--) {
10856                ProviderInfo destPi = dest.get(i).providerInfo;
10857                if (destPi.name == filterPi.name
10858                        && destPi.packageName == filterPi.packageName) {
10859                    return false;
10860                }
10861            }
10862            return true;
10863        }
10864
10865        @Override
10866        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10867            return new PackageParser.ProviderIntentInfo[size];
10868        }
10869
10870        @Override
10871        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10872            if (!sUserManager.exists(userId))
10873                return true;
10874            PackageParser.Package p = filter.provider.owner;
10875            if (p != null) {
10876                PackageSetting ps = (PackageSetting) p.mExtras;
10877                if (ps != null) {
10878                    // System apps are never considered stopped for purposes of
10879                    // filtering, because there may be no way for the user to
10880                    // actually re-launch them.
10881                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10882                            && ps.getStopped(userId);
10883                }
10884            }
10885            return false;
10886        }
10887
10888        @Override
10889        protected boolean isPackageForFilter(String packageName,
10890                PackageParser.ProviderIntentInfo info) {
10891            return packageName.equals(info.provider.owner.packageName);
10892        }
10893
10894        @Override
10895        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10896                int match, int userId) {
10897            if (!sUserManager.exists(userId))
10898                return null;
10899            final PackageParser.ProviderIntentInfo info = filter;
10900            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10901                return null;
10902            }
10903            final PackageParser.Provider provider = info.provider;
10904            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10905            if (ps == null) {
10906                return null;
10907            }
10908            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10909                    ps.readUserState(userId), userId);
10910            if (pi == null) {
10911                return null;
10912            }
10913            final ResolveInfo res = new ResolveInfo();
10914            res.providerInfo = pi;
10915            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10916                res.filter = filter;
10917            }
10918            res.priority = info.getPriority();
10919            res.preferredOrder = provider.owner.mPreferredOrder;
10920            res.match = match;
10921            res.isDefault = info.hasDefault;
10922            res.labelRes = info.labelRes;
10923            res.nonLocalizedLabel = info.nonLocalizedLabel;
10924            res.icon = info.icon;
10925            res.system = res.providerInfo.applicationInfo.isSystemApp();
10926            return res;
10927        }
10928
10929        @Override
10930        protected void sortResults(List<ResolveInfo> results) {
10931            Collections.sort(results, mResolvePrioritySorter);
10932        }
10933
10934        @Override
10935        protected void dumpFilter(PrintWriter out, String prefix,
10936                PackageParser.ProviderIntentInfo filter) {
10937            out.print(prefix);
10938            out.print(
10939                    Integer.toHexString(System.identityHashCode(filter.provider)));
10940            out.print(' ');
10941            filter.provider.printComponentShortName(out);
10942            out.print(" filter ");
10943            out.println(Integer.toHexString(System.identityHashCode(filter)));
10944        }
10945
10946        @Override
10947        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10948            return filter.provider;
10949        }
10950
10951        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10952            PackageParser.Provider provider = (PackageParser.Provider)label;
10953            out.print(prefix); out.print(
10954                    Integer.toHexString(System.identityHashCode(provider)));
10955                    out.print(' ');
10956                    provider.printComponentShortName(out);
10957            if (count > 1) {
10958                out.print(" ("); out.print(count); out.print(" filters)");
10959            }
10960            out.println();
10961        }
10962
10963        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10964                = new ArrayMap<ComponentName, PackageParser.Provider>();
10965        private int mFlags;
10966    }
10967
10968    private static final class EphemeralIntentResolver
10969            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10970        @Override
10971        protected EphemeralResolveIntentInfo[] newArray(int size) {
10972            return new EphemeralResolveIntentInfo[size];
10973        }
10974
10975        @Override
10976        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10977            return true;
10978        }
10979
10980        @Override
10981        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10982                int userId) {
10983            if (!sUserManager.exists(userId)) {
10984                return null;
10985            }
10986            return info.getEphemeralResolveInfo();
10987        }
10988    }
10989
10990    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10991            new Comparator<ResolveInfo>() {
10992        public int compare(ResolveInfo r1, ResolveInfo r2) {
10993            int v1 = r1.priority;
10994            int v2 = r2.priority;
10995            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10996            if (v1 != v2) {
10997                return (v1 > v2) ? -1 : 1;
10998            }
10999            v1 = r1.preferredOrder;
11000            v2 = r2.preferredOrder;
11001            if (v1 != v2) {
11002                return (v1 > v2) ? -1 : 1;
11003            }
11004            if (r1.isDefault != r2.isDefault) {
11005                return r1.isDefault ? -1 : 1;
11006            }
11007            v1 = r1.match;
11008            v2 = r2.match;
11009            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11010            if (v1 != v2) {
11011                return (v1 > v2) ? -1 : 1;
11012            }
11013            if (r1.system != r2.system) {
11014                return r1.system ? -1 : 1;
11015            }
11016            if (r1.activityInfo != null) {
11017                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11018            }
11019            if (r1.serviceInfo != null) {
11020                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11021            }
11022            if (r1.providerInfo != null) {
11023                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11024            }
11025            return 0;
11026        }
11027    };
11028
11029    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11030            new Comparator<ProviderInfo>() {
11031        public int compare(ProviderInfo p1, ProviderInfo p2) {
11032            final int v1 = p1.initOrder;
11033            final int v2 = p2.initOrder;
11034            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11035        }
11036    };
11037
11038    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11039            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11040            final int[] userIds) {
11041        mHandler.post(new Runnable() {
11042            @Override
11043            public void run() {
11044                try {
11045                    final IActivityManager am = ActivityManagerNative.getDefault();
11046                    if (am == null) return;
11047                    final int[] resolvedUserIds;
11048                    if (userIds == null) {
11049                        resolvedUserIds = am.getRunningUserIds();
11050                    } else {
11051                        resolvedUserIds = userIds;
11052                    }
11053                    for (int id : resolvedUserIds) {
11054                        final Intent intent = new Intent(action,
11055                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11056                        if (extras != null) {
11057                            intent.putExtras(extras);
11058                        }
11059                        if (targetPkg != null) {
11060                            intent.setPackage(targetPkg);
11061                        }
11062                        // Modify the UID when posting to other users
11063                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11064                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11065                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11066                            intent.putExtra(Intent.EXTRA_UID, uid);
11067                        }
11068                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11069                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11070                        if (DEBUG_BROADCASTS) {
11071                            RuntimeException here = new RuntimeException("here");
11072                            here.fillInStackTrace();
11073                            Slog.d(TAG, "Sending to user " + id + ": "
11074                                    + intent.toShortString(false, true, false, false)
11075                                    + " " + intent.getExtras(), here);
11076                        }
11077                        am.broadcastIntent(null, intent, null, finishedReceiver,
11078                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11079                                null, finishedReceiver != null, false, id);
11080                    }
11081                } catch (RemoteException ex) {
11082                }
11083            }
11084        });
11085    }
11086
11087    /**
11088     * Check if the external storage media is available. This is true if there
11089     * is a mounted external storage medium or if the external storage is
11090     * emulated.
11091     */
11092    private boolean isExternalMediaAvailable() {
11093        return mMediaMounted || Environment.isExternalStorageEmulated();
11094    }
11095
11096    @Override
11097    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11098        // writer
11099        synchronized (mPackages) {
11100            if (!isExternalMediaAvailable()) {
11101                // If the external storage is no longer mounted at this point,
11102                // the caller may not have been able to delete all of this
11103                // packages files and can not delete any more.  Bail.
11104                return null;
11105            }
11106            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11107            if (lastPackage != null) {
11108                pkgs.remove(lastPackage);
11109            }
11110            if (pkgs.size() > 0) {
11111                return pkgs.get(0);
11112            }
11113        }
11114        return null;
11115    }
11116
11117    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11118        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11119                userId, andCode ? 1 : 0, packageName);
11120        if (mSystemReady) {
11121            msg.sendToTarget();
11122        } else {
11123            if (mPostSystemReadyMessages == null) {
11124                mPostSystemReadyMessages = new ArrayList<>();
11125            }
11126            mPostSystemReadyMessages.add(msg);
11127        }
11128    }
11129
11130    void startCleaningPackages() {
11131        // reader
11132        if (!isExternalMediaAvailable()) {
11133            return;
11134        }
11135        synchronized (mPackages) {
11136            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11137                return;
11138            }
11139        }
11140        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11141        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11142        IActivityManager am = ActivityManagerNative.getDefault();
11143        if (am != null) {
11144            try {
11145                am.startService(null, intent, null, mContext.getOpPackageName(),
11146                        UserHandle.USER_SYSTEM);
11147            } catch (RemoteException e) {
11148            }
11149        }
11150    }
11151
11152    @Override
11153    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11154            int installFlags, String installerPackageName, int userId) {
11155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11156
11157        final int callingUid = Binder.getCallingUid();
11158        enforceCrossUserPermission(callingUid, userId,
11159                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11160
11161        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11162            try {
11163                if (observer != null) {
11164                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11165                }
11166            } catch (RemoteException re) {
11167            }
11168            return;
11169        }
11170
11171        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11172            installFlags |= PackageManager.INSTALL_FROM_ADB;
11173
11174        } else {
11175            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11176            // about installerPackageName.
11177
11178            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11179            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11180        }
11181
11182        UserHandle user;
11183        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11184            user = UserHandle.ALL;
11185        } else {
11186            user = new UserHandle(userId);
11187        }
11188
11189        // Only system components can circumvent runtime permissions when installing.
11190        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11191                && mContext.checkCallingOrSelfPermission(Manifest.permission
11192                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11193            throw new SecurityException("You need the "
11194                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11195                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11196        }
11197
11198        final File originFile = new File(originPath);
11199        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11200
11201        final Message msg = mHandler.obtainMessage(INIT_COPY);
11202        final VerificationInfo verificationInfo = new VerificationInfo(
11203                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11204        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11205                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11206                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11207                null /*certificates*/);
11208        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11209        msg.obj = params;
11210
11211        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11212                System.identityHashCode(msg.obj));
11213        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11214                System.identityHashCode(msg.obj));
11215
11216        mHandler.sendMessage(msg);
11217    }
11218
11219    void installStage(String packageName, File stagedDir, String stagedCid,
11220            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11221            String installerPackageName, int installerUid, UserHandle user,
11222            Certificate[][] certificates) {
11223        if (DEBUG_EPHEMERAL) {
11224            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11225                Slog.d(TAG, "Ephemeral install of " + packageName);
11226            }
11227        }
11228        final VerificationInfo verificationInfo = new VerificationInfo(
11229                sessionParams.originatingUri, sessionParams.referrerUri,
11230                sessionParams.originatingUid, installerUid);
11231
11232        final OriginInfo origin;
11233        if (stagedDir != null) {
11234            origin = OriginInfo.fromStagedFile(stagedDir);
11235        } else {
11236            origin = OriginInfo.fromStagedContainer(stagedCid);
11237        }
11238
11239        final Message msg = mHandler.obtainMessage(INIT_COPY);
11240        final InstallParams params = new InstallParams(origin, null, observer,
11241                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11242                verificationInfo, user, sessionParams.abiOverride,
11243                sessionParams.grantedRuntimePermissions, certificates);
11244        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11245        msg.obj = params;
11246
11247        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11248                System.identityHashCode(msg.obj));
11249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11250                System.identityHashCode(msg.obj));
11251
11252        mHandler.sendMessage(msg);
11253    }
11254
11255    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11256            int userId) {
11257        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11258        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11259    }
11260
11261    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11262            int appId, int userId) {
11263        Bundle extras = new Bundle(1);
11264        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11265
11266        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11267                packageName, extras, 0, null, null, new int[] {userId});
11268        try {
11269            IActivityManager am = ActivityManagerNative.getDefault();
11270            if (isSystem && am.isUserRunning(userId, 0)) {
11271                // The just-installed/enabled app is bundled on the system, so presumed
11272                // to be able to run automatically without needing an explicit launch.
11273                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11274                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11275                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11276                        .setPackage(packageName);
11277                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11278                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11279            }
11280        } catch (RemoteException e) {
11281            // shouldn't happen
11282            Slog.w(TAG, "Unable to bootstrap installed package", e);
11283        }
11284    }
11285
11286    @Override
11287    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11288            int userId) {
11289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11290        PackageSetting pkgSetting;
11291        final int uid = Binder.getCallingUid();
11292        enforceCrossUserPermission(uid, userId,
11293                true /* requireFullPermission */, true /* checkShell */,
11294                "setApplicationHiddenSetting for user " + userId);
11295
11296        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11297            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11298            return false;
11299        }
11300
11301        long callingId = Binder.clearCallingIdentity();
11302        try {
11303            boolean sendAdded = false;
11304            boolean sendRemoved = false;
11305            // writer
11306            synchronized (mPackages) {
11307                pkgSetting = mSettings.mPackages.get(packageName);
11308                if (pkgSetting == null) {
11309                    return false;
11310                }
11311                if (pkgSetting.getHidden(userId) != hidden) {
11312                    pkgSetting.setHidden(hidden, userId);
11313                    mSettings.writePackageRestrictionsLPr(userId);
11314                    if (hidden) {
11315                        sendRemoved = true;
11316                    } else {
11317                        sendAdded = true;
11318                    }
11319                }
11320            }
11321            if (sendAdded) {
11322                sendPackageAddedForUser(packageName, pkgSetting, userId);
11323                return true;
11324            }
11325            if (sendRemoved) {
11326                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11327                        "hiding pkg");
11328                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11329                return true;
11330            }
11331        } finally {
11332            Binder.restoreCallingIdentity(callingId);
11333        }
11334        return false;
11335    }
11336
11337    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11338            int userId) {
11339        final PackageRemovedInfo info = new PackageRemovedInfo();
11340        info.removedPackage = packageName;
11341        info.removedUsers = new int[] {userId};
11342        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11343        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11344    }
11345
11346    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11347        if (pkgList.length > 0) {
11348            Bundle extras = new Bundle(1);
11349            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11350
11351            sendPackageBroadcast(
11352                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11353                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11354                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11355                    new int[] {userId});
11356        }
11357    }
11358
11359    /**
11360     * Returns true if application is not found or there was an error. Otherwise it returns
11361     * the hidden state of the package for the given user.
11362     */
11363    @Override
11364    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11365        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11366        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11367                true /* requireFullPermission */, false /* checkShell */,
11368                "getApplicationHidden for user " + userId);
11369        PackageSetting pkgSetting;
11370        long callingId = Binder.clearCallingIdentity();
11371        try {
11372            // writer
11373            synchronized (mPackages) {
11374                pkgSetting = mSettings.mPackages.get(packageName);
11375                if (pkgSetting == null) {
11376                    return true;
11377                }
11378                return pkgSetting.getHidden(userId);
11379            }
11380        } finally {
11381            Binder.restoreCallingIdentity(callingId);
11382        }
11383    }
11384
11385    /**
11386     * @hide
11387     */
11388    @Override
11389    public int installExistingPackageAsUser(String packageName, int userId) {
11390        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11391                null);
11392        PackageSetting pkgSetting;
11393        final int uid = Binder.getCallingUid();
11394        enforceCrossUserPermission(uid, userId,
11395                true /* requireFullPermission */, true /* checkShell */,
11396                "installExistingPackage for user " + userId);
11397        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11398            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11399        }
11400
11401        long callingId = Binder.clearCallingIdentity();
11402        try {
11403            boolean installed = false;
11404
11405            // writer
11406            synchronized (mPackages) {
11407                pkgSetting = mSettings.mPackages.get(packageName);
11408                if (pkgSetting == null) {
11409                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11410                }
11411                if (!pkgSetting.getInstalled(userId)) {
11412                    pkgSetting.setInstalled(true, userId);
11413                    pkgSetting.setHidden(false, userId);
11414                    mSettings.writePackageRestrictionsLPr(userId);
11415                    installed = true;
11416                }
11417            }
11418
11419            if (installed) {
11420                if (pkgSetting.pkg != null) {
11421                    synchronized (mInstallLock) {
11422                        // We don't need to freeze for a brand new install
11423                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11424                    }
11425                }
11426                sendPackageAddedForUser(packageName, pkgSetting, userId);
11427            }
11428        } finally {
11429            Binder.restoreCallingIdentity(callingId);
11430        }
11431
11432        return PackageManager.INSTALL_SUCCEEDED;
11433    }
11434
11435    boolean isUserRestricted(int userId, String restrictionKey) {
11436        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11437        if (restrictions.getBoolean(restrictionKey, false)) {
11438            Log.w(TAG, "User is restricted: " + restrictionKey);
11439            return true;
11440        }
11441        return false;
11442    }
11443
11444    @Override
11445    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11446            int userId) {
11447        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11449                true /* requireFullPermission */, true /* checkShell */,
11450                "setPackagesSuspended for user " + userId);
11451
11452        if (ArrayUtils.isEmpty(packageNames)) {
11453            return packageNames;
11454        }
11455
11456        // List of package names for whom the suspended state has changed.
11457        List<String> changedPackages = new ArrayList<>(packageNames.length);
11458        // List of package names for whom the suspended state is not set as requested in this
11459        // method.
11460        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11461        for (int i = 0; i < packageNames.length; i++) {
11462            String packageName = packageNames[i];
11463            long callingId = Binder.clearCallingIdentity();
11464            try {
11465                boolean changed = false;
11466                final int appId;
11467                synchronized (mPackages) {
11468                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11469                    if (pkgSetting == null) {
11470                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11471                                + "\". Skipping suspending/un-suspending.");
11472                        unactionedPackages.add(packageName);
11473                        continue;
11474                    }
11475                    appId = pkgSetting.appId;
11476                    if (pkgSetting.getSuspended(userId) != suspended) {
11477                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11478                            unactionedPackages.add(packageName);
11479                            continue;
11480                        }
11481                        pkgSetting.setSuspended(suspended, userId);
11482                        mSettings.writePackageRestrictionsLPr(userId);
11483                        changed = true;
11484                        changedPackages.add(packageName);
11485                    }
11486                }
11487
11488                if (changed && suspended) {
11489                    killApplication(packageName, UserHandle.getUid(userId, appId),
11490                            "suspending package");
11491                }
11492            } finally {
11493                Binder.restoreCallingIdentity(callingId);
11494            }
11495        }
11496
11497        if (!changedPackages.isEmpty()) {
11498            sendPackagesSuspendedForUser(changedPackages.toArray(
11499                    new String[changedPackages.size()]), userId, suspended);
11500        }
11501
11502        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11503    }
11504
11505    @Override
11506    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11507        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11508                true /* requireFullPermission */, false /* checkShell */,
11509                "isPackageSuspendedForUser for user " + userId);
11510        synchronized (mPackages) {
11511            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11512            if (pkgSetting == null) {
11513                throw new IllegalArgumentException("Unknown target package: " + packageName);
11514            }
11515            return pkgSetting.getSuspended(userId);
11516        }
11517    }
11518
11519    /**
11520     * TODO: cache and disallow blocking the active dialer.
11521     *
11522     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11523     */
11524    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11525        if (isPackageDeviceAdmin(packageName, userId)) {
11526            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11527                    + "\": has an active device admin");
11528            return false;
11529        }
11530
11531        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11532        if (packageName.equals(activeLauncherPackageName)) {
11533            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11534                    + "\": contains the active launcher");
11535            return false;
11536        }
11537
11538        if (packageName.equals(mRequiredInstallerPackage)) {
11539            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11540                    + "\": required for package installation");
11541            return false;
11542        }
11543
11544        if (packageName.equals(mRequiredVerifierPackage)) {
11545            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11546                    + "\": required for package verification");
11547            return false;
11548        }
11549
11550        final PackageParser.Package pkg = mPackages.get(packageName);
11551        if (pkg != null && isPrivilegedApp(pkg)) {
11552            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11553                    + "\": is a privileged app");
11554            return false;
11555        }
11556
11557        return true;
11558    }
11559
11560    private String getActiveLauncherPackageName(int userId) {
11561        Intent intent = new Intent(Intent.ACTION_MAIN);
11562        intent.addCategory(Intent.CATEGORY_HOME);
11563        ResolveInfo resolveInfo = resolveIntent(
11564                intent,
11565                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11566                PackageManager.MATCH_DEFAULT_ONLY,
11567                userId);
11568
11569        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11570    }
11571
11572    @Override
11573    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11574        mContext.enforceCallingOrSelfPermission(
11575                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11576                "Only package verification agents can verify applications");
11577
11578        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11579        final PackageVerificationResponse response = new PackageVerificationResponse(
11580                verificationCode, Binder.getCallingUid());
11581        msg.arg1 = id;
11582        msg.obj = response;
11583        mHandler.sendMessage(msg);
11584    }
11585
11586    @Override
11587    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11588            long millisecondsToDelay) {
11589        mContext.enforceCallingOrSelfPermission(
11590                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11591                "Only package verification agents can extend verification timeouts");
11592
11593        final PackageVerificationState state = mPendingVerification.get(id);
11594        final PackageVerificationResponse response = new PackageVerificationResponse(
11595                verificationCodeAtTimeout, Binder.getCallingUid());
11596
11597        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11598            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11599        }
11600        if (millisecondsToDelay < 0) {
11601            millisecondsToDelay = 0;
11602        }
11603        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11604                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11605            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11606        }
11607
11608        if ((state != null) && !state.timeoutExtended()) {
11609            state.extendTimeout();
11610
11611            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11612            msg.arg1 = id;
11613            msg.obj = response;
11614            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11615        }
11616    }
11617
11618    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11619            int verificationCode, UserHandle user) {
11620        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11621        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11622        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11623        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11624        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11625
11626        mContext.sendBroadcastAsUser(intent, user,
11627                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11628    }
11629
11630    private ComponentName matchComponentForVerifier(String packageName,
11631            List<ResolveInfo> receivers) {
11632        ActivityInfo targetReceiver = null;
11633
11634        final int NR = receivers.size();
11635        for (int i = 0; i < NR; i++) {
11636            final ResolveInfo info = receivers.get(i);
11637            if (info.activityInfo == null) {
11638                continue;
11639            }
11640
11641            if (packageName.equals(info.activityInfo.packageName)) {
11642                targetReceiver = info.activityInfo;
11643                break;
11644            }
11645        }
11646
11647        if (targetReceiver == null) {
11648            return null;
11649        }
11650
11651        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11652    }
11653
11654    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11655            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11656        if (pkgInfo.verifiers.length == 0) {
11657            return null;
11658        }
11659
11660        final int N = pkgInfo.verifiers.length;
11661        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11662        for (int i = 0; i < N; i++) {
11663            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11664
11665            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11666                    receivers);
11667            if (comp == null) {
11668                continue;
11669            }
11670
11671            final int verifierUid = getUidForVerifier(verifierInfo);
11672            if (verifierUid == -1) {
11673                continue;
11674            }
11675
11676            if (DEBUG_VERIFY) {
11677                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11678                        + " with the correct signature");
11679            }
11680            sufficientVerifiers.add(comp);
11681            verificationState.addSufficientVerifier(verifierUid);
11682        }
11683
11684        return sufficientVerifiers;
11685    }
11686
11687    private int getUidForVerifier(VerifierInfo verifierInfo) {
11688        synchronized (mPackages) {
11689            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11690            if (pkg == null) {
11691                return -1;
11692            } else if (pkg.mSignatures.length != 1) {
11693                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11694                        + " has more than one signature; ignoring");
11695                return -1;
11696            }
11697
11698            /*
11699             * If the public key of the package's signature does not match
11700             * our expected public key, then this is a different package and
11701             * we should skip.
11702             */
11703
11704            final byte[] expectedPublicKey;
11705            try {
11706                final Signature verifierSig = pkg.mSignatures[0];
11707                final PublicKey publicKey = verifierSig.getPublicKey();
11708                expectedPublicKey = publicKey.getEncoded();
11709            } catch (CertificateException e) {
11710                return -1;
11711            }
11712
11713            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11714
11715            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11716                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11717                        + " does not have the expected public key; ignoring");
11718                return -1;
11719            }
11720
11721            return pkg.applicationInfo.uid;
11722        }
11723    }
11724
11725    @Override
11726    public void finishPackageInstall(int token) {
11727        enforceSystemOrRoot("Only the system is allowed to finish installs");
11728
11729        if (DEBUG_INSTALL) {
11730            Slog.v(TAG, "BM finishing package install for " + token);
11731        }
11732        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11733
11734        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11735        mHandler.sendMessage(msg);
11736    }
11737
11738    /**
11739     * Get the verification agent timeout.
11740     *
11741     * @return verification timeout in milliseconds
11742     */
11743    private long getVerificationTimeout() {
11744        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11745                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11746                DEFAULT_VERIFICATION_TIMEOUT);
11747    }
11748
11749    /**
11750     * Get the default verification agent response code.
11751     *
11752     * @return default verification response code
11753     */
11754    private int getDefaultVerificationResponse() {
11755        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11756                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11757                DEFAULT_VERIFICATION_RESPONSE);
11758    }
11759
11760    /**
11761     * Check whether or not package verification has been enabled.
11762     *
11763     * @return true if verification should be performed
11764     */
11765    private boolean isVerificationEnabled(int userId, int installFlags) {
11766        if (!DEFAULT_VERIFY_ENABLE) {
11767            return false;
11768        }
11769        // Ephemeral apps don't get the full verification treatment
11770        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11771            if (DEBUG_EPHEMERAL) {
11772                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11773            }
11774            return false;
11775        }
11776
11777        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11778
11779        // Check if installing from ADB
11780        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11781            // Do not run verification in a test harness environment
11782            if (ActivityManager.isRunningInTestHarness()) {
11783                return false;
11784            }
11785            if (ensureVerifyAppsEnabled) {
11786                return true;
11787            }
11788            // Check if the developer does not want package verification for ADB installs
11789            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11790                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11791                return false;
11792            }
11793        }
11794
11795        if (ensureVerifyAppsEnabled) {
11796            return true;
11797        }
11798
11799        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11800                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11801    }
11802
11803    @Override
11804    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11805            throws RemoteException {
11806        mContext.enforceCallingOrSelfPermission(
11807                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11808                "Only intentfilter verification agents can verify applications");
11809
11810        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11811        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11812                Binder.getCallingUid(), verificationCode, failedDomains);
11813        msg.arg1 = id;
11814        msg.obj = response;
11815        mHandler.sendMessage(msg);
11816    }
11817
11818    @Override
11819    public int getIntentVerificationStatus(String packageName, int userId) {
11820        synchronized (mPackages) {
11821            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11822        }
11823    }
11824
11825    @Override
11826    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11827        mContext.enforceCallingOrSelfPermission(
11828                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11829
11830        boolean result = false;
11831        synchronized (mPackages) {
11832            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11833        }
11834        if (result) {
11835            scheduleWritePackageRestrictionsLocked(userId);
11836        }
11837        return result;
11838    }
11839
11840    @Override
11841    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11842            String packageName) {
11843        synchronized (mPackages) {
11844            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11845        }
11846    }
11847
11848    @Override
11849    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11850        if (TextUtils.isEmpty(packageName)) {
11851            return ParceledListSlice.emptyList();
11852        }
11853        synchronized (mPackages) {
11854            PackageParser.Package pkg = mPackages.get(packageName);
11855            if (pkg == null || pkg.activities == null) {
11856                return ParceledListSlice.emptyList();
11857            }
11858            final int count = pkg.activities.size();
11859            ArrayList<IntentFilter> result = new ArrayList<>();
11860            for (int n=0; n<count; n++) {
11861                PackageParser.Activity activity = pkg.activities.get(n);
11862                if (activity.intents != null && activity.intents.size() > 0) {
11863                    result.addAll(activity.intents);
11864                }
11865            }
11866            return new ParceledListSlice<>(result);
11867        }
11868    }
11869
11870    @Override
11871    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11872        mContext.enforceCallingOrSelfPermission(
11873                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11874
11875        synchronized (mPackages) {
11876            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11877            if (packageName != null) {
11878                result |= updateIntentVerificationStatus(packageName,
11879                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11880                        userId);
11881                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11882                        packageName, userId);
11883            }
11884            return result;
11885        }
11886    }
11887
11888    @Override
11889    public String getDefaultBrowserPackageName(int userId) {
11890        synchronized (mPackages) {
11891            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11892        }
11893    }
11894
11895    /**
11896     * Get the "allow unknown sources" setting.
11897     *
11898     * @return the current "allow unknown sources" setting
11899     */
11900    private int getUnknownSourcesSettings() {
11901        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11902                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11903                -1);
11904    }
11905
11906    @Override
11907    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11908        final int uid = Binder.getCallingUid();
11909        // writer
11910        synchronized (mPackages) {
11911            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11912            if (targetPackageSetting == null) {
11913                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11914            }
11915
11916            PackageSetting installerPackageSetting;
11917            if (installerPackageName != null) {
11918                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11919                if (installerPackageSetting == null) {
11920                    throw new IllegalArgumentException("Unknown installer package: "
11921                            + installerPackageName);
11922                }
11923            } else {
11924                installerPackageSetting = null;
11925            }
11926
11927            Signature[] callerSignature;
11928            Object obj = mSettings.getUserIdLPr(uid);
11929            if (obj != null) {
11930                if (obj instanceof SharedUserSetting) {
11931                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11932                } else if (obj instanceof PackageSetting) {
11933                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11934                } else {
11935                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11936                }
11937            } else {
11938                throw new SecurityException("Unknown calling UID: " + uid);
11939            }
11940
11941            // Verify: can't set installerPackageName to a package that is
11942            // not signed with the same cert as the caller.
11943            if (installerPackageSetting != null) {
11944                if (compareSignatures(callerSignature,
11945                        installerPackageSetting.signatures.mSignatures)
11946                        != PackageManager.SIGNATURE_MATCH) {
11947                    throw new SecurityException(
11948                            "Caller does not have same cert as new installer package "
11949                            + installerPackageName);
11950                }
11951            }
11952
11953            // Verify: if target already has an installer package, it must
11954            // be signed with the same cert as the caller.
11955            if (targetPackageSetting.installerPackageName != null) {
11956                PackageSetting setting = mSettings.mPackages.get(
11957                        targetPackageSetting.installerPackageName);
11958                // If the currently set package isn't valid, then it's always
11959                // okay to change it.
11960                if (setting != null) {
11961                    if (compareSignatures(callerSignature,
11962                            setting.signatures.mSignatures)
11963                            != PackageManager.SIGNATURE_MATCH) {
11964                        throw new SecurityException(
11965                                "Caller does not have same cert as old installer package "
11966                                + targetPackageSetting.installerPackageName);
11967                    }
11968                }
11969            }
11970
11971            // Okay!
11972            targetPackageSetting.installerPackageName = installerPackageName;
11973            if (installerPackageName != null) {
11974                mSettings.mInstallerPackages.add(installerPackageName);
11975            }
11976            scheduleWriteSettingsLocked();
11977        }
11978    }
11979
11980    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11981        // Queue up an async operation since the package installation may take a little while.
11982        mHandler.post(new Runnable() {
11983            public void run() {
11984                mHandler.removeCallbacks(this);
11985                 // Result object to be returned
11986                PackageInstalledInfo res = new PackageInstalledInfo();
11987                res.setReturnCode(currentStatus);
11988                res.uid = -1;
11989                res.pkg = null;
11990                res.removedInfo = null;
11991                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11992                    args.doPreInstall(res.returnCode);
11993                    synchronized (mInstallLock) {
11994                        installPackageTracedLI(args, res);
11995                    }
11996                    args.doPostInstall(res.returnCode, res.uid);
11997                }
11998
11999                // A restore should be performed at this point if (a) the install
12000                // succeeded, (b) the operation is not an update, and (c) the new
12001                // package has not opted out of backup participation.
12002                final boolean update = res.removedInfo != null
12003                        && res.removedInfo.removedPackage != null;
12004                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12005                boolean doRestore = !update
12006                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12007
12008                // Set up the post-install work request bookkeeping.  This will be used
12009                // and cleaned up by the post-install event handling regardless of whether
12010                // there's a restore pass performed.  Token values are >= 1.
12011                int token;
12012                if (mNextInstallToken < 0) mNextInstallToken = 1;
12013                token = mNextInstallToken++;
12014
12015                PostInstallData data = new PostInstallData(args, res);
12016                mRunningInstalls.put(token, data);
12017                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12018
12019                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12020                    // Pass responsibility to the Backup Manager.  It will perform a
12021                    // restore if appropriate, then pass responsibility back to the
12022                    // Package Manager to run the post-install observer callbacks
12023                    // and broadcasts.
12024                    IBackupManager bm = IBackupManager.Stub.asInterface(
12025                            ServiceManager.getService(Context.BACKUP_SERVICE));
12026                    if (bm != null) {
12027                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12028                                + " to BM for possible restore");
12029                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12030                        try {
12031                            // TODO: http://b/22388012
12032                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12033                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12034                            } else {
12035                                doRestore = false;
12036                            }
12037                        } catch (RemoteException e) {
12038                            // can't happen; the backup manager is local
12039                        } catch (Exception e) {
12040                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12041                            doRestore = false;
12042                        }
12043                    } else {
12044                        Slog.e(TAG, "Backup Manager not found!");
12045                        doRestore = false;
12046                    }
12047                }
12048
12049                if (!doRestore) {
12050                    // No restore possible, or the Backup Manager was mysteriously not
12051                    // available -- just fire the post-install work request directly.
12052                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12053
12054                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12055
12056                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12057                    mHandler.sendMessage(msg);
12058                }
12059            }
12060        });
12061    }
12062
12063    private abstract class HandlerParams {
12064        private static final int MAX_RETRIES = 4;
12065
12066        /**
12067         * Number of times startCopy() has been attempted and had a non-fatal
12068         * error.
12069         */
12070        private int mRetries = 0;
12071
12072        /** User handle for the user requesting the information or installation. */
12073        private final UserHandle mUser;
12074        String traceMethod;
12075        int traceCookie;
12076
12077        HandlerParams(UserHandle user) {
12078            mUser = user;
12079        }
12080
12081        UserHandle getUser() {
12082            return mUser;
12083        }
12084
12085        HandlerParams setTraceMethod(String traceMethod) {
12086            this.traceMethod = traceMethod;
12087            return this;
12088        }
12089
12090        HandlerParams setTraceCookie(int traceCookie) {
12091            this.traceCookie = traceCookie;
12092            return this;
12093        }
12094
12095        final boolean startCopy() {
12096            boolean res;
12097            try {
12098                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12099
12100                if (++mRetries > MAX_RETRIES) {
12101                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12102                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12103                    handleServiceError();
12104                    return false;
12105                } else {
12106                    handleStartCopy();
12107                    res = true;
12108                }
12109            } catch (RemoteException e) {
12110                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12111                mHandler.sendEmptyMessage(MCS_RECONNECT);
12112                res = false;
12113            }
12114            handleReturnCode();
12115            return res;
12116        }
12117
12118        final void serviceError() {
12119            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12120            handleServiceError();
12121            handleReturnCode();
12122        }
12123
12124        abstract void handleStartCopy() throws RemoteException;
12125        abstract void handleServiceError();
12126        abstract void handleReturnCode();
12127    }
12128
12129    class MeasureParams extends HandlerParams {
12130        private final PackageStats mStats;
12131        private boolean mSuccess;
12132
12133        private final IPackageStatsObserver mObserver;
12134
12135        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12136            super(new UserHandle(stats.userHandle));
12137            mObserver = observer;
12138            mStats = stats;
12139        }
12140
12141        @Override
12142        public String toString() {
12143            return "MeasureParams{"
12144                + Integer.toHexString(System.identityHashCode(this))
12145                + " " + mStats.packageName + "}";
12146        }
12147
12148        @Override
12149        void handleStartCopy() throws RemoteException {
12150            synchronized (mInstallLock) {
12151                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12152            }
12153
12154            if (mSuccess) {
12155                final boolean mounted;
12156                if (Environment.isExternalStorageEmulated()) {
12157                    mounted = true;
12158                } else {
12159                    final String status = Environment.getExternalStorageState();
12160                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12161                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12162                }
12163
12164                if (mounted) {
12165                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12166
12167                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12168                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12169
12170                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12171                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12172
12173                    // Always subtract cache size, since it's a subdirectory
12174                    mStats.externalDataSize -= mStats.externalCacheSize;
12175
12176                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12177                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12178
12179                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12180                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12181                }
12182            }
12183        }
12184
12185        @Override
12186        void handleReturnCode() {
12187            if (mObserver != null) {
12188                try {
12189                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12190                } catch (RemoteException e) {
12191                    Slog.i(TAG, "Observer no longer exists.");
12192                }
12193            }
12194        }
12195
12196        @Override
12197        void handleServiceError() {
12198            Slog.e(TAG, "Could not measure application " + mStats.packageName
12199                            + " external storage");
12200        }
12201    }
12202
12203    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12204            throws RemoteException {
12205        long result = 0;
12206        for (File path : paths) {
12207            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12208        }
12209        return result;
12210    }
12211
12212    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12213        for (File path : paths) {
12214            try {
12215                mcs.clearDirectory(path.getAbsolutePath());
12216            } catch (RemoteException e) {
12217            }
12218        }
12219    }
12220
12221    static class OriginInfo {
12222        /**
12223         * Location where install is coming from, before it has been
12224         * copied/renamed into place. This could be a single monolithic APK
12225         * file, or a cluster directory. This location may be untrusted.
12226         */
12227        final File file;
12228        final String cid;
12229
12230        /**
12231         * Flag indicating that {@link #file} or {@link #cid} has already been
12232         * staged, meaning downstream users don't need to defensively copy the
12233         * contents.
12234         */
12235        final boolean staged;
12236
12237        /**
12238         * Flag indicating that {@link #file} or {@link #cid} is an already
12239         * installed app that is being moved.
12240         */
12241        final boolean existing;
12242
12243        final String resolvedPath;
12244        final File resolvedFile;
12245
12246        static OriginInfo fromNothing() {
12247            return new OriginInfo(null, null, false, false);
12248        }
12249
12250        static OriginInfo fromUntrustedFile(File file) {
12251            return new OriginInfo(file, null, false, false);
12252        }
12253
12254        static OriginInfo fromExistingFile(File file) {
12255            return new OriginInfo(file, null, false, true);
12256        }
12257
12258        static OriginInfo fromStagedFile(File file) {
12259            return new OriginInfo(file, null, true, false);
12260        }
12261
12262        static OriginInfo fromStagedContainer(String cid) {
12263            return new OriginInfo(null, cid, true, false);
12264        }
12265
12266        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12267            this.file = file;
12268            this.cid = cid;
12269            this.staged = staged;
12270            this.existing = existing;
12271
12272            if (cid != null) {
12273                resolvedPath = PackageHelper.getSdDir(cid);
12274                resolvedFile = new File(resolvedPath);
12275            } else if (file != null) {
12276                resolvedPath = file.getAbsolutePath();
12277                resolvedFile = file;
12278            } else {
12279                resolvedPath = null;
12280                resolvedFile = null;
12281            }
12282        }
12283    }
12284
12285    static class MoveInfo {
12286        final int moveId;
12287        final String fromUuid;
12288        final String toUuid;
12289        final String packageName;
12290        final String dataAppName;
12291        final int appId;
12292        final String seinfo;
12293        final int targetSdkVersion;
12294
12295        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12296                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12297            this.moveId = moveId;
12298            this.fromUuid = fromUuid;
12299            this.toUuid = toUuid;
12300            this.packageName = packageName;
12301            this.dataAppName = dataAppName;
12302            this.appId = appId;
12303            this.seinfo = seinfo;
12304            this.targetSdkVersion = targetSdkVersion;
12305        }
12306    }
12307
12308    static class VerificationInfo {
12309        /** A constant used to indicate that a uid value is not present. */
12310        public static final int NO_UID = -1;
12311
12312        /** URI referencing where the package was downloaded from. */
12313        final Uri originatingUri;
12314
12315        /** HTTP referrer URI associated with the originatingURI. */
12316        final Uri referrer;
12317
12318        /** UID of the application that the install request originated from. */
12319        final int originatingUid;
12320
12321        /** UID of application requesting the install */
12322        final int installerUid;
12323
12324        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12325            this.originatingUri = originatingUri;
12326            this.referrer = referrer;
12327            this.originatingUid = originatingUid;
12328            this.installerUid = installerUid;
12329        }
12330    }
12331
12332    class InstallParams extends HandlerParams {
12333        final OriginInfo origin;
12334        final MoveInfo move;
12335        final IPackageInstallObserver2 observer;
12336        int installFlags;
12337        final String installerPackageName;
12338        final String volumeUuid;
12339        private InstallArgs mArgs;
12340        private int mRet;
12341        final String packageAbiOverride;
12342        final String[] grantedRuntimePermissions;
12343        final VerificationInfo verificationInfo;
12344        final Certificate[][] certificates;
12345
12346        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12347                int installFlags, String installerPackageName, String volumeUuid,
12348                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12349                String[] grantedPermissions, Certificate[][] certificates) {
12350            super(user);
12351            this.origin = origin;
12352            this.move = move;
12353            this.observer = observer;
12354            this.installFlags = installFlags;
12355            this.installerPackageName = installerPackageName;
12356            this.volumeUuid = volumeUuid;
12357            this.verificationInfo = verificationInfo;
12358            this.packageAbiOverride = packageAbiOverride;
12359            this.grantedRuntimePermissions = grantedPermissions;
12360            this.certificates = certificates;
12361        }
12362
12363        @Override
12364        public String toString() {
12365            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12366                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12367        }
12368
12369        private int installLocationPolicy(PackageInfoLite pkgLite) {
12370            String packageName = pkgLite.packageName;
12371            int installLocation = pkgLite.installLocation;
12372            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12373            // reader
12374            synchronized (mPackages) {
12375                // Currently installed package which the new package is attempting to replace or
12376                // null if no such package is installed.
12377                PackageParser.Package installedPkg = mPackages.get(packageName);
12378                // Package which currently owns the data which the new package will own if installed.
12379                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12380                // will be null whereas dataOwnerPkg will contain information about the package
12381                // which was uninstalled while keeping its data.
12382                PackageParser.Package dataOwnerPkg = installedPkg;
12383                if (dataOwnerPkg  == null) {
12384                    PackageSetting ps = mSettings.mPackages.get(packageName);
12385                    if (ps != null) {
12386                        dataOwnerPkg = ps.pkg;
12387                    }
12388                }
12389
12390                if (dataOwnerPkg != null) {
12391                    // If installed, the package will get access to data left on the device by its
12392                    // predecessor. As a security measure, this is permited only if this is not a
12393                    // version downgrade or if the predecessor package is marked as debuggable and
12394                    // a downgrade is explicitly requested.
12395                    //
12396                    // On debuggable platform builds, downgrades are permitted even for
12397                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12398                    // not offer security guarantees and thus it's OK to disable some security
12399                    // mechanisms to make debugging/testing easier on those builds. However, even on
12400                    // debuggable builds downgrades of packages are permitted only if requested via
12401                    // installFlags. This is because we aim to keep the behavior of debuggable
12402                    // platform builds as close as possible to the behavior of non-debuggable
12403                    // platform builds.
12404                    final boolean downgradeRequested =
12405                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12406                    final boolean packageDebuggable =
12407                                (dataOwnerPkg.applicationInfo.flags
12408                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12409                    final boolean downgradePermitted =
12410                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12411                    if (!downgradePermitted) {
12412                        try {
12413                            checkDowngrade(dataOwnerPkg, pkgLite);
12414                        } catch (PackageManagerException e) {
12415                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12416                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12417                        }
12418                    }
12419                }
12420
12421                if (installedPkg != null) {
12422                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12423                        // Check for updated system application.
12424                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12425                            if (onSd) {
12426                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12427                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12428                            }
12429                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12430                        } else {
12431                            if (onSd) {
12432                                // Install flag overrides everything.
12433                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12434                            }
12435                            // If current upgrade specifies particular preference
12436                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12437                                // Application explicitly specified internal.
12438                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12439                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12440                                // App explictly prefers external. Let policy decide
12441                            } else {
12442                                // Prefer previous location
12443                                if (isExternal(installedPkg)) {
12444                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12445                                }
12446                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12447                            }
12448                        }
12449                    } else {
12450                        // Invalid install. Return error code
12451                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12452                    }
12453                }
12454            }
12455            // All the special cases have been taken care of.
12456            // Return result based on recommended install location.
12457            if (onSd) {
12458                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12459            }
12460            return pkgLite.recommendedInstallLocation;
12461        }
12462
12463        /*
12464         * Invoke remote method to get package information and install
12465         * location values. Override install location based on default
12466         * policy if needed and then create install arguments based
12467         * on the install location.
12468         */
12469        public void handleStartCopy() throws RemoteException {
12470            int ret = PackageManager.INSTALL_SUCCEEDED;
12471
12472            // If we're already staged, we've firmly committed to an install location
12473            if (origin.staged) {
12474                if (origin.file != null) {
12475                    installFlags |= PackageManager.INSTALL_INTERNAL;
12476                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12477                } else if (origin.cid != null) {
12478                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12479                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12480                } else {
12481                    throw new IllegalStateException("Invalid stage location");
12482                }
12483            }
12484
12485            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12486            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12487            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12488            PackageInfoLite pkgLite = null;
12489
12490            if (onInt && onSd) {
12491                // Check if both bits are set.
12492                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12493                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12494            } else if (onSd && ephemeral) {
12495                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12496                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12497            } else {
12498                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12499                        packageAbiOverride);
12500
12501                if (DEBUG_EPHEMERAL && ephemeral) {
12502                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12503                }
12504
12505                /*
12506                 * If we have too little free space, try to free cache
12507                 * before giving up.
12508                 */
12509                if (!origin.staged && pkgLite.recommendedInstallLocation
12510                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12511                    // TODO: focus freeing disk space on the target device
12512                    final StorageManager storage = StorageManager.from(mContext);
12513                    final long lowThreshold = storage.getStorageLowBytes(
12514                            Environment.getDataDirectory());
12515
12516                    final long sizeBytes = mContainerService.calculateInstalledSize(
12517                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12518
12519                    try {
12520                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12521                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12522                                installFlags, packageAbiOverride);
12523                    } catch (InstallerException e) {
12524                        Slog.w(TAG, "Failed to free cache", e);
12525                    }
12526
12527                    /*
12528                     * The cache free must have deleted the file we
12529                     * downloaded to install.
12530                     *
12531                     * TODO: fix the "freeCache" call to not delete
12532                     *       the file we care about.
12533                     */
12534                    if (pkgLite.recommendedInstallLocation
12535                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12536                        pkgLite.recommendedInstallLocation
12537                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12538                    }
12539                }
12540            }
12541
12542            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12543                int loc = pkgLite.recommendedInstallLocation;
12544                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12545                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12546                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12547                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12548                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12549                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12550                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12551                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12552                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12553                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12554                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12555                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12556                } else {
12557                    // Override with defaults if needed.
12558                    loc = installLocationPolicy(pkgLite);
12559                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12560                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12561                    } else if (!onSd && !onInt) {
12562                        // Override install location with flags
12563                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12564                            // Set the flag to install on external media.
12565                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12566                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12567                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12568                            if (DEBUG_EPHEMERAL) {
12569                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12570                            }
12571                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12572                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12573                                    |PackageManager.INSTALL_INTERNAL);
12574                        } else {
12575                            // Make sure the flag for installing on external
12576                            // media is unset
12577                            installFlags |= PackageManager.INSTALL_INTERNAL;
12578                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12579                        }
12580                    }
12581                }
12582            }
12583
12584            final InstallArgs args = createInstallArgs(this);
12585            mArgs = args;
12586
12587            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12588                // TODO: http://b/22976637
12589                // Apps installed for "all" users use the device owner to verify the app
12590                UserHandle verifierUser = getUser();
12591                if (verifierUser == UserHandle.ALL) {
12592                    verifierUser = UserHandle.SYSTEM;
12593                }
12594
12595                /*
12596                 * Determine if we have any installed package verifiers. If we
12597                 * do, then we'll defer to them to verify the packages.
12598                 */
12599                final int requiredUid = mRequiredVerifierPackage == null ? -1
12600                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12601                                verifierUser.getIdentifier());
12602                if (!origin.existing && requiredUid != -1
12603                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12604                    final Intent verification = new Intent(
12605                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12606                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12607                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12608                            PACKAGE_MIME_TYPE);
12609                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12610
12611                    // Query all live verifiers based on current user state
12612                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12613                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12614
12615                    if (DEBUG_VERIFY) {
12616                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12617                                + verification.toString() + " with " + pkgLite.verifiers.length
12618                                + " optional verifiers");
12619                    }
12620
12621                    final int verificationId = mPendingVerificationToken++;
12622
12623                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12624
12625                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12626                            installerPackageName);
12627
12628                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12629                            installFlags);
12630
12631                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12632                            pkgLite.packageName);
12633
12634                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12635                            pkgLite.versionCode);
12636
12637                    if (verificationInfo != null) {
12638                        if (verificationInfo.originatingUri != null) {
12639                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12640                                    verificationInfo.originatingUri);
12641                        }
12642                        if (verificationInfo.referrer != null) {
12643                            verification.putExtra(Intent.EXTRA_REFERRER,
12644                                    verificationInfo.referrer);
12645                        }
12646                        if (verificationInfo.originatingUid >= 0) {
12647                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12648                                    verificationInfo.originatingUid);
12649                        }
12650                        if (verificationInfo.installerUid >= 0) {
12651                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12652                                    verificationInfo.installerUid);
12653                        }
12654                    }
12655
12656                    final PackageVerificationState verificationState = new PackageVerificationState(
12657                            requiredUid, args);
12658
12659                    mPendingVerification.append(verificationId, verificationState);
12660
12661                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12662                            receivers, verificationState);
12663
12664                    /*
12665                     * If any sufficient verifiers were listed in the package
12666                     * manifest, attempt to ask them.
12667                     */
12668                    if (sufficientVerifiers != null) {
12669                        final int N = sufficientVerifiers.size();
12670                        if (N == 0) {
12671                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12672                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12673                        } else {
12674                            for (int i = 0; i < N; i++) {
12675                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12676
12677                                final Intent sufficientIntent = new Intent(verification);
12678                                sufficientIntent.setComponent(verifierComponent);
12679                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12680                            }
12681                        }
12682                    }
12683
12684                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12685                            mRequiredVerifierPackage, receivers);
12686                    if (ret == PackageManager.INSTALL_SUCCEEDED
12687                            && mRequiredVerifierPackage != null) {
12688                        Trace.asyncTraceBegin(
12689                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12690                        /*
12691                         * Send the intent to the required verification agent,
12692                         * but only start the verification timeout after the
12693                         * target BroadcastReceivers have run.
12694                         */
12695                        verification.setComponent(requiredVerifierComponent);
12696                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12697                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12698                                new BroadcastReceiver() {
12699                                    @Override
12700                                    public void onReceive(Context context, Intent intent) {
12701                                        final Message msg = mHandler
12702                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12703                                        msg.arg1 = verificationId;
12704                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12705                                    }
12706                                }, null, 0, null, null);
12707
12708                        /*
12709                         * We don't want the copy to proceed until verification
12710                         * succeeds, so null out this field.
12711                         */
12712                        mArgs = null;
12713                    }
12714                } else {
12715                    /*
12716                     * No package verification is enabled, so immediately start
12717                     * the remote call to initiate copy using temporary file.
12718                     */
12719                    ret = args.copyApk(mContainerService, true);
12720                }
12721            }
12722
12723            mRet = ret;
12724        }
12725
12726        @Override
12727        void handleReturnCode() {
12728            // If mArgs is null, then MCS couldn't be reached. When it
12729            // reconnects, it will try again to install. At that point, this
12730            // will succeed.
12731            if (mArgs != null) {
12732                processPendingInstall(mArgs, mRet);
12733            }
12734        }
12735
12736        @Override
12737        void handleServiceError() {
12738            mArgs = createInstallArgs(this);
12739            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12740        }
12741
12742        public boolean isForwardLocked() {
12743            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12744        }
12745    }
12746
12747    /**
12748     * Used during creation of InstallArgs
12749     *
12750     * @param installFlags package installation flags
12751     * @return true if should be installed on external storage
12752     */
12753    private static boolean installOnExternalAsec(int installFlags) {
12754        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12755            return false;
12756        }
12757        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12758            return true;
12759        }
12760        return false;
12761    }
12762
12763    /**
12764     * Used during creation of InstallArgs
12765     *
12766     * @param installFlags package installation flags
12767     * @return true if should be installed as forward locked
12768     */
12769    private static boolean installForwardLocked(int installFlags) {
12770        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12771    }
12772
12773    private InstallArgs createInstallArgs(InstallParams params) {
12774        if (params.move != null) {
12775            return new MoveInstallArgs(params);
12776        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12777            return new AsecInstallArgs(params);
12778        } else {
12779            return new FileInstallArgs(params);
12780        }
12781    }
12782
12783    /**
12784     * Create args that describe an existing installed package. Typically used
12785     * when cleaning up old installs, or used as a move source.
12786     */
12787    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12788            String resourcePath, String[] instructionSets) {
12789        final boolean isInAsec;
12790        if (installOnExternalAsec(installFlags)) {
12791            /* Apps on SD card are always in ASEC containers. */
12792            isInAsec = true;
12793        } else if (installForwardLocked(installFlags)
12794                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12795            /*
12796             * Forward-locked apps are only in ASEC containers if they're the
12797             * new style
12798             */
12799            isInAsec = true;
12800        } else {
12801            isInAsec = false;
12802        }
12803
12804        if (isInAsec) {
12805            return new AsecInstallArgs(codePath, instructionSets,
12806                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12807        } else {
12808            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12809        }
12810    }
12811
12812    static abstract class InstallArgs {
12813        /** @see InstallParams#origin */
12814        final OriginInfo origin;
12815        /** @see InstallParams#move */
12816        final MoveInfo move;
12817
12818        final IPackageInstallObserver2 observer;
12819        // Always refers to PackageManager flags only
12820        final int installFlags;
12821        final String installerPackageName;
12822        final String volumeUuid;
12823        final UserHandle user;
12824        final String abiOverride;
12825        final String[] installGrantPermissions;
12826        /** If non-null, drop an async trace when the install completes */
12827        final String traceMethod;
12828        final int traceCookie;
12829        final Certificate[][] certificates;
12830
12831        // The list of instruction sets supported by this app. This is currently
12832        // only used during the rmdex() phase to clean up resources. We can get rid of this
12833        // if we move dex files under the common app path.
12834        /* nullable */ String[] instructionSets;
12835
12836        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12837                int installFlags, String installerPackageName, String volumeUuid,
12838                UserHandle user, String[] instructionSets,
12839                String abiOverride, String[] installGrantPermissions,
12840                String traceMethod, int traceCookie, Certificate[][] certificates) {
12841            this.origin = origin;
12842            this.move = move;
12843            this.installFlags = installFlags;
12844            this.observer = observer;
12845            this.installerPackageName = installerPackageName;
12846            this.volumeUuid = volumeUuid;
12847            this.user = user;
12848            this.instructionSets = instructionSets;
12849            this.abiOverride = abiOverride;
12850            this.installGrantPermissions = installGrantPermissions;
12851            this.traceMethod = traceMethod;
12852            this.traceCookie = traceCookie;
12853            this.certificates = certificates;
12854        }
12855
12856        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12857        abstract int doPreInstall(int status);
12858
12859        /**
12860         * Rename package into final resting place. All paths on the given
12861         * scanned package should be updated to reflect the rename.
12862         */
12863        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12864        abstract int doPostInstall(int status, int uid);
12865
12866        /** @see PackageSettingBase#codePathString */
12867        abstract String getCodePath();
12868        /** @see PackageSettingBase#resourcePathString */
12869        abstract String getResourcePath();
12870
12871        // Need installer lock especially for dex file removal.
12872        abstract void cleanUpResourcesLI();
12873        abstract boolean doPostDeleteLI(boolean delete);
12874
12875        /**
12876         * Called before the source arguments are copied. This is used mostly
12877         * for MoveParams when it needs to read the source file to put it in the
12878         * destination.
12879         */
12880        int doPreCopy() {
12881            return PackageManager.INSTALL_SUCCEEDED;
12882        }
12883
12884        /**
12885         * Called after the source arguments are copied. This is used mostly for
12886         * MoveParams when it needs to read the source file to put it in the
12887         * destination.
12888         */
12889        int doPostCopy(int uid) {
12890            return PackageManager.INSTALL_SUCCEEDED;
12891        }
12892
12893        protected boolean isFwdLocked() {
12894            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12895        }
12896
12897        protected boolean isExternalAsec() {
12898            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12899        }
12900
12901        protected boolean isEphemeral() {
12902            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12903        }
12904
12905        UserHandle getUser() {
12906            return user;
12907        }
12908    }
12909
12910    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12911        if (!allCodePaths.isEmpty()) {
12912            if (instructionSets == null) {
12913                throw new IllegalStateException("instructionSet == null");
12914            }
12915            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12916            for (String codePath : allCodePaths) {
12917                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12918                    try {
12919                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12920                    } catch (InstallerException ignored) {
12921                    }
12922                }
12923            }
12924        }
12925    }
12926
12927    /**
12928     * Logic to handle installation of non-ASEC applications, including copying
12929     * and renaming logic.
12930     */
12931    class FileInstallArgs extends InstallArgs {
12932        private File codeFile;
12933        private File resourceFile;
12934
12935        // Example topology:
12936        // /data/app/com.example/base.apk
12937        // /data/app/com.example/split_foo.apk
12938        // /data/app/com.example/lib/arm/libfoo.so
12939        // /data/app/com.example/lib/arm64/libfoo.so
12940        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12941
12942        /** New install */
12943        FileInstallArgs(InstallParams params) {
12944            super(params.origin, params.move, params.observer, params.installFlags,
12945                    params.installerPackageName, params.volumeUuid,
12946                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12947                    params.grantedRuntimePermissions,
12948                    params.traceMethod, params.traceCookie, params.certificates);
12949            if (isFwdLocked()) {
12950                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12951            }
12952        }
12953
12954        /** Existing install */
12955        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12956            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12957                    null, null, null, 0, null /*certificates*/);
12958            this.codeFile = (codePath != null) ? new File(codePath) : null;
12959            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12960        }
12961
12962        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12963            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12964            try {
12965                return doCopyApk(imcs, temp);
12966            } finally {
12967                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12968            }
12969        }
12970
12971        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12972            if (origin.staged) {
12973                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12974                codeFile = origin.file;
12975                resourceFile = origin.file;
12976                return PackageManager.INSTALL_SUCCEEDED;
12977            }
12978
12979            try {
12980                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12981                final File tempDir =
12982                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12983                codeFile = tempDir;
12984                resourceFile = tempDir;
12985            } catch (IOException e) {
12986                Slog.w(TAG, "Failed to create copy file: " + e);
12987                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12988            }
12989
12990            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12991                @Override
12992                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12993                    if (!FileUtils.isValidExtFilename(name)) {
12994                        throw new IllegalArgumentException("Invalid filename: " + name);
12995                    }
12996                    try {
12997                        final File file = new File(codeFile, name);
12998                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12999                                O_RDWR | O_CREAT, 0644);
13000                        Os.chmod(file.getAbsolutePath(), 0644);
13001                        return new ParcelFileDescriptor(fd);
13002                    } catch (ErrnoException e) {
13003                        throw new RemoteException("Failed to open: " + e.getMessage());
13004                    }
13005                }
13006            };
13007
13008            int ret = PackageManager.INSTALL_SUCCEEDED;
13009            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13010            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13011                Slog.e(TAG, "Failed to copy package");
13012                return ret;
13013            }
13014
13015            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13016            NativeLibraryHelper.Handle handle = null;
13017            try {
13018                handle = NativeLibraryHelper.Handle.create(codeFile);
13019                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13020                        abiOverride);
13021            } catch (IOException e) {
13022                Slog.e(TAG, "Copying native libraries failed", e);
13023                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13024            } finally {
13025                IoUtils.closeQuietly(handle);
13026            }
13027
13028            return ret;
13029        }
13030
13031        int doPreInstall(int status) {
13032            if (status != PackageManager.INSTALL_SUCCEEDED) {
13033                cleanUp();
13034            }
13035            return status;
13036        }
13037
13038        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13039            if (status != PackageManager.INSTALL_SUCCEEDED) {
13040                cleanUp();
13041                return false;
13042            }
13043
13044            final File targetDir = codeFile.getParentFile();
13045            final File beforeCodeFile = codeFile;
13046            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13047
13048            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13049            try {
13050                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13051            } catch (ErrnoException e) {
13052                Slog.w(TAG, "Failed to rename", e);
13053                return false;
13054            }
13055
13056            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13057                Slog.w(TAG, "Failed to restorecon");
13058                return false;
13059            }
13060
13061            // Reflect the rename internally
13062            codeFile = afterCodeFile;
13063            resourceFile = afterCodeFile;
13064
13065            // Reflect the rename in scanned details
13066            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13067            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13068                    afterCodeFile, pkg.baseCodePath));
13069            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13070                    afterCodeFile, pkg.splitCodePaths));
13071
13072            // Reflect the rename in app info
13073            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13074            pkg.setApplicationInfoCodePath(pkg.codePath);
13075            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13076            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13077            pkg.setApplicationInfoResourcePath(pkg.codePath);
13078            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13079            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13080
13081            return true;
13082        }
13083
13084        int doPostInstall(int status, int uid) {
13085            if (status != PackageManager.INSTALL_SUCCEEDED) {
13086                cleanUp();
13087            }
13088            return status;
13089        }
13090
13091        @Override
13092        String getCodePath() {
13093            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13094        }
13095
13096        @Override
13097        String getResourcePath() {
13098            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13099        }
13100
13101        private boolean cleanUp() {
13102            if (codeFile == null || !codeFile.exists()) {
13103                return false;
13104            }
13105
13106            removeCodePathLI(codeFile);
13107
13108            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13109                resourceFile.delete();
13110            }
13111
13112            return true;
13113        }
13114
13115        void cleanUpResourcesLI() {
13116            // Try enumerating all code paths before deleting
13117            List<String> allCodePaths = Collections.EMPTY_LIST;
13118            if (codeFile != null && codeFile.exists()) {
13119                try {
13120                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13121                    allCodePaths = pkg.getAllCodePaths();
13122                } catch (PackageParserException e) {
13123                    // Ignored; we tried our best
13124                }
13125            }
13126
13127            cleanUp();
13128            removeDexFiles(allCodePaths, instructionSets);
13129        }
13130
13131        boolean doPostDeleteLI(boolean delete) {
13132            // XXX err, shouldn't we respect the delete flag?
13133            cleanUpResourcesLI();
13134            return true;
13135        }
13136    }
13137
13138    private boolean isAsecExternal(String cid) {
13139        final String asecPath = PackageHelper.getSdFilesystem(cid);
13140        return !asecPath.startsWith(mAsecInternalPath);
13141    }
13142
13143    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13144            PackageManagerException {
13145        if (copyRet < 0) {
13146            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13147                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13148                throw new PackageManagerException(copyRet, message);
13149            }
13150        }
13151    }
13152
13153    /**
13154     * Extract the MountService "container ID" from the full code path of an
13155     * .apk.
13156     */
13157    static String cidFromCodePath(String fullCodePath) {
13158        int eidx = fullCodePath.lastIndexOf("/");
13159        String subStr1 = fullCodePath.substring(0, eidx);
13160        int sidx = subStr1.lastIndexOf("/");
13161        return subStr1.substring(sidx+1, eidx);
13162    }
13163
13164    /**
13165     * Logic to handle installation of ASEC applications, including copying and
13166     * renaming logic.
13167     */
13168    class AsecInstallArgs extends InstallArgs {
13169        static final String RES_FILE_NAME = "pkg.apk";
13170        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13171
13172        String cid;
13173        String packagePath;
13174        String resourcePath;
13175
13176        /** New install */
13177        AsecInstallArgs(InstallParams params) {
13178            super(params.origin, params.move, params.observer, params.installFlags,
13179                    params.installerPackageName, params.volumeUuid,
13180                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13181                    params.grantedRuntimePermissions,
13182                    params.traceMethod, params.traceCookie, params.certificates);
13183        }
13184
13185        /** Existing install */
13186        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13187                        boolean isExternal, boolean isForwardLocked) {
13188            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13189              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13190                    instructionSets, null, null, null, 0, null /*certificates*/);
13191            // Hackily pretend we're still looking at a full code path
13192            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13193                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13194            }
13195
13196            // Extract cid from fullCodePath
13197            int eidx = fullCodePath.lastIndexOf("/");
13198            String subStr1 = fullCodePath.substring(0, eidx);
13199            int sidx = subStr1.lastIndexOf("/");
13200            cid = subStr1.substring(sidx+1, eidx);
13201            setMountPath(subStr1);
13202        }
13203
13204        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13205            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13206              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13207                    instructionSets, null, null, null, 0, null /*certificates*/);
13208            this.cid = cid;
13209            setMountPath(PackageHelper.getSdDir(cid));
13210        }
13211
13212        void createCopyFile() {
13213            cid = mInstallerService.allocateExternalStageCidLegacy();
13214        }
13215
13216        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13217            if (origin.staged && origin.cid != null) {
13218                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13219                cid = origin.cid;
13220                setMountPath(PackageHelper.getSdDir(cid));
13221                return PackageManager.INSTALL_SUCCEEDED;
13222            }
13223
13224            if (temp) {
13225                createCopyFile();
13226            } else {
13227                /*
13228                 * Pre-emptively destroy the container since it's destroyed if
13229                 * copying fails due to it existing anyway.
13230                 */
13231                PackageHelper.destroySdDir(cid);
13232            }
13233
13234            final String newMountPath = imcs.copyPackageToContainer(
13235                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13236                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13237
13238            if (newMountPath != null) {
13239                setMountPath(newMountPath);
13240                return PackageManager.INSTALL_SUCCEEDED;
13241            } else {
13242                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13243            }
13244        }
13245
13246        @Override
13247        String getCodePath() {
13248            return packagePath;
13249        }
13250
13251        @Override
13252        String getResourcePath() {
13253            return resourcePath;
13254        }
13255
13256        int doPreInstall(int status) {
13257            if (status != PackageManager.INSTALL_SUCCEEDED) {
13258                // Destroy container
13259                PackageHelper.destroySdDir(cid);
13260            } else {
13261                boolean mounted = PackageHelper.isContainerMounted(cid);
13262                if (!mounted) {
13263                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13264                            Process.SYSTEM_UID);
13265                    if (newMountPath != null) {
13266                        setMountPath(newMountPath);
13267                    } else {
13268                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13269                    }
13270                }
13271            }
13272            return status;
13273        }
13274
13275        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13276            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13277            String newMountPath = null;
13278            if (PackageHelper.isContainerMounted(cid)) {
13279                // Unmount the container
13280                if (!PackageHelper.unMountSdDir(cid)) {
13281                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13282                    return false;
13283                }
13284            }
13285            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13286                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13287                        " which might be stale. Will try to clean up.");
13288                // Clean up the stale container and proceed to recreate.
13289                if (!PackageHelper.destroySdDir(newCacheId)) {
13290                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13291                    return false;
13292                }
13293                // Successfully cleaned up stale container. Try to rename again.
13294                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13295                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13296                            + " inspite of cleaning it up.");
13297                    return false;
13298                }
13299            }
13300            if (!PackageHelper.isContainerMounted(newCacheId)) {
13301                Slog.w(TAG, "Mounting container " + newCacheId);
13302                newMountPath = PackageHelper.mountSdDir(newCacheId,
13303                        getEncryptKey(), Process.SYSTEM_UID);
13304            } else {
13305                newMountPath = PackageHelper.getSdDir(newCacheId);
13306            }
13307            if (newMountPath == null) {
13308                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13309                return false;
13310            }
13311            Log.i(TAG, "Succesfully renamed " + cid +
13312                    " to " + newCacheId +
13313                    " at new path: " + newMountPath);
13314            cid = newCacheId;
13315
13316            final File beforeCodeFile = new File(packagePath);
13317            setMountPath(newMountPath);
13318            final File afterCodeFile = new File(packagePath);
13319
13320            // Reflect the rename in scanned details
13321            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13322            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13323                    afterCodeFile, pkg.baseCodePath));
13324            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13325                    afterCodeFile, pkg.splitCodePaths));
13326
13327            // Reflect the rename in app info
13328            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13329            pkg.setApplicationInfoCodePath(pkg.codePath);
13330            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13331            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13332            pkg.setApplicationInfoResourcePath(pkg.codePath);
13333            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13334            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13335
13336            return true;
13337        }
13338
13339        private void setMountPath(String mountPath) {
13340            final File mountFile = new File(mountPath);
13341
13342            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13343            if (monolithicFile.exists()) {
13344                packagePath = monolithicFile.getAbsolutePath();
13345                if (isFwdLocked()) {
13346                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13347                } else {
13348                    resourcePath = packagePath;
13349                }
13350            } else {
13351                packagePath = mountFile.getAbsolutePath();
13352                resourcePath = packagePath;
13353            }
13354        }
13355
13356        int doPostInstall(int status, int uid) {
13357            if (status != PackageManager.INSTALL_SUCCEEDED) {
13358                cleanUp();
13359            } else {
13360                final int groupOwner;
13361                final String protectedFile;
13362                if (isFwdLocked()) {
13363                    groupOwner = UserHandle.getSharedAppGid(uid);
13364                    protectedFile = RES_FILE_NAME;
13365                } else {
13366                    groupOwner = -1;
13367                    protectedFile = null;
13368                }
13369
13370                if (uid < Process.FIRST_APPLICATION_UID
13371                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13372                    Slog.e(TAG, "Failed to finalize " + cid);
13373                    PackageHelper.destroySdDir(cid);
13374                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13375                }
13376
13377                boolean mounted = PackageHelper.isContainerMounted(cid);
13378                if (!mounted) {
13379                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13380                }
13381            }
13382            return status;
13383        }
13384
13385        private void cleanUp() {
13386            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13387
13388            // Destroy secure container
13389            PackageHelper.destroySdDir(cid);
13390        }
13391
13392        private List<String> getAllCodePaths() {
13393            final File codeFile = new File(getCodePath());
13394            if (codeFile != null && codeFile.exists()) {
13395                try {
13396                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13397                    return pkg.getAllCodePaths();
13398                } catch (PackageParserException e) {
13399                    // Ignored; we tried our best
13400                }
13401            }
13402            return Collections.EMPTY_LIST;
13403        }
13404
13405        void cleanUpResourcesLI() {
13406            // Enumerate all code paths before deleting
13407            cleanUpResourcesLI(getAllCodePaths());
13408        }
13409
13410        private void cleanUpResourcesLI(List<String> allCodePaths) {
13411            cleanUp();
13412            removeDexFiles(allCodePaths, instructionSets);
13413        }
13414
13415        String getPackageName() {
13416            return getAsecPackageName(cid);
13417        }
13418
13419        boolean doPostDeleteLI(boolean delete) {
13420            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13421            final List<String> allCodePaths = getAllCodePaths();
13422            boolean mounted = PackageHelper.isContainerMounted(cid);
13423            if (mounted) {
13424                // Unmount first
13425                if (PackageHelper.unMountSdDir(cid)) {
13426                    mounted = false;
13427                }
13428            }
13429            if (!mounted && delete) {
13430                cleanUpResourcesLI(allCodePaths);
13431            }
13432            return !mounted;
13433        }
13434
13435        @Override
13436        int doPreCopy() {
13437            if (isFwdLocked()) {
13438                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13439                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13440                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13441                }
13442            }
13443
13444            return PackageManager.INSTALL_SUCCEEDED;
13445        }
13446
13447        @Override
13448        int doPostCopy(int uid) {
13449            if (isFwdLocked()) {
13450                if (uid < Process.FIRST_APPLICATION_UID
13451                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13452                                RES_FILE_NAME)) {
13453                    Slog.e(TAG, "Failed to finalize " + cid);
13454                    PackageHelper.destroySdDir(cid);
13455                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13456                }
13457            }
13458
13459            return PackageManager.INSTALL_SUCCEEDED;
13460        }
13461    }
13462
13463    /**
13464     * Logic to handle movement of existing installed applications.
13465     */
13466    class MoveInstallArgs extends InstallArgs {
13467        private File codeFile;
13468        private File resourceFile;
13469
13470        /** New install */
13471        MoveInstallArgs(InstallParams params) {
13472            super(params.origin, params.move, params.observer, params.installFlags,
13473                    params.installerPackageName, params.volumeUuid,
13474                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13475                    params.grantedRuntimePermissions,
13476                    params.traceMethod, params.traceCookie, params.certificates);
13477        }
13478
13479        int copyApk(IMediaContainerService imcs, boolean temp) {
13480            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13481                    + move.fromUuid + " to " + move.toUuid);
13482            synchronized (mInstaller) {
13483                try {
13484                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13485                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13486                } catch (InstallerException e) {
13487                    Slog.w(TAG, "Failed to move app", e);
13488                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13489                }
13490            }
13491
13492            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13493            resourceFile = codeFile;
13494            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13495
13496            return PackageManager.INSTALL_SUCCEEDED;
13497        }
13498
13499        int doPreInstall(int status) {
13500            if (status != PackageManager.INSTALL_SUCCEEDED) {
13501                cleanUp(move.toUuid);
13502            }
13503            return status;
13504        }
13505
13506        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13507            if (status != PackageManager.INSTALL_SUCCEEDED) {
13508                cleanUp(move.toUuid);
13509                return false;
13510            }
13511
13512            // Reflect the move in app info
13513            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13514            pkg.setApplicationInfoCodePath(pkg.codePath);
13515            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13516            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13517            pkg.setApplicationInfoResourcePath(pkg.codePath);
13518            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13519            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13520
13521            return true;
13522        }
13523
13524        int doPostInstall(int status, int uid) {
13525            if (status == PackageManager.INSTALL_SUCCEEDED) {
13526                cleanUp(move.fromUuid);
13527            } else {
13528                cleanUp(move.toUuid);
13529            }
13530            return status;
13531        }
13532
13533        @Override
13534        String getCodePath() {
13535            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13536        }
13537
13538        @Override
13539        String getResourcePath() {
13540            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13541        }
13542
13543        private boolean cleanUp(String volumeUuid) {
13544            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13545                    move.dataAppName);
13546            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13547            final int[] userIds = sUserManager.getUserIds();
13548            synchronized (mInstallLock) {
13549                // Clean up both app data and code
13550                // All package moves are frozen until finished
13551                for (int userId : userIds) {
13552                    try {
13553                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13554                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13555                    } catch (InstallerException e) {
13556                        Slog.w(TAG, String.valueOf(e));
13557                    }
13558                }
13559                removeCodePathLI(codeFile);
13560            }
13561            return true;
13562        }
13563
13564        void cleanUpResourcesLI() {
13565            throw new UnsupportedOperationException();
13566        }
13567
13568        boolean doPostDeleteLI(boolean delete) {
13569            throw new UnsupportedOperationException();
13570        }
13571    }
13572
13573    static String getAsecPackageName(String packageCid) {
13574        int idx = packageCid.lastIndexOf("-");
13575        if (idx == -1) {
13576            return packageCid;
13577        }
13578        return packageCid.substring(0, idx);
13579    }
13580
13581    // Utility method used to create code paths based on package name and available index.
13582    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13583        String idxStr = "";
13584        int idx = 1;
13585        // Fall back to default value of idx=1 if prefix is not
13586        // part of oldCodePath
13587        if (oldCodePath != null) {
13588            String subStr = oldCodePath;
13589            // Drop the suffix right away
13590            if (suffix != null && subStr.endsWith(suffix)) {
13591                subStr = subStr.substring(0, subStr.length() - suffix.length());
13592            }
13593            // If oldCodePath already contains prefix find out the
13594            // ending index to either increment or decrement.
13595            int sidx = subStr.lastIndexOf(prefix);
13596            if (sidx != -1) {
13597                subStr = subStr.substring(sidx + prefix.length());
13598                if (subStr != null) {
13599                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13600                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13601                    }
13602                    try {
13603                        idx = Integer.parseInt(subStr);
13604                        if (idx <= 1) {
13605                            idx++;
13606                        } else {
13607                            idx--;
13608                        }
13609                    } catch(NumberFormatException e) {
13610                    }
13611                }
13612            }
13613        }
13614        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13615        return prefix + idxStr;
13616    }
13617
13618    private File getNextCodePath(File targetDir, String packageName) {
13619        int suffix = 1;
13620        File result;
13621        do {
13622            result = new File(targetDir, packageName + "-" + suffix);
13623            suffix++;
13624        } while (result.exists());
13625        return result;
13626    }
13627
13628    // Utility method that returns the relative package path with respect
13629    // to the installation directory. Like say for /data/data/com.test-1.apk
13630    // string com.test-1 is returned.
13631    static String deriveCodePathName(String codePath) {
13632        if (codePath == null) {
13633            return null;
13634        }
13635        final File codeFile = new File(codePath);
13636        final String name = codeFile.getName();
13637        if (codeFile.isDirectory()) {
13638            return name;
13639        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13640            final int lastDot = name.lastIndexOf('.');
13641            return name.substring(0, lastDot);
13642        } else {
13643            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13644            return null;
13645        }
13646    }
13647
13648    static class PackageInstalledInfo {
13649        String name;
13650        int uid;
13651        // The set of users that originally had this package installed.
13652        int[] origUsers;
13653        // The set of users that now have this package installed.
13654        int[] newUsers;
13655        PackageParser.Package pkg;
13656        int returnCode;
13657        String returnMsg;
13658        PackageRemovedInfo removedInfo;
13659        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13660
13661        public void setError(int code, String msg) {
13662            setReturnCode(code);
13663            setReturnMessage(msg);
13664            Slog.w(TAG, msg);
13665        }
13666
13667        public void setError(String msg, PackageParserException e) {
13668            setReturnCode(e.error);
13669            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13670            Slog.w(TAG, msg, e);
13671        }
13672
13673        public void setError(String msg, PackageManagerException e) {
13674            returnCode = e.error;
13675            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13676            Slog.w(TAG, msg, e);
13677        }
13678
13679        public void setReturnCode(int returnCode) {
13680            this.returnCode = returnCode;
13681            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13682            for (int i = 0; i < childCount; i++) {
13683                addedChildPackages.valueAt(i).returnCode = returnCode;
13684            }
13685        }
13686
13687        private void setReturnMessage(String returnMsg) {
13688            this.returnMsg = returnMsg;
13689            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13690            for (int i = 0; i < childCount; i++) {
13691                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13692            }
13693        }
13694
13695        // In some error cases we want to convey more info back to the observer
13696        String origPackage;
13697        String origPermission;
13698    }
13699
13700    /*
13701     * Install a non-existing package.
13702     */
13703    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13704            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13705            PackageInstalledInfo res) {
13706        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13707
13708        // Remember this for later, in case we need to rollback this install
13709        String pkgName = pkg.packageName;
13710
13711        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13712
13713        synchronized(mPackages) {
13714            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13715                // A package with the same name is already installed, though
13716                // it has been renamed to an older name.  The package we
13717                // are trying to install should be installed as an update to
13718                // the existing one, but that has not been requested, so bail.
13719                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13720                        + " without first uninstalling package running as "
13721                        + mSettings.mRenamedPackages.get(pkgName));
13722                return;
13723            }
13724            if (mPackages.containsKey(pkgName)) {
13725                // Don't allow installation over an existing package with the same name.
13726                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13727                        + " without first uninstalling.");
13728                return;
13729            }
13730        }
13731
13732        try {
13733            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13734                    System.currentTimeMillis(), user);
13735
13736            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13737
13738            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13739                prepareAppDataAfterInstallLIF(newPackage);
13740
13741            } else {
13742                // Remove package from internal structures, but keep around any
13743                // data that might have already existed
13744                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13745                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13746            }
13747        } catch (PackageManagerException e) {
13748            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13749        }
13750
13751        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13752    }
13753
13754    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13755        // Can't rotate keys during boot or if sharedUser.
13756        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13757                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13758            return false;
13759        }
13760        // app is using upgradeKeySets; make sure all are valid
13761        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13762        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13763        for (int i = 0; i < upgradeKeySets.length; i++) {
13764            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13765                Slog.wtf(TAG, "Package "
13766                         + (oldPs.name != null ? oldPs.name : "<null>")
13767                         + " contains upgrade-key-set reference to unknown key-set: "
13768                         + upgradeKeySets[i]
13769                         + " reverting to signatures check.");
13770                return false;
13771            }
13772        }
13773        return true;
13774    }
13775
13776    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13777        // Upgrade keysets are being used.  Determine if new package has a superset of the
13778        // required keys.
13779        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13780        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13781        for (int i = 0; i < upgradeKeySets.length; i++) {
13782            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13783            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13784                return true;
13785            }
13786        }
13787        return false;
13788    }
13789
13790    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13791            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13792        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13793
13794        final PackageParser.Package oldPackage;
13795        final String pkgName = pkg.packageName;
13796        final int[] allUsers;
13797        final int[] installedUsers;
13798
13799        synchronized(mPackages) {
13800            oldPackage = mPackages.get(pkgName);
13801            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13802
13803            // don't allow upgrade to target a release SDK from a pre-release SDK
13804            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13805                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13806            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13807                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13808            if (oldTargetsPreRelease
13809                    && !newTargetsPreRelease
13810                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13811                Slog.w(TAG, "Can't install package targeting released sdk");
13812                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13813                return;
13814            }
13815
13816            // don't allow an upgrade from full to ephemeral
13817            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13818            if (isEphemeral && !oldIsEphemeral) {
13819                // can't downgrade from full to ephemeral
13820                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13821                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13822                return;
13823            }
13824
13825            // verify signatures are valid
13826            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13827            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13828                if (!checkUpgradeKeySetLP(ps, pkg)) {
13829                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13830                            "New package not signed by keys specified by upgrade-keysets: "
13831                                    + pkgName);
13832                    return;
13833                }
13834            } else {
13835                // default to original signature matching
13836                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13837                        != PackageManager.SIGNATURE_MATCH) {
13838                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13839                            "New package has a different signature: " + pkgName);
13840                    return;
13841                }
13842            }
13843
13844            // Check for shared user id changes
13845            String invalidPackageName =
13846                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13847            if (invalidPackageName != null) {
13848                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13849                        "Package " + invalidPackageName + " tried to change user "
13850                                + oldPackage.mSharedUserId);
13851                return;
13852            }
13853
13854            // In case of rollback, remember per-user/profile install state
13855            allUsers = sUserManager.getUserIds();
13856            installedUsers = ps.queryInstalledUsers(allUsers, true);
13857        }
13858
13859        // Update what is removed
13860        res.removedInfo = new PackageRemovedInfo();
13861        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13862        res.removedInfo.removedPackage = oldPackage.packageName;
13863        res.removedInfo.isUpdate = true;
13864        res.removedInfo.origUsers = installedUsers;
13865        final int childCount = (oldPackage.childPackages != null)
13866                ? oldPackage.childPackages.size() : 0;
13867        for (int i = 0; i < childCount; i++) {
13868            boolean childPackageUpdated = false;
13869            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13870            if (res.addedChildPackages != null) {
13871                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13872                if (childRes != null) {
13873                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13874                    childRes.removedInfo.removedPackage = childPkg.packageName;
13875                    childRes.removedInfo.isUpdate = true;
13876                    childPackageUpdated = true;
13877                }
13878            }
13879            if (!childPackageUpdated) {
13880                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13881                childRemovedRes.removedPackage = childPkg.packageName;
13882                childRemovedRes.isUpdate = false;
13883                childRemovedRes.dataRemoved = true;
13884                synchronized (mPackages) {
13885                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13886                    if (childPs != null) {
13887                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13888                    }
13889                }
13890                if (res.removedInfo.removedChildPackages == null) {
13891                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13892                }
13893                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13894            }
13895        }
13896
13897        boolean sysPkg = (isSystemApp(oldPackage));
13898        if (sysPkg) {
13899            // Set the system/privileged flags as needed
13900            final boolean privileged =
13901                    (oldPackage.applicationInfo.privateFlags
13902                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13903            final int systemPolicyFlags = policyFlags
13904                    | PackageParser.PARSE_IS_SYSTEM
13905                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13906
13907            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13908                    user, allUsers, installerPackageName, res);
13909        } else {
13910            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13911                    user, allUsers, installerPackageName, res);
13912        }
13913    }
13914
13915    public List<String> getPreviousCodePaths(String packageName) {
13916        final PackageSetting ps = mSettings.mPackages.get(packageName);
13917        final List<String> result = new ArrayList<String>();
13918        if (ps != null && ps.oldCodePaths != null) {
13919            result.addAll(ps.oldCodePaths);
13920        }
13921        return result;
13922    }
13923
13924    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13925            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13926            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13927        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13928                + deletedPackage);
13929
13930        String pkgName = deletedPackage.packageName;
13931        boolean deletedPkg = true;
13932        boolean addedPkg = false;
13933        boolean updatedSettings = false;
13934        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13935        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13936                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13937
13938        final long origUpdateTime = (pkg.mExtras != null)
13939                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13940
13941        // First delete the existing package while retaining the data directory
13942        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13943                res.removedInfo, true, pkg)) {
13944            // If the existing package wasn't successfully deleted
13945            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13946            deletedPkg = false;
13947        } else {
13948            // Successfully deleted the old package; proceed with replace.
13949
13950            // If deleted package lived in a container, give users a chance to
13951            // relinquish resources before killing.
13952            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13953                if (DEBUG_INSTALL) {
13954                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13955                }
13956                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13957                final ArrayList<String> pkgList = new ArrayList<String>(1);
13958                pkgList.add(deletedPackage.applicationInfo.packageName);
13959                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13960            }
13961
13962            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13963                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13964            clearAppProfilesLIF(pkg);
13965
13966            try {
13967                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13968                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13969                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13970
13971                // Update the in-memory copy of the previous code paths.
13972                PackageSetting ps = mSettings.mPackages.get(pkgName);
13973                if (!killApp) {
13974                    if (ps.oldCodePaths == null) {
13975                        ps.oldCodePaths = new ArraySet<>();
13976                    }
13977                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13978                    if (deletedPackage.splitCodePaths != null) {
13979                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13980                    }
13981                } else {
13982                    ps.oldCodePaths = null;
13983                }
13984                if (ps.childPackageNames != null) {
13985                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13986                        final String childPkgName = ps.childPackageNames.get(i);
13987                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13988                        childPs.oldCodePaths = ps.oldCodePaths;
13989                    }
13990                }
13991                prepareAppDataAfterInstallLIF(newPackage);
13992                addedPkg = true;
13993            } catch (PackageManagerException e) {
13994                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13995            }
13996        }
13997
13998        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13999            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14000
14001            // Revert all internal state mutations and added folders for the failed install
14002            if (addedPkg) {
14003                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14004                        res.removedInfo, true, null);
14005            }
14006
14007            // Restore the old package
14008            if (deletedPkg) {
14009                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14010                File restoreFile = new File(deletedPackage.codePath);
14011                // Parse old package
14012                boolean oldExternal = isExternal(deletedPackage);
14013                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14014                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14015                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14016                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14017                try {
14018                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14019                            null);
14020                } catch (PackageManagerException e) {
14021                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14022                            + e.getMessage());
14023                    return;
14024                }
14025
14026                synchronized (mPackages) {
14027                    // Ensure the installer package name up to date
14028                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14029
14030                    // Update permissions for restored package
14031                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14032
14033                    mSettings.writeLPr();
14034                }
14035
14036                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14037            }
14038        } else {
14039            synchronized (mPackages) {
14040                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14041                if (ps != null) {
14042                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14043                    if (res.removedInfo.removedChildPackages != null) {
14044                        final int childCount = res.removedInfo.removedChildPackages.size();
14045                        // Iterate in reverse as we may modify the collection
14046                        for (int i = childCount - 1; i >= 0; i--) {
14047                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14048                            if (res.addedChildPackages.containsKey(childPackageName)) {
14049                                res.removedInfo.removedChildPackages.removeAt(i);
14050                            } else {
14051                                PackageRemovedInfo childInfo = res.removedInfo
14052                                        .removedChildPackages.valueAt(i);
14053                                childInfo.removedForAllUsers = mPackages.get(
14054                                        childInfo.removedPackage) == null;
14055                            }
14056                        }
14057                    }
14058                }
14059            }
14060        }
14061    }
14062
14063    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14064            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14065            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14066        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14067                + ", old=" + deletedPackage);
14068
14069        final boolean disabledSystem;
14070
14071        // Remove existing system package
14072        removePackageLI(deletedPackage, true);
14073
14074        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14075        if (!disabledSystem) {
14076            // We didn't need to disable the .apk as a current system package,
14077            // which means we are replacing another update that is already
14078            // installed.  We need to make sure to delete the older one's .apk.
14079            res.removedInfo.args = createInstallArgsForExisting(0,
14080                    deletedPackage.applicationInfo.getCodePath(),
14081                    deletedPackage.applicationInfo.getResourcePath(),
14082                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14083        } else {
14084            res.removedInfo.args = null;
14085        }
14086
14087        // Successfully disabled the old package. Now proceed with re-installation
14088        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14089                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14090        clearAppProfilesLIF(pkg);
14091
14092        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14093        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14094                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14095
14096        PackageParser.Package newPackage = null;
14097        try {
14098            // Add the package to the internal data structures
14099            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14100
14101            // Set the update and install times
14102            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14103            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14104                    System.currentTimeMillis());
14105
14106            // Update the package dynamic state if succeeded
14107            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14108                // Now that the install succeeded make sure we remove data
14109                // directories for any child package the update removed.
14110                final int deletedChildCount = (deletedPackage.childPackages != null)
14111                        ? deletedPackage.childPackages.size() : 0;
14112                final int newChildCount = (newPackage.childPackages != null)
14113                        ? newPackage.childPackages.size() : 0;
14114                for (int i = 0; i < deletedChildCount; i++) {
14115                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14116                    boolean childPackageDeleted = true;
14117                    for (int j = 0; j < newChildCount; j++) {
14118                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14119                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14120                            childPackageDeleted = false;
14121                            break;
14122                        }
14123                    }
14124                    if (childPackageDeleted) {
14125                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14126                                deletedChildPkg.packageName);
14127                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14128                            PackageRemovedInfo removedChildRes = res.removedInfo
14129                                    .removedChildPackages.get(deletedChildPkg.packageName);
14130                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14131                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14132                        }
14133                    }
14134                }
14135
14136                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14137                prepareAppDataAfterInstallLIF(newPackage);
14138            }
14139        } catch (PackageManagerException e) {
14140            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14141            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14142        }
14143
14144        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14145            // Re installation failed. Restore old information
14146            // Remove new pkg information
14147            if (newPackage != null) {
14148                removeInstalledPackageLI(newPackage, true);
14149            }
14150            // Add back the old system package
14151            try {
14152                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14153            } catch (PackageManagerException e) {
14154                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14155            }
14156
14157            synchronized (mPackages) {
14158                if (disabledSystem) {
14159                    enableSystemPackageLPw(deletedPackage);
14160                }
14161
14162                // Ensure the installer package name up to date
14163                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14164
14165                // Update permissions for restored package
14166                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14167
14168                mSettings.writeLPr();
14169            }
14170
14171            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14172                    + " after failed upgrade");
14173        }
14174    }
14175
14176    /**
14177     * Checks whether the parent or any of the child packages have a change shared
14178     * user. For a package to be a valid update the shred users of the parent and
14179     * the children should match. We may later support changing child shared users.
14180     * @param oldPkg The updated package.
14181     * @param newPkg The update package.
14182     * @return The shared user that change between the versions.
14183     */
14184    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14185            PackageParser.Package newPkg) {
14186        // Check parent shared user
14187        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14188            return newPkg.packageName;
14189        }
14190        // Check child shared users
14191        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14192        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14193        for (int i = 0; i < newChildCount; i++) {
14194            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14195            // If this child was present, did it have the same shared user?
14196            for (int j = 0; j < oldChildCount; j++) {
14197                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14198                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14199                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14200                    return newChildPkg.packageName;
14201                }
14202            }
14203        }
14204        return null;
14205    }
14206
14207    private void removeNativeBinariesLI(PackageSetting ps) {
14208        // Remove the lib path for the parent package
14209        if (ps != null) {
14210            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14211            // Remove the lib path for the child packages
14212            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14213            for (int i = 0; i < childCount; i++) {
14214                PackageSetting childPs = null;
14215                synchronized (mPackages) {
14216                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14217                }
14218                if (childPs != null) {
14219                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14220                            .legacyNativeLibraryPathString);
14221                }
14222            }
14223        }
14224    }
14225
14226    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14227        // Enable the parent package
14228        mSettings.enableSystemPackageLPw(pkg.packageName);
14229        // Enable the child packages
14230        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14231        for (int i = 0; i < childCount; i++) {
14232            PackageParser.Package childPkg = pkg.childPackages.get(i);
14233            mSettings.enableSystemPackageLPw(childPkg.packageName);
14234        }
14235    }
14236
14237    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14238            PackageParser.Package newPkg) {
14239        // Disable the parent package (parent always replaced)
14240        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14241        // Disable the child packages
14242        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14243        for (int i = 0; i < childCount; i++) {
14244            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14245            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14246            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14247        }
14248        return disabled;
14249    }
14250
14251    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14252            String installerPackageName) {
14253        // Enable the parent package
14254        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14255        // Enable the child packages
14256        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14257        for (int i = 0; i < childCount; i++) {
14258            PackageParser.Package childPkg = pkg.childPackages.get(i);
14259            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14260        }
14261    }
14262
14263    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14264        // Collect all used permissions in the UID
14265        ArraySet<String> usedPermissions = new ArraySet<>();
14266        final int packageCount = su.packages.size();
14267        for (int i = 0; i < packageCount; i++) {
14268            PackageSetting ps = su.packages.valueAt(i);
14269            if (ps.pkg == null) {
14270                continue;
14271            }
14272            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14273            for (int j = 0; j < requestedPermCount; j++) {
14274                String permission = ps.pkg.requestedPermissions.get(j);
14275                BasePermission bp = mSettings.mPermissions.get(permission);
14276                if (bp != null) {
14277                    usedPermissions.add(permission);
14278                }
14279            }
14280        }
14281
14282        PermissionsState permissionsState = su.getPermissionsState();
14283        // Prune install permissions
14284        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14285        final int installPermCount = installPermStates.size();
14286        for (int i = installPermCount - 1; i >= 0;  i--) {
14287            PermissionState permissionState = installPermStates.get(i);
14288            if (!usedPermissions.contains(permissionState.getName())) {
14289                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14290                if (bp != null) {
14291                    permissionsState.revokeInstallPermission(bp);
14292                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14293                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14294                }
14295            }
14296        }
14297
14298        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14299
14300        // Prune runtime permissions
14301        for (int userId : allUserIds) {
14302            List<PermissionState> runtimePermStates = permissionsState
14303                    .getRuntimePermissionStates(userId);
14304            final int runtimePermCount = runtimePermStates.size();
14305            for (int i = runtimePermCount - 1; i >= 0; i--) {
14306                PermissionState permissionState = runtimePermStates.get(i);
14307                if (!usedPermissions.contains(permissionState.getName())) {
14308                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14309                    if (bp != null) {
14310                        permissionsState.revokeRuntimePermission(bp, userId);
14311                        permissionsState.updatePermissionFlags(bp, userId,
14312                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14313                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14314                                runtimePermissionChangedUserIds, userId);
14315                    }
14316                }
14317            }
14318        }
14319
14320        return runtimePermissionChangedUserIds;
14321    }
14322
14323    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14324            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14325        // Update the parent package setting
14326        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14327                res, user);
14328        // Update the child packages setting
14329        final int childCount = (newPackage.childPackages != null)
14330                ? newPackage.childPackages.size() : 0;
14331        for (int i = 0; i < childCount; i++) {
14332            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14333            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14334            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14335                    childRes.origUsers, childRes, user);
14336        }
14337    }
14338
14339    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14340            String installerPackageName, int[] allUsers, int[] installedForUsers,
14341            PackageInstalledInfo res, UserHandle user) {
14342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14343
14344        String pkgName = newPackage.packageName;
14345        synchronized (mPackages) {
14346            //write settings. the installStatus will be incomplete at this stage.
14347            //note that the new package setting would have already been
14348            //added to mPackages. It hasn't been persisted yet.
14349            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14350            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14351            mSettings.writeLPr();
14352            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14353        }
14354
14355        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14356        synchronized (mPackages) {
14357            updatePermissionsLPw(newPackage.packageName, newPackage,
14358                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14359                            ? UPDATE_PERMISSIONS_ALL : 0));
14360            // For system-bundled packages, we assume that installing an upgraded version
14361            // of the package implies that the user actually wants to run that new code,
14362            // so we enable the package.
14363            PackageSetting ps = mSettings.mPackages.get(pkgName);
14364            final int userId = user.getIdentifier();
14365            if (ps != null) {
14366                if (isSystemApp(newPackage)) {
14367                    if (DEBUG_INSTALL) {
14368                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14369                    }
14370                    // Enable system package for requested users
14371                    if (res.origUsers != null) {
14372                        for (int origUserId : res.origUsers) {
14373                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14374                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14375                                        origUserId, installerPackageName);
14376                            }
14377                        }
14378                    }
14379                    // Also convey the prior install/uninstall state
14380                    if (allUsers != null && installedForUsers != null) {
14381                        for (int currentUserId : allUsers) {
14382                            final boolean installed = ArrayUtils.contains(
14383                                    installedForUsers, currentUserId);
14384                            if (DEBUG_INSTALL) {
14385                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14386                            }
14387                            ps.setInstalled(installed, currentUserId);
14388                        }
14389                        // these install state changes will be persisted in the
14390                        // upcoming call to mSettings.writeLPr().
14391                    }
14392                }
14393                // It's implied that when a user requests installation, they want the app to be
14394                // installed and enabled.
14395                if (userId != UserHandle.USER_ALL) {
14396                    ps.setInstalled(true, userId);
14397                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14398                }
14399            }
14400            res.name = pkgName;
14401            res.uid = newPackage.applicationInfo.uid;
14402            res.pkg = newPackage;
14403            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14404            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14405            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14406            //to update install status
14407            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14408            mSettings.writeLPr();
14409            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14410        }
14411
14412        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14413    }
14414
14415    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14416        try {
14417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14418            installPackageLI(args, res);
14419        } finally {
14420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14421        }
14422    }
14423
14424    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14425        final int installFlags = args.installFlags;
14426        final String installerPackageName = args.installerPackageName;
14427        final String volumeUuid = args.volumeUuid;
14428        final File tmpPackageFile = new File(args.getCodePath());
14429        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14430        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14431                || (args.volumeUuid != null));
14432        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14433        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14434        boolean replace = false;
14435        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14436        if (args.move != null) {
14437            // moving a complete application; perform an initial scan on the new install location
14438            scanFlags |= SCAN_INITIAL;
14439        }
14440        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14441            scanFlags |= SCAN_DONT_KILL_APP;
14442        }
14443
14444        // Result object to be returned
14445        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14446
14447        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14448
14449        // Sanity check
14450        if (ephemeral && (forwardLocked || onExternal)) {
14451            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14452                    + " external=" + onExternal);
14453            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14454            return;
14455        }
14456
14457        // Retrieve PackageSettings and parse package
14458        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14459                | PackageParser.PARSE_ENFORCE_CODE
14460                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14461                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14462                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14463                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14464        PackageParser pp = new PackageParser();
14465        pp.setSeparateProcesses(mSeparateProcesses);
14466        pp.setDisplayMetrics(mMetrics);
14467
14468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14469        final PackageParser.Package pkg;
14470        try {
14471            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14472        } catch (PackageParserException e) {
14473            res.setError("Failed parse during installPackageLI", e);
14474            return;
14475        } finally {
14476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14477        }
14478
14479        // If we are installing a clustered package add results for the children
14480        if (pkg.childPackages != null) {
14481            synchronized (mPackages) {
14482                final int childCount = pkg.childPackages.size();
14483                for (int i = 0; i < childCount; i++) {
14484                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14485                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14486                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14487                    childRes.pkg = childPkg;
14488                    childRes.name = childPkg.packageName;
14489                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14490                    if (childPs != null) {
14491                        childRes.origUsers = childPs.queryInstalledUsers(
14492                                sUserManager.getUserIds(), true);
14493                    }
14494                    if ((mPackages.containsKey(childPkg.packageName))) {
14495                        childRes.removedInfo = new PackageRemovedInfo();
14496                        childRes.removedInfo.removedPackage = childPkg.packageName;
14497                    }
14498                    if (res.addedChildPackages == null) {
14499                        res.addedChildPackages = new ArrayMap<>();
14500                    }
14501                    res.addedChildPackages.put(childPkg.packageName, childRes);
14502                }
14503            }
14504        }
14505
14506        // If package doesn't declare API override, mark that we have an install
14507        // time CPU ABI override.
14508        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14509            pkg.cpuAbiOverride = args.abiOverride;
14510        }
14511
14512        String pkgName = res.name = pkg.packageName;
14513        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14514            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14515                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14516                return;
14517            }
14518        }
14519
14520        try {
14521            // either use what we've been given or parse directly from the APK
14522            if (args.certificates != null) {
14523                try {
14524                    PackageParser.populateCertificates(pkg, args.certificates);
14525                } catch (PackageParserException e) {
14526                    // there was something wrong with the certificates we were given;
14527                    // try to pull them from the APK
14528                    PackageParser.collectCertificates(pkg, parseFlags);
14529                }
14530            } else {
14531                PackageParser.collectCertificates(pkg, parseFlags);
14532            }
14533        } catch (PackageParserException e) {
14534            res.setError("Failed collect during installPackageLI", e);
14535            return;
14536        }
14537
14538        // Get rid of all references to package scan path via parser.
14539        pp = null;
14540        String oldCodePath = null;
14541        boolean systemApp = false;
14542        synchronized (mPackages) {
14543            // Check if installing already existing package
14544            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14545                String oldName = mSettings.mRenamedPackages.get(pkgName);
14546                if (pkg.mOriginalPackages != null
14547                        && pkg.mOriginalPackages.contains(oldName)
14548                        && mPackages.containsKey(oldName)) {
14549                    // This package is derived from an original package,
14550                    // and this device has been updating from that original
14551                    // name.  We must continue using the original name, so
14552                    // rename the new package here.
14553                    pkg.setPackageName(oldName);
14554                    pkgName = pkg.packageName;
14555                    replace = true;
14556                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14557                            + oldName + " pkgName=" + pkgName);
14558                } else if (mPackages.containsKey(pkgName)) {
14559                    // This package, under its official name, already exists
14560                    // on the device; we should replace it.
14561                    replace = true;
14562                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14563                }
14564
14565                // Child packages are installed through the parent package
14566                if (pkg.parentPackage != null) {
14567                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14568                            "Package " + pkg.packageName + " is child of package "
14569                                    + pkg.parentPackage.parentPackage + ". Child packages "
14570                                    + "can be updated only through the parent package.");
14571                    return;
14572                }
14573
14574                if (replace) {
14575                    // Prevent apps opting out from runtime permissions
14576                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14577                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14578                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14579                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14580                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14581                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14582                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14583                                        + " doesn't support runtime permissions but the old"
14584                                        + " target SDK " + oldTargetSdk + " does.");
14585                        return;
14586                    }
14587
14588                    // Prevent installing of child packages
14589                    if (oldPackage.parentPackage != null) {
14590                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14591                                "Package " + pkg.packageName + " is child of package "
14592                                        + oldPackage.parentPackage + ". Child packages "
14593                                        + "can be updated only through the parent package.");
14594                        return;
14595                    }
14596                }
14597            }
14598
14599            PackageSetting ps = mSettings.mPackages.get(pkgName);
14600            if (ps != null) {
14601                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14602
14603                // Quick sanity check that we're signed correctly if updating;
14604                // we'll check this again later when scanning, but we want to
14605                // bail early here before tripping over redefined permissions.
14606                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14607                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14608                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14609                                + pkg.packageName + " upgrade keys do not match the "
14610                                + "previously installed version");
14611                        return;
14612                    }
14613                } else {
14614                    try {
14615                        verifySignaturesLP(ps, pkg);
14616                    } catch (PackageManagerException e) {
14617                        res.setError(e.error, e.getMessage());
14618                        return;
14619                    }
14620                }
14621
14622                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14623                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14624                    systemApp = (ps.pkg.applicationInfo.flags &
14625                            ApplicationInfo.FLAG_SYSTEM) != 0;
14626                }
14627                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14628            }
14629
14630            // Check whether the newly-scanned package wants to define an already-defined perm
14631            int N = pkg.permissions.size();
14632            for (int i = N-1; i >= 0; i--) {
14633                PackageParser.Permission perm = pkg.permissions.get(i);
14634                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14635                if (bp != null) {
14636                    // If the defining package is signed with our cert, it's okay.  This
14637                    // also includes the "updating the same package" case, of course.
14638                    // "updating same package" could also involve key-rotation.
14639                    final boolean sigsOk;
14640                    if (bp.sourcePackage.equals(pkg.packageName)
14641                            && (bp.packageSetting instanceof PackageSetting)
14642                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14643                                    scanFlags))) {
14644                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14645                    } else {
14646                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14647                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14648                    }
14649                    if (!sigsOk) {
14650                        // If the owning package is the system itself, we log but allow
14651                        // install to proceed; we fail the install on all other permission
14652                        // redefinitions.
14653                        if (!bp.sourcePackage.equals("android")) {
14654                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14655                                    + pkg.packageName + " attempting to redeclare permission "
14656                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14657                            res.origPermission = perm.info.name;
14658                            res.origPackage = bp.sourcePackage;
14659                            return;
14660                        } else {
14661                            Slog.w(TAG, "Package " + pkg.packageName
14662                                    + " attempting to redeclare system permission "
14663                                    + perm.info.name + "; ignoring new declaration");
14664                            pkg.permissions.remove(i);
14665                        }
14666                    }
14667                }
14668            }
14669        }
14670
14671        if (systemApp) {
14672            if (onExternal) {
14673                // Abort update; system app can't be replaced with app on sdcard
14674                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14675                        "Cannot install updates to system apps on sdcard");
14676                return;
14677            } else if (ephemeral) {
14678                // Abort update; system app can't be replaced with an ephemeral app
14679                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14680                        "Cannot update a system app with an ephemeral app");
14681                return;
14682            }
14683        }
14684
14685        if (args.move != null) {
14686            // We did an in-place move, so dex is ready to roll
14687            scanFlags |= SCAN_NO_DEX;
14688            scanFlags |= SCAN_MOVE;
14689
14690            synchronized (mPackages) {
14691                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14692                if (ps == null) {
14693                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14694                            "Missing settings for moved package " + pkgName);
14695                }
14696
14697                // We moved the entire application as-is, so bring over the
14698                // previously derived ABI information.
14699                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14700                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14701            }
14702
14703        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14704            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14705            scanFlags |= SCAN_NO_DEX;
14706
14707            try {
14708                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14709                    args.abiOverride : pkg.cpuAbiOverride);
14710                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14711                        true /* extract libs */);
14712            } catch (PackageManagerException pme) {
14713                Slog.e(TAG, "Error deriving application ABI", pme);
14714                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14715                return;
14716            }
14717
14718            // Shared libraries for the package need to be updated.
14719            synchronized (mPackages) {
14720                try {
14721                    updateSharedLibrariesLPw(pkg, null);
14722                } catch (PackageManagerException e) {
14723                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14724                }
14725            }
14726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14727            // Do not run PackageDexOptimizer through the local performDexOpt
14728            // method because `pkg` is not in `mPackages` yet.
14729            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14730                    null /* instructionSets */, false /* checkProfiles */,
14731                    getCompilerFilterForReason(REASON_INSTALL));
14732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14733            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14734                String msg = "Extracting package failed for " + pkgName;
14735                res.setError(INSTALL_FAILED_DEXOPT, msg);
14736                return;
14737            }
14738
14739            // Notify BackgroundDexOptService that the package has been changed.
14740            // If this is an update of a package which used to fail to compile,
14741            // BDOS will remove it from its blacklist.
14742            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14743        }
14744
14745        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14746            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14747            return;
14748        }
14749
14750        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14751
14752        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14753                "installPackageLI")) {
14754            if (replace) {
14755                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14756                        installerPackageName, res);
14757            } else {
14758                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14759                        args.user, installerPackageName, volumeUuid, res);
14760            }
14761        }
14762        synchronized (mPackages) {
14763            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14764            if (ps != null) {
14765                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14766            }
14767
14768            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14769            for (int i = 0; i < childCount; i++) {
14770                PackageParser.Package childPkg = pkg.childPackages.get(i);
14771                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14772                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14773                if (childPs != null) {
14774                    childRes.newUsers = childPs.queryInstalledUsers(
14775                            sUserManager.getUserIds(), true);
14776                }
14777            }
14778        }
14779    }
14780
14781    private void startIntentFilterVerifications(int userId, boolean replacing,
14782            PackageParser.Package pkg) {
14783        if (mIntentFilterVerifierComponent == null) {
14784            Slog.w(TAG, "No IntentFilter verification will not be done as "
14785                    + "there is no IntentFilterVerifier available!");
14786            return;
14787        }
14788
14789        final int verifierUid = getPackageUid(
14790                mIntentFilterVerifierComponent.getPackageName(),
14791                MATCH_DEBUG_TRIAGED_MISSING,
14792                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14793
14794        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14795        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14796        mHandler.sendMessage(msg);
14797
14798        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14799        for (int i = 0; i < childCount; i++) {
14800            PackageParser.Package childPkg = pkg.childPackages.get(i);
14801            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14802            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14803            mHandler.sendMessage(msg);
14804        }
14805    }
14806
14807    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14808            PackageParser.Package pkg) {
14809        int size = pkg.activities.size();
14810        if (size == 0) {
14811            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14812                    "No activity, so no need to verify any IntentFilter!");
14813            return;
14814        }
14815
14816        final boolean hasDomainURLs = hasDomainURLs(pkg);
14817        if (!hasDomainURLs) {
14818            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14819                    "No domain URLs, so no need to verify any IntentFilter!");
14820            return;
14821        }
14822
14823        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14824                + " if any IntentFilter from the " + size
14825                + " Activities needs verification ...");
14826
14827        int count = 0;
14828        final String packageName = pkg.packageName;
14829
14830        synchronized (mPackages) {
14831            // If this is a new install and we see that we've already run verification for this
14832            // package, we have nothing to do: it means the state was restored from backup.
14833            if (!replacing) {
14834                IntentFilterVerificationInfo ivi =
14835                        mSettings.getIntentFilterVerificationLPr(packageName);
14836                if (ivi != null) {
14837                    if (DEBUG_DOMAIN_VERIFICATION) {
14838                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14839                                + ivi.getStatusString());
14840                    }
14841                    return;
14842                }
14843            }
14844
14845            // If any filters need to be verified, then all need to be.
14846            boolean needToVerify = false;
14847            for (PackageParser.Activity a : pkg.activities) {
14848                for (ActivityIntentInfo filter : a.intents) {
14849                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14850                        if (DEBUG_DOMAIN_VERIFICATION) {
14851                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14852                        }
14853                        needToVerify = true;
14854                        break;
14855                    }
14856                }
14857            }
14858
14859            if (needToVerify) {
14860                final int verificationId = mIntentFilterVerificationToken++;
14861                for (PackageParser.Activity a : pkg.activities) {
14862                    for (ActivityIntentInfo filter : a.intents) {
14863                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14864                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14865                                    "Verification needed for IntentFilter:" + filter.toString());
14866                            mIntentFilterVerifier.addOneIntentFilterVerification(
14867                                    verifierUid, userId, verificationId, filter, packageName);
14868                            count++;
14869                        }
14870                    }
14871                }
14872            }
14873        }
14874
14875        if (count > 0) {
14876            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14877                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14878                    +  " for userId:" + userId);
14879            mIntentFilterVerifier.startVerifications(userId);
14880        } else {
14881            if (DEBUG_DOMAIN_VERIFICATION) {
14882                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14883            }
14884        }
14885    }
14886
14887    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14888        final ComponentName cn  = filter.activity.getComponentName();
14889        final String packageName = cn.getPackageName();
14890
14891        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14892                packageName);
14893        if (ivi == null) {
14894            return true;
14895        }
14896        int status = ivi.getStatus();
14897        switch (status) {
14898            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14899            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14900                return true;
14901
14902            default:
14903                // Nothing to do
14904                return false;
14905        }
14906    }
14907
14908    private static boolean isMultiArch(ApplicationInfo info) {
14909        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14910    }
14911
14912    private static boolean isExternal(PackageParser.Package pkg) {
14913        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14914    }
14915
14916    private static boolean isExternal(PackageSetting ps) {
14917        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14918    }
14919
14920    private static boolean isEphemeral(PackageParser.Package pkg) {
14921        return pkg.applicationInfo.isEphemeralApp();
14922    }
14923
14924    private static boolean isEphemeral(PackageSetting ps) {
14925        return ps.pkg != null && isEphemeral(ps.pkg);
14926    }
14927
14928    private static boolean isSystemApp(PackageParser.Package pkg) {
14929        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14930    }
14931
14932    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14933        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14934    }
14935
14936    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14937        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14938    }
14939
14940    private static boolean isSystemApp(PackageSetting ps) {
14941        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14942    }
14943
14944    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14945        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14946    }
14947
14948    private int packageFlagsToInstallFlags(PackageSetting ps) {
14949        int installFlags = 0;
14950        if (isEphemeral(ps)) {
14951            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14952        }
14953        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14954            // This existing package was an external ASEC install when we have
14955            // the external flag without a UUID
14956            installFlags |= PackageManager.INSTALL_EXTERNAL;
14957        }
14958        if (ps.isForwardLocked()) {
14959            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14960        }
14961        return installFlags;
14962    }
14963
14964    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14965        if (isExternal(pkg)) {
14966            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14967                return StorageManager.UUID_PRIMARY_PHYSICAL;
14968            } else {
14969                return pkg.volumeUuid;
14970            }
14971        } else {
14972            return StorageManager.UUID_PRIVATE_INTERNAL;
14973        }
14974    }
14975
14976    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14977        if (isExternal(pkg)) {
14978            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14979                return mSettings.getExternalVersion();
14980            } else {
14981                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14982            }
14983        } else {
14984            return mSettings.getInternalVersion();
14985        }
14986    }
14987
14988    private void deleteTempPackageFiles() {
14989        final FilenameFilter filter = new FilenameFilter() {
14990            public boolean accept(File dir, String name) {
14991                return name.startsWith("vmdl") && name.endsWith(".tmp");
14992            }
14993        };
14994        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14995            file.delete();
14996        }
14997    }
14998
14999    @Override
15000    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15001            int flags) {
15002        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15003                flags);
15004    }
15005
15006    @Override
15007    public void deletePackage(final String packageName,
15008            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15009        mContext.enforceCallingOrSelfPermission(
15010                android.Manifest.permission.DELETE_PACKAGES, null);
15011        Preconditions.checkNotNull(packageName);
15012        Preconditions.checkNotNull(observer);
15013        final int uid = Binder.getCallingUid();
15014        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15015        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15016        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15017            mContext.enforceCallingOrSelfPermission(
15018                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15019                    "deletePackage for user " + userId);
15020        }
15021
15022        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15023            try {
15024                observer.onPackageDeleted(packageName,
15025                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15026            } catch (RemoteException re) {
15027            }
15028            return;
15029        }
15030
15031        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15032            try {
15033                observer.onPackageDeleted(packageName,
15034                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15035            } catch (RemoteException re) {
15036            }
15037            return;
15038        }
15039
15040        if (DEBUG_REMOVE) {
15041            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15042                    + " deleteAllUsers: " + deleteAllUsers );
15043        }
15044        // Queue up an async operation since the package deletion may take a little while.
15045        mHandler.post(new Runnable() {
15046            public void run() {
15047                mHandler.removeCallbacks(this);
15048                int returnCode;
15049                if (!deleteAllUsers) {
15050                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15051                } else {
15052                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15053                    // If nobody is blocking uninstall, proceed with delete for all users
15054                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15055                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15056                    } else {
15057                        // Otherwise uninstall individually for users with blockUninstalls=false
15058                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15059                        for (int userId : users) {
15060                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15061                                returnCode = deletePackageX(packageName, userId, userFlags);
15062                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15063                                    Slog.w(TAG, "Package delete failed for user " + userId
15064                                            + ", returnCode " + returnCode);
15065                                }
15066                            }
15067                        }
15068                        // The app has only been marked uninstalled for certain users.
15069                        // We still need to report that delete was blocked
15070                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15071                    }
15072                }
15073                try {
15074                    observer.onPackageDeleted(packageName, returnCode, null);
15075                } catch (RemoteException e) {
15076                    Log.i(TAG, "Observer no longer exists.");
15077                } //end catch
15078            } //end run
15079        });
15080    }
15081
15082    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15083        int[] result = EMPTY_INT_ARRAY;
15084        for (int userId : userIds) {
15085            if (getBlockUninstallForUser(packageName, userId)) {
15086                result = ArrayUtils.appendInt(result, userId);
15087            }
15088        }
15089        return result;
15090    }
15091
15092    @Override
15093    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15094        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15095    }
15096
15097    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15098        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15099                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15100        try {
15101            if (dpm != null) {
15102                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15103                        /* callingUserOnly =*/ false);
15104                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15105                        : deviceOwnerComponentName.getPackageName();
15106                // Does the package contains the device owner?
15107                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15108                // this check is probably not needed, since DO should be registered as a device
15109                // admin on some user too. (Original bug for this: b/17657954)
15110                if (packageName.equals(deviceOwnerPackageName)) {
15111                    return true;
15112                }
15113                // Does it contain a device admin for any user?
15114                int[] users;
15115                if (userId == UserHandle.USER_ALL) {
15116                    users = sUserManager.getUserIds();
15117                } else {
15118                    users = new int[]{userId};
15119                }
15120                for (int i = 0; i < users.length; ++i) {
15121                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15122                        return true;
15123                    }
15124                }
15125            }
15126        } catch (RemoteException e) {
15127        }
15128        return false;
15129    }
15130
15131    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15132        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15133    }
15134
15135    /**
15136     *  This method is an internal method that could be get invoked either
15137     *  to delete an installed package or to clean up a failed installation.
15138     *  After deleting an installed package, a broadcast is sent to notify any
15139     *  listeners that the package has been removed. For cleaning up a failed
15140     *  installation, the broadcast is not necessary since the package's
15141     *  installation wouldn't have sent the initial broadcast either
15142     *  The key steps in deleting a package are
15143     *  deleting the package information in internal structures like mPackages,
15144     *  deleting the packages base directories through installd
15145     *  updating mSettings to reflect current status
15146     *  persisting settings for later use
15147     *  sending a broadcast if necessary
15148     */
15149    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15150        final PackageRemovedInfo info = new PackageRemovedInfo();
15151        final boolean res;
15152
15153        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15154                ? UserHandle.ALL : new UserHandle(userId);
15155
15156        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15157            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15158            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15159        }
15160
15161        PackageSetting uninstalledPs = null;
15162
15163        // for the uninstall-updates case and restricted profiles, remember the per-
15164        // user handle installed state
15165        int[] allUsers;
15166        synchronized (mPackages) {
15167            uninstalledPs = mSettings.mPackages.get(packageName);
15168            if (uninstalledPs == null) {
15169                Slog.w(TAG, "Not removing non-existent package " + packageName);
15170                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15171            }
15172            allUsers = sUserManager.getUserIds();
15173            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15174        }
15175
15176        synchronized (mInstallLock) {
15177            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15178            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15179                    "deletePackageX")) {
15180                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15181                        deleteFlags | REMOVE_CHATTY, info, true, null);
15182            }
15183            synchronized (mPackages) {
15184                if (res) {
15185                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15186                }
15187            }
15188        }
15189
15190        if (res) {
15191            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15192            info.sendPackageRemovedBroadcasts(killApp);
15193            info.sendSystemPackageUpdatedBroadcasts();
15194            info.sendSystemPackageAppearedBroadcasts();
15195        }
15196        // Force a gc here.
15197        Runtime.getRuntime().gc();
15198        // Delete the resources here after sending the broadcast to let
15199        // other processes clean up before deleting resources.
15200        if (info.args != null) {
15201            synchronized (mInstallLock) {
15202                info.args.doPostDeleteLI(true);
15203            }
15204        }
15205
15206        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15207    }
15208
15209    class PackageRemovedInfo {
15210        String removedPackage;
15211        int uid = -1;
15212        int removedAppId = -1;
15213        int[] origUsers;
15214        int[] removedUsers = null;
15215        boolean isRemovedPackageSystemUpdate = false;
15216        boolean isUpdate;
15217        boolean dataRemoved;
15218        boolean removedForAllUsers;
15219        // Clean up resources deleted packages.
15220        InstallArgs args = null;
15221        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15222        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15223
15224        void sendPackageRemovedBroadcasts(boolean killApp) {
15225            sendPackageRemovedBroadcastInternal(killApp);
15226            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15227            for (int i = 0; i < childCount; i++) {
15228                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15229                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15230            }
15231        }
15232
15233        void sendSystemPackageUpdatedBroadcasts() {
15234            if (isRemovedPackageSystemUpdate) {
15235                sendSystemPackageUpdatedBroadcastsInternal();
15236                final int childCount = (removedChildPackages != null)
15237                        ? removedChildPackages.size() : 0;
15238                for (int i = 0; i < childCount; i++) {
15239                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15240                    if (childInfo.isRemovedPackageSystemUpdate) {
15241                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15242                    }
15243                }
15244            }
15245        }
15246
15247        void sendSystemPackageAppearedBroadcasts() {
15248            final int packageCount = (appearedChildPackages != null)
15249                    ? appearedChildPackages.size() : 0;
15250            for (int i = 0; i < packageCount; i++) {
15251                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15252                for (int userId : installedInfo.newUsers) {
15253                    sendPackageAddedForUser(installedInfo.name, true,
15254                            UserHandle.getAppId(installedInfo.uid), userId);
15255                }
15256            }
15257        }
15258
15259        private void sendSystemPackageUpdatedBroadcastsInternal() {
15260            Bundle extras = new Bundle(2);
15261            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15262            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15263            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15264                    extras, 0, null, null, null);
15265            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15266                    extras, 0, null, null, null);
15267            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15268                    null, 0, removedPackage, null, null);
15269        }
15270
15271        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15272            Bundle extras = new Bundle(2);
15273            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15274            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15275            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15276            if (isUpdate || isRemovedPackageSystemUpdate) {
15277                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15278            }
15279            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15280            if (removedPackage != null) {
15281                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15282                        extras, 0, null, null, removedUsers);
15283                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15284                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15285                            removedPackage, extras, 0, null, null, removedUsers);
15286                }
15287            }
15288            if (removedAppId >= 0) {
15289                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15290                        removedUsers);
15291            }
15292        }
15293    }
15294
15295    /*
15296     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15297     * flag is not set, the data directory is removed as well.
15298     * make sure this flag is set for partially installed apps. If not its meaningless to
15299     * delete a partially installed application.
15300     */
15301    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15302            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15303        String packageName = ps.name;
15304        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15305        // Retrieve object to delete permissions for shared user later on
15306        final PackageParser.Package deletedPkg;
15307        final PackageSetting deletedPs;
15308        // reader
15309        synchronized (mPackages) {
15310            deletedPkg = mPackages.get(packageName);
15311            deletedPs = mSettings.mPackages.get(packageName);
15312            if (outInfo != null) {
15313                outInfo.removedPackage = packageName;
15314                outInfo.removedUsers = deletedPs != null
15315                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15316                        : null;
15317            }
15318        }
15319
15320        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15321
15322        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15323            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15324                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15325            destroyAppProfilesLIF(deletedPkg);
15326            if (outInfo != null) {
15327                outInfo.dataRemoved = true;
15328            }
15329            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15330        }
15331
15332        // writer
15333        synchronized (mPackages) {
15334            if (deletedPs != null) {
15335                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15336                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15337                    clearDefaultBrowserIfNeeded(packageName);
15338                    if (outInfo != null) {
15339                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15340                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15341                    }
15342                    updatePermissionsLPw(deletedPs.name, null, 0);
15343                    if (deletedPs.sharedUser != null) {
15344                        // Remove permissions associated with package. Since runtime
15345                        // permissions are per user we have to kill the removed package
15346                        // or packages running under the shared user of the removed
15347                        // package if revoking the permissions requested only by the removed
15348                        // package is successful and this causes a change in gids.
15349                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15350                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15351                                    userId);
15352                            if (userIdToKill == UserHandle.USER_ALL
15353                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15354                                // If gids changed for this user, kill all affected packages.
15355                                mHandler.post(new Runnable() {
15356                                    @Override
15357                                    public void run() {
15358                                        // This has to happen with no lock held.
15359                                        killApplication(deletedPs.name, deletedPs.appId,
15360                                                KILL_APP_REASON_GIDS_CHANGED);
15361                                    }
15362                                });
15363                                break;
15364                            }
15365                        }
15366                    }
15367                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15368                }
15369                // make sure to preserve per-user disabled state if this removal was just
15370                // a downgrade of a system app to the factory package
15371                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15372                    if (DEBUG_REMOVE) {
15373                        Slog.d(TAG, "Propagating install state across downgrade");
15374                    }
15375                    for (int userId : allUserHandles) {
15376                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15377                        if (DEBUG_REMOVE) {
15378                            Slog.d(TAG, "    user " + userId + " => " + installed);
15379                        }
15380                        ps.setInstalled(installed, userId);
15381                    }
15382                }
15383            }
15384            // can downgrade to reader
15385            if (writeSettings) {
15386                // Save settings now
15387                mSettings.writeLPr();
15388            }
15389        }
15390        if (outInfo != null) {
15391            // A user ID was deleted here. Go through all users and remove it
15392            // from KeyStore.
15393            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15394        }
15395    }
15396
15397    static boolean locationIsPrivileged(File path) {
15398        try {
15399            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15400                    .getCanonicalPath();
15401            return path.getCanonicalPath().startsWith(privilegedAppDir);
15402        } catch (IOException e) {
15403            Slog.e(TAG, "Unable to access code path " + path);
15404        }
15405        return false;
15406    }
15407
15408    /*
15409     * Tries to delete system package.
15410     */
15411    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15412            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15413            boolean writeSettings) {
15414        if (deletedPs.parentPackageName != null) {
15415            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15416            return false;
15417        }
15418
15419        final boolean applyUserRestrictions
15420                = (allUserHandles != null) && (outInfo.origUsers != null);
15421        final PackageSetting disabledPs;
15422        // Confirm if the system package has been updated
15423        // An updated system app can be deleted. This will also have to restore
15424        // the system pkg from system partition
15425        // reader
15426        synchronized (mPackages) {
15427            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15428        }
15429
15430        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15431                + " disabledPs=" + disabledPs);
15432
15433        if (disabledPs == null) {
15434            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15435            return false;
15436        } else if (DEBUG_REMOVE) {
15437            Slog.d(TAG, "Deleting system pkg from data partition");
15438        }
15439
15440        if (DEBUG_REMOVE) {
15441            if (applyUserRestrictions) {
15442                Slog.d(TAG, "Remembering install states:");
15443                for (int userId : allUserHandles) {
15444                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15445                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15446                }
15447            }
15448        }
15449
15450        // Delete the updated package
15451        outInfo.isRemovedPackageSystemUpdate = true;
15452        if (outInfo.removedChildPackages != null) {
15453            final int childCount = (deletedPs.childPackageNames != null)
15454                    ? deletedPs.childPackageNames.size() : 0;
15455            for (int i = 0; i < childCount; i++) {
15456                String childPackageName = deletedPs.childPackageNames.get(i);
15457                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15458                        .contains(childPackageName)) {
15459                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15460                            childPackageName);
15461                    if (childInfo != null) {
15462                        childInfo.isRemovedPackageSystemUpdate = true;
15463                    }
15464                }
15465            }
15466        }
15467
15468        if (disabledPs.versionCode < deletedPs.versionCode) {
15469            // Delete data for downgrades
15470            flags &= ~PackageManager.DELETE_KEEP_DATA;
15471        } else {
15472            // Preserve data by setting flag
15473            flags |= PackageManager.DELETE_KEEP_DATA;
15474        }
15475
15476        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15477                outInfo, writeSettings, disabledPs.pkg);
15478        if (!ret) {
15479            return false;
15480        }
15481
15482        // writer
15483        synchronized (mPackages) {
15484            // Reinstate the old system package
15485            enableSystemPackageLPw(disabledPs.pkg);
15486            // Remove any native libraries from the upgraded package.
15487            removeNativeBinariesLI(deletedPs);
15488        }
15489
15490        // Install the system package
15491        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15492        int parseFlags = mDefParseFlags
15493                | PackageParser.PARSE_MUST_BE_APK
15494                | PackageParser.PARSE_IS_SYSTEM
15495                | PackageParser.PARSE_IS_SYSTEM_DIR;
15496        if (locationIsPrivileged(disabledPs.codePath)) {
15497            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15498        }
15499
15500        final PackageParser.Package newPkg;
15501        try {
15502            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15503        } catch (PackageManagerException e) {
15504            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15505                    + e.getMessage());
15506            return false;
15507        }
15508
15509        prepareAppDataAfterInstallLIF(newPkg);
15510
15511        // writer
15512        synchronized (mPackages) {
15513            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15514
15515            // Propagate the permissions state as we do not want to drop on the floor
15516            // runtime permissions. The update permissions method below will take
15517            // care of removing obsolete permissions and grant install permissions.
15518            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15519            updatePermissionsLPw(newPkg.packageName, newPkg,
15520                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15521
15522            if (applyUserRestrictions) {
15523                if (DEBUG_REMOVE) {
15524                    Slog.d(TAG, "Propagating install state across reinstall");
15525                }
15526                for (int userId : allUserHandles) {
15527                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15528                    if (DEBUG_REMOVE) {
15529                        Slog.d(TAG, "    user " + userId + " => " + installed);
15530                    }
15531                    ps.setInstalled(installed, userId);
15532
15533                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15534                }
15535                // Regardless of writeSettings we need to ensure that this restriction
15536                // state propagation is persisted
15537                mSettings.writeAllUsersPackageRestrictionsLPr();
15538            }
15539            // can downgrade to reader here
15540            if (writeSettings) {
15541                mSettings.writeLPr();
15542            }
15543        }
15544        return true;
15545    }
15546
15547    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15548            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15549            PackageRemovedInfo outInfo, boolean writeSettings,
15550            PackageParser.Package replacingPackage) {
15551        synchronized (mPackages) {
15552            if (outInfo != null) {
15553                outInfo.uid = ps.appId;
15554            }
15555
15556            if (outInfo != null && outInfo.removedChildPackages != null) {
15557                final int childCount = (ps.childPackageNames != null)
15558                        ? ps.childPackageNames.size() : 0;
15559                for (int i = 0; i < childCount; i++) {
15560                    String childPackageName = ps.childPackageNames.get(i);
15561                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15562                    if (childPs == null) {
15563                        return false;
15564                    }
15565                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15566                            childPackageName);
15567                    if (childInfo != null) {
15568                        childInfo.uid = childPs.appId;
15569                    }
15570                }
15571            }
15572        }
15573
15574        // Delete package data from internal structures and also remove data if flag is set
15575        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15576
15577        // Delete the child packages data
15578        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15579        for (int i = 0; i < childCount; i++) {
15580            PackageSetting childPs;
15581            synchronized (mPackages) {
15582                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15583            }
15584            if (childPs != null) {
15585                PackageRemovedInfo childOutInfo = (outInfo != null
15586                        && outInfo.removedChildPackages != null)
15587                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15588                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15589                        && (replacingPackage != null
15590                        && !replacingPackage.hasChildPackage(childPs.name))
15591                        ? flags & ~DELETE_KEEP_DATA : flags;
15592                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15593                        deleteFlags, writeSettings);
15594            }
15595        }
15596
15597        // Delete application code and resources only for parent packages
15598        if (ps.parentPackageName == null) {
15599            if (deleteCodeAndResources && (outInfo != null)) {
15600                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15601                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15602                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15603            }
15604        }
15605
15606        return true;
15607    }
15608
15609    @Override
15610    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15611            int userId) {
15612        mContext.enforceCallingOrSelfPermission(
15613                android.Manifest.permission.DELETE_PACKAGES, null);
15614        synchronized (mPackages) {
15615            PackageSetting ps = mSettings.mPackages.get(packageName);
15616            if (ps == null) {
15617                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15618                return false;
15619            }
15620            if (!ps.getInstalled(userId)) {
15621                // Can't block uninstall for an app that is not installed or enabled.
15622                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15623                return false;
15624            }
15625            ps.setBlockUninstall(blockUninstall, userId);
15626            mSettings.writePackageRestrictionsLPr(userId);
15627        }
15628        return true;
15629    }
15630
15631    @Override
15632    public boolean getBlockUninstallForUser(String packageName, int userId) {
15633        synchronized (mPackages) {
15634            PackageSetting ps = mSettings.mPackages.get(packageName);
15635            if (ps == null) {
15636                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15637                return false;
15638            }
15639            return ps.getBlockUninstall(userId);
15640        }
15641    }
15642
15643    @Override
15644    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15645        int callingUid = Binder.getCallingUid();
15646        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15647            throw new SecurityException(
15648                    "setRequiredForSystemUser can only be run by the system or root");
15649        }
15650        synchronized (mPackages) {
15651            PackageSetting ps = mSettings.mPackages.get(packageName);
15652            if (ps == null) {
15653                Log.w(TAG, "Package doesn't exist: " + packageName);
15654                return false;
15655            }
15656            if (systemUserApp) {
15657                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15658            } else {
15659                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15660            }
15661            mSettings.writeLPr();
15662        }
15663        return true;
15664    }
15665
15666    /*
15667     * This method handles package deletion in general
15668     */
15669    private boolean deletePackageLIF(String packageName, UserHandle user,
15670            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15671            PackageRemovedInfo outInfo, boolean writeSettings,
15672            PackageParser.Package replacingPackage) {
15673        if (packageName == null) {
15674            Slog.w(TAG, "Attempt to delete null packageName.");
15675            return false;
15676        }
15677
15678        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15679
15680        PackageSetting ps;
15681
15682        synchronized (mPackages) {
15683            ps = mSettings.mPackages.get(packageName);
15684            if (ps == null) {
15685                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15686                return false;
15687            }
15688
15689            if (ps.parentPackageName != null && (!isSystemApp(ps)
15690                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15691                if (DEBUG_REMOVE) {
15692                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15693                            + ((user == null) ? UserHandle.USER_ALL : user));
15694                }
15695                final int removedUserId = (user != null) ? user.getIdentifier()
15696                        : UserHandle.USER_ALL;
15697                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15698                    return false;
15699                }
15700                markPackageUninstalledForUserLPw(ps, user);
15701                scheduleWritePackageRestrictionsLocked(user);
15702                return true;
15703            }
15704        }
15705
15706        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15707                && user.getIdentifier() != UserHandle.USER_ALL)) {
15708            // The caller is asking that the package only be deleted for a single
15709            // user.  To do this, we just mark its uninstalled state and delete
15710            // its data. If this is a system app, we only allow this to happen if
15711            // they have set the special DELETE_SYSTEM_APP which requests different
15712            // semantics than normal for uninstalling system apps.
15713            markPackageUninstalledForUserLPw(ps, user);
15714
15715            if (!isSystemApp(ps)) {
15716                // Do not uninstall the APK if an app should be cached
15717                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15718                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15719                    // Other user still have this package installed, so all
15720                    // we need to do is clear this user's data and save that
15721                    // it is uninstalled.
15722                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15723                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15724                        return false;
15725                    }
15726                    scheduleWritePackageRestrictionsLocked(user);
15727                    return true;
15728                } else {
15729                    // We need to set it back to 'installed' so the uninstall
15730                    // broadcasts will be sent correctly.
15731                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15732                    ps.setInstalled(true, user.getIdentifier());
15733                }
15734            } else {
15735                // This is a system app, so we assume that the
15736                // other users still have this package installed, so all
15737                // we need to do is clear this user's data and save that
15738                // it is uninstalled.
15739                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15740                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15741                    return false;
15742                }
15743                scheduleWritePackageRestrictionsLocked(user);
15744                return true;
15745            }
15746        }
15747
15748        // If we are deleting a composite package for all users, keep track
15749        // of result for each child.
15750        if (ps.childPackageNames != null && outInfo != null) {
15751            synchronized (mPackages) {
15752                final int childCount = ps.childPackageNames.size();
15753                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15754                for (int i = 0; i < childCount; i++) {
15755                    String childPackageName = ps.childPackageNames.get(i);
15756                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15757                    childInfo.removedPackage = childPackageName;
15758                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15759                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15760                    if (childPs != null) {
15761                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15762                    }
15763                }
15764            }
15765        }
15766
15767        boolean ret = false;
15768        if (isSystemApp(ps)) {
15769            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15770            // When an updated system application is deleted we delete the existing resources
15771            // as well and fall back to existing code in system partition
15772            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15773        } else {
15774            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15775            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15776                    outInfo, writeSettings, replacingPackage);
15777        }
15778
15779        // Take a note whether we deleted the package for all users
15780        if (outInfo != null) {
15781            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15782            if (outInfo.removedChildPackages != null) {
15783                synchronized (mPackages) {
15784                    final int childCount = outInfo.removedChildPackages.size();
15785                    for (int i = 0; i < childCount; i++) {
15786                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15787                        if (childInfo != null) {
15788                            childInfo.removedForAllUsers = mPackages.get(
15789                                    childInfo.removedPackage) == null;
15790                        }
15791                    }
15792                }
15793            }
15794            // If we uninstalled an update to a system app there may be some
15795            // child packages that appeared as they are declared in the system
15796            // app but were not declared in the update.
15797            if (isSystemApp(ps)) {
15798                synchronized (mPackages) {
15799                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15800                    final int childCount = (updatedPs.childPackageNames != null)
15801                            ? updatedPs.childPackageNames.size() : 0;
15802                    for (int i = 0; i < childCount; i++) {
15803                        String childPackageName = updatedPs.childPackageNames.get(i);
15804                        if (outInfo.removedChildPackages == null
15805                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15806                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15807                            if (childPs == null) {
15808                                continue;
15809                            }
15810                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15811                            installRes.name = childPackageName;
15812                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15813                            installRes.pkg = mPackages.get(childPackageName);
15814                            installRes.uid = childPs.pkg.applicationInfo.uid;
15815                            if (outInfo.appearedChildPackages == null) {
15816                                outInfo.appearedChildPackages = new ArrayMap<>();
15817                            }
15818                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15819                        }
15820                    }
15821                }
15822            }
15823        }
15824
15825        return ret;
15826    }
15827
15828    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15829        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15830                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15831        for (int nextUserId : userIds) {
15832            if (DEBUG_REMOVE) {
15833                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15834            }
15835            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15836                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15837                    false /*hidden*/, false /*suspended*/, null, null, null,
15838                    false /*blockUninstall*/,
15839                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15840        }
15841    }
15842
15843    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15844            PackageRemovedInfo outInfo) {
15845        final PackageParser.Package pkg;
15846        synchronized (mPackages) {
15847            pkg = mPackages.get(ps.name);
15848        }
15849
15850        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15851                : new int[] {userId};
15852        for (int nextUserId : userIds) {
15853            if (DEBUG_REMOVE) {
15854                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15855                        + nextUserId);
15856            }
15857
15858            destroyAppDataLIF(pkg, userId,
15859                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15860            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15861            schedulePackageCleaning(ps.name, nextUserId, false);
15862            synchronized (mPackages) {
15863                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15864                    scheduleWritePackageRestrictionsLocked(nextUserId);
15865                }
15866                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15867            }
15868        }
15869
15870        if (outInfo != null) {
15871            outInfo.removedPackage = ps.name;
15872            outInfo.removedAppId = ps.appId;
15873            outInfo.removedUsers = userIds;
15874        }
15875
15876        return true;
15877    }
15878
15879    private final class ClearStorageConnection implements ServiceConnection {
15880        IMediaContainerService mContainerService;
15881
15882        @Override
15883        public void onServiceConnected(ComponentName name, IBinder service) {
15884            synchronized (this) {
15885                mContainerService = IMediaContainerService.Stub.asInterface(service);
15886                notifyAll();
15887            }
15888        }
15889
15890        @Override
15891        public void onServiceDisconnected(ComponentName name) {
15892        }
15893    }
15894
15895    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15896        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15897
15898        final boolean mounted;
15899        if (Environment.isExternalStorageEmulated()) {
15900            mounted = true;
15901        } else {
15902            final String status = Environment.getExternalStorageState();
15903
15904            mounted = status.equals(Environment.MEDIA_MOUNTED)
15905                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15906        }
15907
15908        if (!mounted) {
15909            return;
15910        }
15911
15912        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15913        int[] users;
15914        if (userId == UserHandle.USER_ALL) {
15915            users = sUserManager.getUserIds();
15916        } else {
15917            users = new int[] { userId };
15918        }
15919        final ClearStorageConnection conn = new ClearStorageConnection();
15920        if (mContext.bindServiceAsUser(
15921                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15922            try {
15923                for (int curUser : users) {
15924                    long timeout = SystemClock.uptimeMillis() + 5000;
15925                    synchronized (conn) {
15926                        long now = SystemClock.uptimeMillis();
15927                        while (conn.mContainerService == null && now < timeout) {
15928                            try {
15929                                conn.wait(timeout - now);
15930                            } catch (InterruptedException e) {
15931                            }
15932                        }
15933                    }
15934                    if (conn.mContainerService == null) {
15935                        return;
15936                    }
15937
15938                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15939                    clearDirectory(conn.mContainerService,
15940                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15941                    if (allData) {
15942                        clearDirectory(conn.mContainerService,
15943                                userEnv.buildExternalStorageAppDataDirs(packageName));
15944                        clearDirectory(conn.mContainerService,
15945                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15946                    }
15947                }
15948            } finally {
15949                mContext.unbindService(conn);
15950            }
15951        }
15952    }
15953
15954    @Override
15955    public void clearApplicationProfileData(String packageName) {
15956        enforceSystemOrRoot("Only the system can clear all profile data");
15957
15958        final PackageParser.Package pkg;
15959        synchronized (mPackages) {
15960            pkg = mPackages.get(packageName);
15961        }
15962
15963        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15964            synchronized (mInstallLock) {
15965                clearAppProfilesLIF(pkg);
15966            }
15967        }
15968    }
15969
15970    @Override
15971    public void clearApplicationUserData(final String packageName,
15972            final IPackageDataObserver observer, final int userId) {
15973        mContext.enforceCallingOrSelfPermission(
15974                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15975
15976        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15977                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15978
15979        final DevicePolicyManagerInternal dpmi = LocalServices
15980                .getService(DevicePolicyManagerInternal.class);
15981        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15982            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15983        }
15984        // Queue up an async operation since the package deletion may take a little while.
15985        mHandler.post(new Runnable() {
15986            public void run() {
15987                mHandler.removeCallbacks(this);
15988                final boolean succeeded;
15989                try (PackageFreezer freezer = freezePackage(packageName,
15990                        "clearApplicationUserData")) {
15991                    synchronized (mInstallLock) {
15992                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15993                    }
15994                    clearExternalStorageDataSync(packageName, userId, true);
15995                }
15996                if (succeeded) {
15997                    // invoke DeviceStorageMonitor's update method to clear any notifications
15998                    DeviceStorageMonitorInternal dsm = LocalServices
15999                            .getService(DeviceStorageMonitorInternal.class);
16000                    if (dsm != null) {
16001                        dsm.checkMemory();
16002                    }
16003                }
16004                if(observer != null) {
16005                    try {
16006                        observer.onRemoveCompleted(packageName, succeeded);
16007                    } catch (RemoteException e) {
16008                        Log.i(TAG, "Observer no longer exists.");
16009                    }
16010                } //end if observer
16011            } //end run
16012        });
16013    }
16014
16015    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16016        if (packageName == null) {
16017            Slog.w(TAG, "Attempt to delete null packageName.");
16018            return false;
16019        }
16020
16021        // Try finding details about the requested package
16022        PackageParser.Package pkg;
16023        synchronized (mPackages) {
16024            pkg = mPackages.get(packageName);
16025            if (pkg == null) {
16026                final PackageSetting ps = mSettings.mPackages.get(packageName);
16027                if (ps != null) {
16028                    pkg = ps.pkg;
16029                }
16030            }
16031
16032            if (pkg == null) {
16033                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16034                return false;
16035            }
16036
16037            PackageSetting ps = (PackageSetting) pkg.mExtras;
16038            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16039        }
16040
16041        clearAppDataLIF(pkg, userId,
16042                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16043
16044        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16045        removeKeystoreDataIfNeeded(userId, appId);
16046
16047        final UserManager um = mContext.getSystemService(UserManager.class);
16048        final int flags;
16049        if (um.isUserUnlocked(userId)) {
16050            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16051        } else if (um.isUserRunning(userId)) {
16052            flags = StorageManager.FLAG_STORAGE_DE;
16053        } else {
16054            flags = 0;
16055        }
16056        prepareAppDataContentsLIF(pkg, userId, flags);
16057
16058        return true;
16059    }
16060
16061    /**
16062     * Reverts user permission state changes (permissions and flags) in
16063     * all packages for a given user.
16064     *
16065     * @param userId The device user for which to do a reset.
16066     */
16067    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16068        final int packageCount = mPackages.size();
16069        for (int i = 0; i < packageCount; i++) {
16070            PackageParser.Package pkg = mPackages.valueAt(i);
16071            PackageSetting ps = (PackageSetting) pkg.mExtras;
16072            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16073        }
16074    }
16075
16076    /**
16077     * Reverts user permission state changes (permissions and flags).
16078     *
16079     * @param ps The package for which to reset.
16080     * @param userId The device user for which to do a reset.
16081     */
16082    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16083            final PackageSetting ps, final int userId) {
16084        if (ps.pkg == null) {
16085            return;
16086        }
16087
16088        // These are flags that can change base on user actions.
16089        final int userSettableMask = FLAG_PERMISSION_USER_SET
16090                | FLAG_PERMISSION_USER_FIXED
16091                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16092                | FLAG_PERMISSION_REVIEW_REQUIRED;
16093
16094        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16095                | FLAG_PERMISSION_POLICY_FIXED;
16096
16097        boolean writeInstallPermissions = false;
16098        boolean writeRuntimePermissions = false;
16099
16100        final int permissionCount = ps.pkg.requestedPermissions.size();
16101        for (int i = 0; i < permissionCount; i++) {
16102            String permission = ps.pkg.requestedPermissions.get(i);
16103
16104            BasePermission bp = mSettings.mPermissions.get(permission);
16105            if (bp == null) {
16106                continue;
16107            }
16108
16109            // If shared user we just reset the state to which only this app contributed.
16110            if (ps.sharedUser != null) {
16111                boolean used = false;
16112                final int packageCount = ps.sharedUser.packages.size();
16113                for (int j = 0; j < packageCount; j++) {
16114                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16115                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16116                            && pkg.pkg.requestedPermissions.contains(permission)) {
16117                        used = true;
16118                        break;
16119                    }
16120                }
16121                if (used) {
16122                    continue;
16123                }
16124            }
16125
16126            PermissionsState permissionsState = ps.getPermissionsState();
16127
16128            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16129
16130            // Always clear the user settable flags.
16131            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16132                    bp.name) != null;
16133            // If permission review is enabled and this is a legacy app, mark the
16134            // permission as requiring a review as this is the initial state.
16135            int flags = 0;
16136            if (Build.PERMISSIONS_REVIEW_REQUIRED
16137                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16138                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16139            }
16140            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16141                if (hasInstallState) {
16142                    writeInstallPermissions = true;
16143                } else {
16144                    writeRuntimePermissions = true;
16145                }
16146            }
16147
16148            // Below is only runtime permission handling.
16149            if (!bp.isRuntime()) {
16150                continue;
16151            }
16152
16153            // Never clobber system or policy.
16154            if ((oldFlags & policyOrSystemFlags) != 0) {
16155                continue;
16156            }
16157
16158            // If this permission was granted by default, make sure it is.
16159            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16160                if (permissionsState.grantRuntimePermission(bp, userId)
16161                        != PERMISSION_OPERATION_FAILURE) {
16162                    writeRuntimePermissions = true;
16163                }
16164            // If permission review is enabled the permissions for a legacy apps
16165            // are represented as constantly granted runtime ones, so don't revoke.
16166            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16167                // Otherwise, reset the permission.
16168                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16169                switch (revokeResult) {
16170                    case PERMISSION_OPERATION_SUCCESS:
16171                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16172                        writeRuntimePermissions = true;
16173                        final int appId = ps.appId;
16174                        mHandler.post(new Runnable() {
16175                            @Override
16176                            public void run() {
16177                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16178                            }
16179                        });
16180                    } break;
16181                }
16182            }
16183        }
16184
16185        // Synchronously write as we are taking permissions away.
16186        if (writeRuntimePermissions) {
16187            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16188        }
16189
16190        // Synchronously write as we are taking permissions away.
16191        if (writeInstallPermissions) {
16192            mSettings.writeLPr();
16193        }
16194    }
16195
16196    /**
16197     * Remove entries from the keystore daemon. Will only remove it if the
16198     * {@code appId} is valid.
16199     */
16200    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16201        if (appId < 0) {
16202            return;
16203        }
16204
16205        final KeyStore keyStore = KeyStore.getInstance();
16206        if (keyStore != null) {
16207            if (userId == UserHandle.USER_ALL) {
16208                for (final int individual : sUserManager.getUserIds()) {
16209                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16210                }
16211            } else {
16212                keyStore.clearUid(UserHandle.getUid(userId, appId));
16213            }
16214        } else {
16215            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16216        }
16217    }
16218
16219    @Override
16220    public void deleteApplicationCacheFiles(final String packageName,
16221            final IPackageDataObserver observer) {
16222        final int userId = UserHandle.getCallingUserId();
16223        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16224    }
16225
16226    @Override
16227    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16228            final IPackageDataObserver observer) {
16229        mContext.enforceCallingOrSelfPermission(
16230                android.Manifest.permission.DELETE_CACHE_FILES, null);
16231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16232                /* requireFullPermission= */ true, /* checkShell= */ false,
16233                "delete application cache files");
16234
16235        final PackageParser.Package pkg;
16236        synchronized (mPackages) {
16237            pkg = mPackages.get(packageName);
16238        }
16239
16240        // Queue up an async operation since the package deletion may take a little while.
16241        mHandler.post(new Runnable() {
16242            public void run() {
16243                synchronized (mInstallLock) {
16244                    final int flags = StorageManager.FLAG_STORAGE_DE
16245                            | StorageManager.FLAG_STORAGE_CE;
16246                    // We're only clearing cache files, so we don't care if the
16247                    // app is unfrozen and still able to run
16248                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16249                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16250                }
16251                clearExternalStorageDataSync(packageName, userId, false);
16252                if (observer != null) {
16253                    try {
16254                        observer.onRemoveCompleted(packageName, true);
16255                    } catch (RemoteException e) {
16256                        Log.i(TAG, "Observer no longer exists.");
16257                    }
16258                }
16259            }
16260        });
16261    }
16262
16263    @Override
16264    public void getPackageSizeInfo(final String packageName, int userHandle,
16265            final IPackageStatsObserver observer) {
16266        mContext.enforceCallingOrSelfPermission(
16267                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16268        if (packageName == null) {
16269            throw new IllegalArgumentException("Attempt to get size of null packageName");
16270        }
16271
16272        PackageStats stats = new PackageStats(packageName, userHandle);
16273
16274        /*
16275         * Queue up an async operation since the package measurement may take a
16276         * little while.
16277         */
16278        Message msg = mHandler.obtainMessage(INIT_COPY);
16279        msg.obj = new MeasureParams(stats, observer);
16280        mHandler.sendMessage(msg);
16281    }
16282
16283    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16284        final PackageSetting ps;
16285        synchronized (mPackages) {
16286            ps = mSettings.mPackages.get(packageName);
16287            if (ps == null) {
16288                Slog.w(TAG, "Failed to find settings for " + packageName);
16289                return false;
16290            }
16291        }
16292        try {
16293            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16294                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16295                    ps.getCeDataInode(userId), ps.codePathString, stats);
16296        } catch (InstallerException e) {
16297            Slog.w(TAG, String.valueOf(e));
16298            return false;
16299        }
16300
16301        // For now, ignore code size of packages on system partition
16302        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16303            stats.codeSize = 0;
16304        }
16305
16306        return true;
16307    }
16308
16309    private int getUidTargetSdkVersionLockedLPr(int uid) {
16310        Object obj = mSettings.getUserIdLPr(uid);
16311        if (obj instanceof SharedUserSetting) {
16312            final SharedUserSetting sus = (SharedUserSetting) obj;
16313            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16314            final Iterator<PackageSetting> it = sus.packages.iterator();
16315            while (it.hasNext()) {
16316                final PackageSetting ps = it.next();
16317                if (ps.pkg != null) {
16318                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16319                    if (v < vers) vers = v;
16320                }
16321            }
16322            return vers;
16323        } else if (obj instanceof PackageSetting) {
16324            final PackageSetting ps = (PackageSetting) obj;
16325            if (ps.pkg != null) {
16326                return ps.pkg.applicationInfo.targetSdkVersion;
16327            }
16328        }
16329        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16330    }
16331
16332    @Override
16333    public void addPreferredActivity(IntentFilter filter, int match,
16334            ComponentName[] set, ComponentName activity, int userId) {
16335        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16336                "Adding preferred");
16337    }
16338
16339    private void addPreferredActivityInternal(IntentFilter filter, int match,
16340            ComponentName[] set, ComponentName activity, boolean always, int userId,
16341            String opname) {
16342        // writer
16343        int callingUid = Binder.getCallingUid();
16344        enforceCrossUserPermission(callingUid, userId,
16345                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16346        if (filter.countActions() == 0) {
16347            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16348            return;
16349        }
16350        synchronized (mPackages) {
16351            if (mContext.checkCallingOrSelfPermission(
16352                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16353                    != PackageManager.PERMISSION_GRANTED) {
16354                if (getUidTargetSdkVersionLockedLPr(callingUid)
16355                        < Build.VERSION_CODES.FROYO) {
16356                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16357                            + callingUid);
16358                    return;
16359                }
16360                mContext.enforceCallingOrSelfPermission(
16361                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16362            }
16363
16364            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16365            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16366                    + userId + ":");
16367            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16368            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16369            scheduleWritePackageRestrictionsLocked(userId);
16370        }
16371    }
16372
16373    @Override
16374    public void replacePreferredActivity(IntentFilter filter, int match,
16375            ComponentName[] set, ComponentName activity, int userId) {
16376        if (filter.countActions() != 1) {
16377            throw new IllegalArgumentException(
16378                    "replacePreferredActivity expects filter to have only 1 action.");
16379        }
16380        if (filter.countDataAuthorities() != 0
16381                || filter.countDataPaths() != 0
16382                || filter.countDataSchemes() > 1
16383                || filter.countDataTypes() != 0) {
16384            throw new IllegalArgumentException(
16385                    "replacePreferredActivity expects filter to have no data authorities, " +
16386                    "paths, or types; and at most one scheme.");
16387        }
16388
16389        final int callingUid = Binder.getCallingUid();
16390        enforceCrossUserPermission(callingUid, userId,
16391                true /* requireFullPermission */, false /* checkShell */,
16392                "replace preferred activity");
16393        synchronized (mPackages) {
16394            if (mContext.checkCallingOrSelfPermission(
16395                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16396                    != PackageManager.PERMISSION_GRANTED) {
16397                if (getUidTargetSdkVersionLockedLPr(callingUid)
16398                        < Build.VERSION_CODES.FROYO) {
16399                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16400                            + Binder.getCallingUid());
16401                    return;
16402                }
16403                mContext.enforceCallingOrSelfPermission(
16404                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16405            }
16406
16407            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16408            if (pir != null) {
16409                // Get all of the existing entries that exactly match this filter.
16410                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16411                if (existing != null && existing.size() == 1) {
16412                    PreferredActivity cur = existing.get(0);
16413                    if (DEBUG_PREFERRED) {
16414                        Slog.i(TAG, "Checking replace of preferred:");
16415                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16416                        if (!cur.mPref.mAlways) {
16417                            Slog.i(TAG, "  -- CUR; not mAlways!");
16418                        } else {
16419                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16420                            Slog.i(TAG, "  -- CUR: mSet="
16421                                    + Arrays.toString(cur.mPref.mSetComponents));
16422                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16423                            Slog.i(TAG, "  -- NEW: mMatch="
16424                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16425                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16426                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16427                        }
16428                    }
16429                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16430                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16431                            && cur.mPref.sameSet(set)) {
16432                        // Setting the preferred activity to what it happens to be already
16433                        if (DEBUG_PREFERRED) {
16434                            Slog.i(TAG, "Replacing with same preferred activity "
16435                                    + cur.mPref.mShortComponent + " for user "
16436                                    + userId + ":");
16437                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16438                        }
16439                        return;
16440                    }
16441                }
16442
16443                if (existing != null) {
16444                    if (DEBUG_PREFERRED) {
16445                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16446                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16447                    }
16448                    for (int i = 0; i < existing.size(); i++) {
16449                        PreferredActivity pa = existing.get(i);
16450                        if (DEBUG_PREFERRED) {
16451                            Slog.i(TAG, "Removing existing preferred activity "
16452                                    + pa.mPref.mComponent + ":");
16453                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16454                        }
16455                        pir.removeFilter(pa);
16456                    }
16457                }
16458            }
16459            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16460                    "Replacing preferred");
16461        }
16462    }
16463
16464    @Override
16465    public void clearPackagePreferredActivities(String packageName) {
16466        final int uid = Binder.getCallingUid();
16467        // writer
16468        synchronized (mPackages) {
16469            PackageParser.Package pkg = mPackages.get(packageName);
16470            if (pkg == null || pkg.applicationInfo.uid != uid) {
16471                if (mContext.checkCallingOrSelfPermission(
16472                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16473                        != PackageManager.PERMISSION_GRANTED) {
16474                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16475                            < Build.VERSION_CODES.FROYO) {
16476                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16477                                + Binder.getCallingUid());
16478                        return;
16479                    }
16480                    mContext.enforceCallingOrSelfPermission(
16481                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16482                }
16483            }
16484
16485            int user = UserHandle.getCallingUserId();
16486            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16487                scheduleWritePackageRestrictionsLocked(user);
16488            }
16489        }
16490    }
16491
16492    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16493    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16494        ArrayList<PreferredActivity> removed = null;
16495        boolean changed = false;
16496        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16497            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16498            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16499            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16500                continue;
16501            }
16502            Iterator<PreferredActivity> it = pir.filterIterator();
16503            while (it.hasNext()) {
16504                PreferredActivity pa = it.next();
16505                // Mark entry for removal only if it matches the package name
16506                // and the entry is of type "always".
16507                if (packageName == null ||
16508                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16509                                && pa.mPref.mAlways)) {
16510                    if (removed == null) {
16511                        removed = new ArrayList<PreferredActivity>();
16512                    }
16513                    removed.add(pa);
16514                }
16515            }
16516            if (removed != null) {
16517                for (int j=0; j<removed.size(); j++) {
16518                    PreferredActivity pa = removed.get(j);
16519                    pir.removeFilter(pa);
16520                }
16521                changed = true;
16522            }
16523        }
16524        return changed;
16525    }
16526
16527    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16528    private void clearIntentFilterVerificationsLPw(int userId) {
16529        final int packageCount = mPackages.size();
16530        for (int i = 0; i < packageCount; i++) {
16531            PackageParser.Package pkg = mPackages.valueAt(i);
16532            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16533        }
16534    }
16535
16536    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16537    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16538        if (userId == UserHandle.USER_ALL) {
16539            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16540                    sUserManager.getUserIds())) {
16541                for (int oneUserId : sUserManager.getUserIds()) {
16542                    scheduleWritePackageRestrictionsLocked(oneUserId);
16543                }
16544            }
16545        } else {
16546            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16547                scheduleWritePackageRestrictionsLocked(userId);
16548            }
16549        }
16550    }
16551
16552    void clearDefaultBrowserIfNeeded(String packageName) {
16553        for (int oneUserId : sUserManager.getUserIds()) {
16554            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16555            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16556            if (packageName.equals(defaultBrowserPackageName)) {
16557                setDefaultBrowserPackageName(null, oneUserId);
16558            }
16559        }
16560    }
16561
16562    @Override
16563    public void resetApplicationPreferences(int userId) {
16564        mContext.enforceCallingOrSelfPermission(
16565                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16566        // writer
16567        synchronized (mPackages) {
16568            final long identity = Binder.clearCallingIdentity();
16569            try {
16570                clearPackagePreferredActivitiesLPw(null, userId);
16571                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16572                // TODO: We have to reset the default SMS and Phone. This requires
16573                // significant refactoring to keep all default apps in the package
16574                // manager (cleaner but more work) or have the services provide
16575                // callbacks to the package manager to request a default app reset.
16576                applyFactoryDefaultBrowserLPw(userId);
16577                clearIntentFilterVerificationsLPw(userId);
16578                primeDomainVerificationsLPw(userId);
16579                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16580                scheduleWritePackageRestrictionsLocked(userId);
16581            } finally {
16582                Binder.restoreCallingIdentity(identity);
16583            }
16584        }
16585    }
16586
16587    @Override
16588    public int getPreferredActivities(List<IntentFilter> outFilters,
16589            List<ComponentName> outActivities, String packageName) {
16590
16591        int num = 0;
16592        final int userId = UserHandle.getCallingUserId();
16593        // reader
16594        synchronized (mPackages) {
16595            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16596            if (pir != null) {
16597                final Iterator<PreferredActivity> it = pir.filterIterator();
16598                while (it.hasNext()) {
16599                    final PreferredActivity pa = it.next();
16600                    if (packageName == null
16601                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16602                                    && pa.mPref.mAlways)) {
16603                        if (outFilters != null) {
16604                            outFilters.add(new IntentFilter(pa));
16605                        }
16606                        if (outActivities != null) {
16607                            outActivities.add(pa.mPref.mComponent);
16608                        }
16609                    }
16610                }
16611            }
16612        }
16613
16614        return num;
16615    }
16616
16617    @Override
16618    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16619            int userId) {
16620        int callingUid = Binder.getCallingUid();
16621        if (callingUid != Process.SYSTEM_UID) {
16622            throw new SecurityException(
16623                    "addPersistentPreferredActivity can only be run by the system");
16624        }
16625        if (filter.countActions() == 0) {
16626            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16627            return;
16628        }
16629        synchronized (mPackages) {
16630            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16631                    ":");
16632            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16633            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16634                    new PersistentPreferredActivity(filter, activity));
16635            scheduleWritePackageRestrictionsLocked(userId);
16636        }
16637    }
16638
16639    @Override
16640    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16641        int callingUid = Binder.getCallingUid();
16642        if (callingUid != Process.SYSTEM_UID) {
16643            throw new SecurityException(
16644                    "clearPackagePersistentPreferredActivities can only be run by the system");
16645        }
16646        ArrayList<PersistentPreferredActivity> removed = null;
16647        boolean changed = false;
16648        synchronized (mPackages) {
16649            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16650                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16651                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16652                        .valueAt(i);
16653                if (userId != thisUserId) {
16654                    continue;
16655                }
16656                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16657                while (it.hasNext()) {
16658                    PersistentPreferredActivity ppa = it.next();
16659                    // Mark entry for removal only if it matches the package name.
16660                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16661                        if (removed == null) {
16662                            removed = new ArrayList<PersistentPreferredActivity>();
16663                        }
16664                        removed.add(ppa);
16665                    }
16666                }
16667                if (removed != null) {
16668                    for (int j=0; j<removed.size(); j++) {
16669                        PersistentPreferredActivity ppa = removed.get(j);
16670                        ppir.removeFilter(ppa);
16671                    }
16672                    changed = true;
16673                }
16674            }
16675
16676            if (changed) {
16677                scheduleWritePackageRestrictionsLocked(userId);
16678            }
16679        }
16680    }
16681
16682    /**
16683     * Common machinery for picking apart a restored XML blob and passing
16684     * it to a caller-supplied functor to be applied to the running system.
16685     */
16686    private void restoreFromXml(XmlPullParser parser, int userId,
16687            String expectedStartTag, BlobXmlRestorer functor)
16688            throws IOException, XmlPullParserException {
16689        int type;
16690        while ((type = parser.next()) != XmlPullParser.START_TAG
16691                && type != XmlPullParser.END_DOCUMENT) {
16692        }
16693        if (type != XmlPullParser.START_TAG) {
16694            // oops didn't find a start tag?!
16695            if (DEBUG_BACKUP) {
16696                Slog.e(TAG, "Didn't find start tag during restore");
16697            }
16698            return;
16699        }
16700Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16701        // this is supposed to be TAG_PREFERRED_BACKUP
16702        if (!expectedStartTag.equals(parser.getName())) {
16703            if (DEBUG_BACKUP) {
16704                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16705            }
16706            return;
16707        }
16708
16709        // skip interfering stuff, then we're aligned with the backing implementation
16710        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16711Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16712        functor.apply(parser, userId);
16713    }
16714
16715    private interface BlobXmlRestorer {
16716        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16717    }
16718
16719    /**
16720     * Non-Binder method, support for the backup/restore mechanism: write the
16721     * full set of preferred activities in its canonical XML format.  Returns the
16722     * XML output as a byte array, or null if there is none.
16723     */
16724    @Override
16725    public byte[] getPreferredActivityBackup(int userId) {
16726        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16727            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16728        }
16729
16730        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16731        try {
16732            final XmlSerializer serializer = new FastXmlSerializer();
16733            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16734            serializer.startDocument(null, true);
16735            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16736
16737            synchronized (mPackages) {
16738                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16739            }
16740
16741            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16742            serializer.endDocument();
16743            serializer.flush();
16744        } catch (Exception e) {
16745            if (DEBUG_BACKUP) {
16746                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16747            }
16748            return null;
16749        }
16750
16751        return dataStream.toByteArray();
16752    }
16753
16754    @Override
16755    public void restorePreferredActivities(byte[] backup, int userId) {
16756        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16757            throw new SecurityException("Only the system may call restorePreferredActivities()");
16758        }
16759
16760        try {
16761            final XmlPullParser parser = Xml.newPullParser();
16762            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16763            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16764                    new BlobXmlRestorer() {
16765                        @Override
16766                        public void apply(XmlPullParser parser, int userId)
16767                                throws XmlPullParserException, IOException {
16768                            synchronized (mPackages) {
16769                                mSettings.readPreferredActivitiesLPw(parser, userId);
16770                            }
16771                        }
16772                    } );
16773        } catch (Exception e) {
16774            if (DEBUG_BACKUP) {
16775                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16776            }
16777        }
16778    }
16779
16780    /**
16781     * Non-Binder method, support for the backup/restore mechanism: write the
16782     * default browser (etc) settings in its canonical XML format.  Returns the default
16783     * browser XML representation as a byte array, or null if there is none.
16784     */
16785    @Override
16786    public byte[] getDefaultAppsBackup(int userId) {
16787        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16788            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16789        }
16790
16791        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16792        try {
16793            final XmlSerializer serializer = new FastXmlSerializer();
16794            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16795            serializer.startDocument(null, true);
16796            serializer.startTag(null, TAG_DEFAULT_APPS);
16797
16798            synchronized (mPackages) {
16799                mSettings.writeDefaultAppsLPr(serializer, userId);
16800            }
16801
16802            serializer.endTag(null, TAG_DEFAULT_APPS);
16803            serializer.endDocument();
16804            serializer.flush();
16805        } catch (Exception e) {
16806            if (DEBUG_BACKUP) {
16807                Slog.e(TAG, "Unable to write default apps for backup", e);
16808            }
16809            return null;
16810        }
16811
16812        return dataStream.toByteArray();
16813    }
16814
16815    @Override
16816    public void restoreDefaultApps(byte[] backup, int userId) {
16817        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16818            throw new SecurityException("Only the system may call restoreDefaultApps()");
16819        }
16820
16821        try {
16822            final XmlPullParser parser = Xml.newPullParser();
16823            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16824            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16825                    new BlobXmlRestorer() {
16826                        @Override
16827                        public void apply(XmlPullParser parser, int userId)
16828                                throws XmlPullParserException, IOException {
16829                            synchronized (mPackages) {
16830                                mSettings.readDefaultAppsLPw(parser, userId);
16831                            }
16832                        }
16833                    } );
16834        } catch (Exception e) {
16835            if (DEBUG_BACKUP) {
16836                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16837            }
16838        }
16839    }
16840
16841    @Override
16842    public byte[] getIntentFilterVerificationBackup(int userId) {
16843        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16844            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16845        }
16846
16847        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16848        try {
16849            final XmlSerializer serializer = new FastXmlSerializer();
16850            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16851            serializer.startDocument(null, true);
16852            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16853
16854            synchronized (mPackages) {
16855                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16856            }
16857
16858            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16859            serializer.endDocument();
16860            serializer.flush();
16861        } catch (Exception e) {
16862            if (DEBUG_BACKUP) {
16863                Slog.e(TAG, "Unable to write default apps for backup", e);
16864            }
16865            return null;
16866        }
16867
16868        return dataStream.toByteArray();
16869    }
16870
16871    @Override
16872    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16874            throw new SecurityException("Only the system may call restorePreferredActivities()");
16875        }
16876
16877        try {
16878            final XmlPullParser parser = Xml.newPullParser();
16879            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16880            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16881                    new BlobXmlRestorer() {
16882                        @Override
16883                        public void apply(XmlPullParser parser, int userId)
16884                                throws XmlPullParserException, IOException {
16885                            synchronized (mPackages) {
16886                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16887                                mSettings.writeLPr();
16888                            }
16889                        }
16890                    } );
16891        } catch (Exception e) {
16892            if (DEBUG_BACKUP) {
16893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16894            }
16895        }
16896    }
16897
16898    @Override
16899    public byte[] getPermissionGrantBackup(int userId) {
16900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16901            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16902        }
16903
16904        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16905        try {
16906            final XmlSerializer serializer = new FastXmlSerializer();
16907            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16908            serializer.startDocument(null, true);
16909            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16910
16911            synchronized (mPackages) {
16912                serializeRuntimePermissionGrantsLPr(serializer, userId);
16913            }
16914
16915            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16916            serializer.endDocument();
16917            serializer.flush();
16918        } catch (Exception e) {
16919            if (DEBUG_BACKUP) {
16920                Slog.e(TAG, "Unable to write default apps for backup", e);
16921            }
16922            return null;
16923        }
16924
16925        return dataStream.toByteArray();
16926    }
16927
16928    @Override
16929    public void restorePermissionGrants(byte[] backup, int userId) {
16930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16931            throw new SecurityException("Only the system may call restorePermissionGrants()");
16932        }
16933
16934        try {
16935            final XmlPullParser parser = Xml.newPullParser();
16936            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16937            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16938                    new BlobXmlRestorer() {
16939                        @Override
16940                        public void apply(XmlPullParser parser, int userId)
16941                                throws XmlPullParserException, IOException {
16942                            synchronized (mPackages) {
16943                                processRestoredPermissionGrantsLPr(parser, userId);
16944                            }
16945                        }
16946                    } );
16947        } catch (Exception e) {
16948            if (DEBUG_BACKUP) {
16949                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16950            }
16951        }
16952    }
16953
16954    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16955            throws IOException {
16956        serializer.startTag(null, TAG_ALL_GRANTS);
16957
16958        final int N = mSettings.mPackages.size();
16959        for (int i = 0; i < N; i++) {
16960            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16961            boolean pkgGrantsKnown = false;
16962
16963            PermissionsState packagePerms = ps.getPermissionsState();
16964
16965            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16966                final int grantFlags = state.getFlags();
16967                // only look at grants that are not system/policy fixed
16968                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16969                    final boolean isGranted = state.isGranted();
16970                    // And only back up the user-twiddled state bits
16971                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16972                        final String packageName = mSettings.mPackages.keyAt(i);
16973                        if (!pkgGrantsKnown) {
16974                            serializer.startTag(null, TAG_GRANT);
16975                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16976                            pkgGrantsKnown = true;
16977                        }
16978
16979                        final boolean userSet =
16980                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16981                        final boolean userFixed =
16982                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16983                        final boolean revoke =
16984                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16985
16986                        serializer.startTag(null, TAG_PERMISSION);
16987                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16988                        if (isGranted) {
16989                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16990                        }
16991                        if (userSet) {
16992                            serializer.attribute(null, ATTR_USER_SET, "true");
16993                        }
16994                        if (userFixed) {
16995                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16996                        }
16997                        if (revoke) {
16998                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16999                        }
17000                        serializer.endTag(null, TAG_PERMISSION);
17001                    }
17002                }
17003            }
17004
17005            if (pkgGrantsKnown) {
17006                serializer.endTag(null, TAG_GRANT);
17007            }
17008        }
17009
17010        serializer.endTag(null, TAG_ALL_GRANTS);
17011    }
17012
17013    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17014            throws XmlPullParserException, IOException {
17015        String pkgName = null;
17016        int outerDepth = parser.getDepth();
17017        int type;
17018        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17019                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17020            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17021                continue;
17022            }
17023
17024            final String tagName = parser.getName();
17025            if (tagName.equals(TAG_GRANT)) {
17026                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17027                if (DEBUG_BACKUP) {
17028                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17029                }
17030            } else if (tagName.equals(TAG_PERMISSION)) {
17031
17032                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17033                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17034
17035                int newFlagSet = 0;
17036                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17037                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17038                }
17039                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17040                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17041                }
17042                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17043                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17044                }
17045                if (DEBUG_BACKUP) {
17046                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17047                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17048                }
17049                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17050                if (ps != null) {
17051                    // Already installed so we apply the grant immediately
17052                    if (DEBUG_BACKUP) {
17053                        Slog.v(TAG, "        + already installed; applying");
17054                    }
17055                    PermissionsState perms = ps.getPermissionsState();
17056                    BasePermission bp = mSettings.mPermissions.get(permName);
17057                    if (bp != null) {
17058                        if (isGranted) {
17059                            perms.grantRuntimePermission(bp, userId);
17060                        }
17061                        if (newFlagSet != 0) {
17062                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17063                        }
17064                    }
17065                } else {
17066                    // Need to wait for post-restore install to apply the grant
17067                    if (DEBUG_BACKUP) {
17068                        Slog.v(TAG, "        - not yet installed; saving for later");
17069                    }
17070                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17071                            isGranted, newFlagSet, userId);
17072                }
17073            } else {
17074                PackageManagerService.reportSettingsProblem(Log.WARN,
17075                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17076                XmlUtils.skipCurrentTag(parser);
17077            }
17078        }
17079
17080        scheduleWriteSettingsLocked();
17081        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17082    }
17083
17084    @Override
17085    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17086            int sourceUserId, int targetUserId, int flags) {
17087        mContext.enforceCallingOrSelfPermission(
17088                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17089        int callingUid = Binder.getCallingUid();
17090        enforceOwnerRights(ownerPackage, callingUid);
17091        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17092        if (intentFilter.countActions() == 0) {
17093            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17094            return;
17095        }
17096        synchronized (mPackages) {
17097            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17098                    ownerPackage, targetUserId, flags);
17099            CrossProfileIntentResolver resolver =
17100                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17101            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17102            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17103            if (existing != null) {
17104                int size = existing.size();
17105                for (int i = 0; i < size; i++) {
17106                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17107                        return;
17108                    }
17109                }
17110            }
17111            resolver.addFilter(newFilter);
17112            scheduleWritePackageRestrictionsLocked(sourceUserId);
17113        }
17114    }
17115
17116    @Override
17117    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17118        mContext.enforceCallingOrSelfPermission(
17119                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17120        int callingUid = Binder.getCallingUid();
17121        enforceOwnerRights(ownerPackage, callingUid);
17122        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17123        synchronized (mPackages) {
17124            CrossProfileIntentResolver resolver =
17125                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17126            ArraySet<CrossProfileIntentFilter> set =
17127                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17128            for (CrossProfileIntentFilter filter : set) {
17129                if (filter.getOwnerPackage().equals(ownerPackage)) {
17130                    resolver.removeFilter(filter);
17131                }
17132            }
17133            scheduleWritePackageRestrictionsLocked(sourceUserId);
17134        }
17135    }
17136
17137    // Enforcing that callingUid is owning pkg on userId
17138    private void enforceOwnerRights(String pkg, int callingUid) {
17139        // The system owns everything.
17140        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17141            return;
17142        }
17143        int callingUserId = UserHandle.getUserId(callingUid);
17144        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17145        if (pi == null) {
17146            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17147                    + callingUserId);
17148        }
17149        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17150            throw new SecurityException("Calling uid " + callingUid
17151                    + " does not own package " + pkg);
17152        }
17153    }
17154
17155    @Override
17156    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17157        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17158    }
17159
17160    private Intent getHomeIntent() {
17161        Intent intent = new Intent(Intent.ACTION_MAIN);
17162        intent.addCategory(Intent.CATEGORY_HOME);
17163        return intent;
17164    }
17165
17166    private IntentFilter getHomeFilter() {
17167        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17168        filter.addCategory(Intent.CATEGORY_HOME);
17169        filter.addCategory(Intent.CATEGORY_DEFAULT);
17170        return filter;
17171    }
17172
17173    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17174            int userId) {
17175        Intent intent  = getHomeIntent();
17176        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17177                PackageManager.GET_META_DATA, userId);
17178        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17179                true, false, false, userId);
17180
17181        allHomeCandidates.clear();
17182        if (list != null) {
17183            for (ResolveInfo ri : list) {
17184                allHomeCandidates.add(ri);
17185            }
17186        }
17187        return (preferred == null || preferred.activityInfo == null)
17188                ? null
17189                : new ComponentName(preferred.activityInfo.packageName,
17190                        preferred.activityInfo.name);
17191    }
17192
17193    @Override
17194    public void setHomeActivity(ComponentName comp, int userId) {
17195        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17196        getHomeActivitiesAsUser(homeActivities, userId);
17197
17198        boolean found = false;
17199
17200        final int size = homeActivities.size();
17201        final ComponentName[] set = new ComponentName[size];
17202        for (int i = 0; i < size; i++) {
17203            final ResolveInfo candidate = homeActivities.get(i);
17204            final ActivityInfo info = candidate.activityInfo;
17205            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17206            set[i] = activityName;
17207            if (!found && activityName.equals(comp)) {
17208                found = true;
17209            }
17210        }
17211        if (!found) {
17212            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17213                    + userId);
17214        }
17215        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17216                set, comp, userId);
17217    }
17218
17219    private @Nullable String getSetupWizardPackageName() {
17220        final Intent intent = new Intent(Intent.ACTION_MAIN);
17221        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17222
17223        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17224                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17225                        | MATCH_DISABLED_COMPONENTS,
17226                UserHandle.myUserId());
17227        if (matches.size() == 1) {
17228            return matches.get(0).getComponentInfo().packageName;
17229        } else {
17230            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17231                    + ": matches=" + matches);
17232            return null;
17233        }
17234    }
17235
17236    @Override
17237    public void setApplicationEnabledSetting(String appPackageName,
17238            int newState, int flags, int userId, String callingPackage) {
17239        if (!sUserManager.exists(userId)) return;
17240        if (callingPackage == null) {
17241            callingPackage = Integer.toString(Binder.getCallingUid());
17242        }
17243        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17244    }
17245
17246    @Override
17247    public void setComponentEnabledSetting(ComponentName componentName,
17248            int newState, int flags, int userId) {
17249        if (!sUserManager.exists(userId)) return;
17250        setEnabledSetting(componentName.getPackageName(),
17251                componentName.getClassName(), newState, flags, userId, null);
17252    }
17253
17254    private void setEnabledSetting(final String packageName, String className, int newState,
17255            final int flags, int userId, String callingPackage) {
17256        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17257              || newState == COMPONENT_ENABLED_STATE_ENABLED
17258              || newState == COMPONENT_ENABLED_STATE_DISABLED
17259              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17260              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17261            throw new IllegalArgumentException("Invalid new component state: "
17262                    + newState);
17263        }
17264        PackageSetting pkgSetting;
17265        final int uid = Binder.getCallingUid();
17266        final int permission;
17267        if (uid == Process.SYSTEM_UID) {
17268            permission = PackageManager.PERMISSION_GRANTED;
17269        } else {
17270            permission = mContext.checkCallingOrSelfPermission(
17271                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17272        }
17273        enforceCrossUserPermission(uid, userId,
17274                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17275        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17276        boolean sendNow = false;
17277        boolean isApp = (className == null);
17278        String componentName = isApp ? packageName : className;
17279        int packageUid = -1;
17280        ArrayList<String> components;
17281
17282        // writer
17283        synchronized (mPackages) {
17284            pkgSetting = mSettings.mPackages.get(packageName);
17285            if (pkgSetting == null) {
17286                if (className == null) {
17287                    throw new IllegalArgumentException("Unknown package: " + packageName);
17288                }
17289                throw new IllegalArgumentException(
17290                        "Unknown component: " + packageName + "/" + className);
17291            }
17292            // Allow root and verify that userId is not being specified by a different user
17293            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17294                throw new SecurityException(
17295                        "Permission Denial: attempt to change component state from pid="
17296                        + Binder.getCallingPid()
17297                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17298            }
17299            if (className == null) {
17300                // We're dealing with an application/package level state change
17301                if (pkgSetting.getEnabled(userId) == newState) {
17302                    // Nothing to do
17303                    return;
17304                }
17305                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17306                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17307                    // Don't care about who enables an app.
17308                    callingPackage = null;
17309                }
17310                pkgSetting.setEnabled(newState, userId, callingPackage);
17311                // pkgSetting.pkg.mSetEnabled = newState;
17312            } else {
17313                // We're dealing with a component level state change
17314                // First, verify that this is a valid class name.
17315                PackageParser.Package pkg = pkgSetting.pkg;
17316                if (pkg == null || !pkg.hasComponentClassName(className)) {
17317                    if (pkg != null &&
17318                            pkg.applicationInfo.targetSdkVersion >=
17319                                    Build.VERSION_CODES.JELLY_BEAN) {
17320                        throw new IllegalArgumentException("Component class " + className
17321                                + " does not exist in " + packageName);
17322                    } else {
17323                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17324                                + className + " does not exist in " + packageName);
17325                    }
17326                }
17327                switch (newState) {
17328                case COMPONENT_ENABLED_STATE_ENABLED:
17329                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17330                        return;
17331                    }
17332                    break;
17333                case COMPONENT_ENABLED_STATE_DISABLED:
17334                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17335                        return;
17336                    }
17337                    break;
17338                case COMPONENT_ENABLED_STATE_DEFAULT:
17339                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17340                        return;
17341                    }
17342                    break;
17343                default:
17344                    Slog.e(TAG, "Invalid new component state: " + newState);
17345                    return;
17346                }
17347            }
17348            scheduleWritePackageRestrictionsLocked(userId);
17349            components = mPendingBroadcasts.get(userId, packageName);
17350            final boolean newPackage = components == null;
17351            if (newPackage) {
17352                components = new ArrayList<String>();
17353            }
17354            if (!components.contains(componentName)) {
17355                components.add(componentName);
17356            }
17357            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17358                sendNow = true;
17359                // Purge entry from pending broadcast list if another one exists already
17360                // since we are sending one right away.
17361                mPendingBroadcasts.remove(userId, packageName);
17362            } else {
17363                if (newPackage) {
17364                    mPendingBroadcasts.put(userId, packageName, components);
17365                }
17366                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17367                    // Schedule a message
17368                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17369                }
17370            }
17371        }
17372
17373        long callingId = Binder.clearCallingIdentity();
17374        try {
17375            if (sendNow) {
17376                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17377                sendPackageChangedBroadcast(packageName,
17378                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17379            }
17380        } finally {
17381            Binder.restoreCallingIdentity(callingId);
17382        }
17383    }
17384
17385    @Override
17386    public void flushPackageRestrictionsAsUser(int userId) {
17387        if (!sUserManager.exists(userId)) {
17388            return;
17389        }
17390        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17391                false /* checkShell */, "flushPackageRestrictions");
17392        synchronized (mPackages) {
17393            mSettings.writePackageRestrictionsLPr(userId);
17394            mDirtyUsers.remove(userId);
17395            if (mDirtyUsers.isEmpty()) {
17396                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17397            }
17398        }
17399    }
17400
17401    private void sendPackageChangedBroadcast(String packageName,
17402            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17403        if (DEBUG_INSTALL)
17404            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17405                    + componentNames);
17406        Bundle extras = new Bundle(4);
17407        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17408        String nameList[] = new String[componentNames.size()];
17409        componentNames.toArray(nameList);
17410        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17411        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17412        extras.putInt(Intent.EXTRA_UID, packageUid);
17413        // If this is not reporting a change of the overall package, then only send it
17414        // to registered receivers.  We don't want to launch a swath of apps for every
17415        // little component state change.
17416        final int flags = !componentNames.contains(packageName)
17417                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17418        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17419                new int[] {UserHandle.getUserId(packageUid)});
17420    }
17421
17422    @Override
17423    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17424        if (!sUserManager.exists(userId)) return;
17425        final int uid = Binder.getCallingUid();
17426        final int permission = mContext.checkCallingOrSelfPermission(
17427                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17428        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17429        enforceCrossUserPermission(uid, userId,
17430                true /* requireFullPermission */, true /* checkShell */, "stop package");
17431        // writer
17432        synchronized (mPackages) {
17433            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17434                    allowedByPermission, uid, userId)) {
17435                scheduleWritePackageRestrictionsLocked(userId);
17436            }
17437        }
17438    }
17439
17440    @Override
17441    public String getInstallerPackageName(String packageName) {
17442        // reader
17443        synchronized (mPackages) {
17444            return mSettings.getInstallerPackageNameLPr(packageName);
17445        }
17446    }
17447
17448    @Override
17449    public int getApplicationEnabledSetting(String packageName, int userId) {
17450        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17451        int uid = Binder.getCallingUid();
17452        enforceCrossUserPermission(uid, userId,
17453                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17454        // reader
17455        synchronized (mPackages) {
17456            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17457        }
17458    }
17459
17460    @Override
17461    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17462        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17463        int uid = Binder.getCallingUid();
17464        enforceCrossUserPermission(uid, userId,
17465                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17466        // reader
17467        synchronized (mPackages) {
17468            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17469        }
17470    }
17471
17472    @Override
17473    public void enterSafeMode() {
17474        enforceSystemOrRoot("Only the system can request entering safe mode");
17475
17476        if (!mSystemReady) {
17477            mSafeMode = true;
17478        }
17479    }
17480
17481    @Override
17482    public void systemReady() {
17483        mSystemReady = true;
17484
17485        // Read the compatibilty setting when the system is ready.
17486        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17487                mContext.getContentResolver(),
17488                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17489        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17490        if (DEBUG_SETTINGS) {
17491            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17492        }
17493
17494        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17495
17496        synchronized (mPackages) {
17497            // Verify that all of the preferred activity components actually
17498            // exist.  It is possible for applications to be updated and at
17499            // that point remove a previously declared activity component that
17500            // had been set as a preferred activity.  We try to clean this up
17501            // the next time we encounter that preferred activity, but it is
17502            // possible for the user flow to never be able to return to that
17503            // situation so here we do a sanity check to make sure we haven't
17504            // left any junk around.
17505            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17506            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17507                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17508                removed.clear();
17509                for (PreferredActivity pa : pir.filterSet()) {
17510                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17511                        removed.add(pa);
17512                    }
17513                }
17514                if (removed.size() > 0) {
17515                    for (int r=0; r<removed.size(); r++) {
17516                        PreferredActivity pa = removed.get(r);
17517                        Slog.w(TAG, "Removing dangling preferred activity: "
17518                                + pa.mPref.mComponent);
17519                        pir.removeFilter(pa);
17520                    }
17521                    mSettings.writePackageRestrictionsLPr(
17522                            mSettings.mPreferredActivities.keyAt(i));
17523                }
17524            }
17525
17526            for (int userId : UserManagerService.getInstance().getUserIds()) {
17527                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17528                    grantPermissionsUserIds = ArrayUtils.appendInt(
17529                            grantPermissionsUserIds, userId);
17530                }
17531            }
17532        }
17533        sUserManager.systemReady();
17534
17535        // If we upgraded grant all default permissions before kicking off.
17536        for (int userId : grantPermissionsUserIds) {
17537            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17538        }
17539
17540        // Kick off any messages waiting for system ready
17541        if (mPostSystemReadyMessages != null) {
17542            for (Message msg : mPostSystemReadyMessages) {
17543                msg.sendToTarget();
17544            }
17545            mPostSystemReadyMessages = null;
17546        }
17547
17548        // Watch for external volumes that come and go over time
17549        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17550        storage.registerListener(mStorageListener);
17551
17552        mInstallerService.systemReady();
17553        mPackageDexOptimizer.systemReady();
17554
17555        MountServiceInternal mountServiceInternal = LocalServices.getService(
17556                MountServiceInternal.class);
17557        mountServiceInternal.addExternalStoragePolicy(
17558                new MountServiceInternal.ExternalStorageMountPolicy() {
17559            @Override
17560            public int getMountMode(int uid, String packageName) {
17561                if (Process.isIsolated(uid)) {
17562                    return Zygote.MOUNT_EXTERNAL_NONE;
17563                }
17564                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17565                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17566                }
17567                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17568                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17569                }
17570                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17571                    return Zygote.MOUNT_EXTERNAL_READ;
17572                }
17573                return Zygote.MOUNT_EXTERNAL_WRITE;
17574            }
17575
17576            @Override
17577            public boolean hasExternalStorage(int uid, String packageName) {
17578                return true;
17579            }
17580        });
17581
17582        // Now that we're mostly running, clean up stale users and apps
17583        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17584        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17585    }
17586
17587    @Override
17588    public boolean isSafeMode() {
17589        return mSafeMode;
17590    }
17591
17592    @Override
17593    public boolean hasSystemUidErrors() {
17594        return mHasSystemUidErrors;
17595    }
17596
17597    static String arrayToString(int[] array) {
17598        StringBuffer buf = new StringBuffer(128);
17599        buf.append('[');
17600        if (array != null) {
17601            for (int i=0; i<array.length; i++) {
17602                if (i > 0) buf.append(", ");
17603                buf.append(array[i]);
17604            }
17605        }
17606        buf.append(']');
17607        return buf.toString();
17608    }
17609
17610    static class DumpState {
17611        public static final int DUMP_LIBS = 1 << 0;
17612        public static final int DUMP_FEATURES = 1 << 1;
17613        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17614        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17615        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17616        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17617        public static final int DUMP_PERMISSIONS = 1 << 6;
17618        public static final int DUMP_PACKAGES = 1 << 7;
17619        public static final int DUMP_SHARED_USERS = 1 << 8;
17620        public static final int DUMP_MESSAGES = 1 << 9;
17621        public static final int DUMP_PROVIDERS = 1 << 10;
17622        public static final int DUMP_VERIFIERS = 1 << 11;
17623        public static final int DUMP_PREFERRED = 1 << 12;
17624        public static final int DUMP_PREFERRED_XML = 1 << 13;
17625        public static final int DUMP_KEYSETS = 1 << 14;
17626        public static final int DUMP_VERSION = 1 << 15;
17627        public static final int DUMP_INSTALLS = 1 << 16;
17628        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17629        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17630        public static final int DUMP_FROZEN = 1 << 19;
17631
17632        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17633
17634        private int mTypes;
17635
17636        private int mOptions;
17637
17638        private boolean mTitlePrinted;
17639
17640        private SharedUserSetting mSharedUser;
17641
17642        public boolean isDumping(int type) {
17643            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17644                return true;
17645            }
17646
17647            return (mTypes & type) != 0;
17648        }
17649
17650        public void setDump(int type) {
17651            mTypes |= type;
17652        }
17653
17654        public boolean isOptionEnabled(int option) {
17655            return (mOptions & option) != 0;
17656        }
17657
17658        public void setOptionEnabled(int option) {
17659            mOptions |= option;
17660        }
17661
17662        public boolean onTitlePrinted() {
17663            final boolean printed = mTitlePrinted;
17664            mTitlePrinted = true;
17665            return printed;
17666        }
17667
17668        public boolean getTitlePrinted() {
17669            return mTitlePrinted;
17670        }
17671
17672        public void setTitlePrinted(boolean enabled) {
17673            mTitlePrinted = enabled;
17674        }
17675
17676        public SharedUserSetting getSharedUser() {
17677            return mSharedUser;
17678        }
17679
17680        public void setSharedUser(SharedUserSetting user) {
17681            mSharedUser = user;
17682        }
17683    }
17684
17685    @Override
17686    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17687            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17688        (new PackageManagerShellCommand(this)).exec(
17689                this, in, out, err, args, resultReceiver);
17690    }
17691
17692    @Override
17693    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17694        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17695                != PackageManager.PERMISSION_GRANTED) {
17696            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17697                    + Binder.getCallingPid()
17698                    + ", uid=" + Binder.getCallingUid()
17699                    + " without permission "
17700                    + android.Manifest.permission.DUMP);
17701            return;
17702        }
17703
17704        DumpState dumpState = new DumpState();
17705        boolean fullPreferred = false;
17706        boolean checkin = false;
17707
17708        String packageName = null;
17709        ArraySet<String> permissionNames = null;
17710
17711        int opti = 0;
17712        while (opti < args.length) {
17713            String opt = args[opti];
17714            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17715                break;
17716            }
17717            opti++;
17718
17719            if ("-a".equals(opt)) {
17720                // Right now we only know how to print all.
17721            } else if ("-h".equals(opt)) {
17722                pw.println("Package manager dump options:");
17723                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17724                pw.println("    --checkin: dump for a checkin");
17725                pw.println("    -f: print details of intent filters");
17726                pw.println("    -h: print this help");
17727                pw.println("  cmd may be one of:");
17728                pw.println("    l[ibraries]: list known shared libraries");
17729                pw.println("    f[eatures]: list device features");
17730                pw.println("    k[eysets]: print known keysets");
17731                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17732                pw.println("    perm[issions]: dump permissions");
17733                pw.println("    permission [name ...]: dump declaration and use of given permission");
17734                pw.println("    pref[erred]: print preferred package settings");
17735                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17736                pw.println("    prov[iders]: dump content providers");
17737                pw.println("    p[ackages]: dump installed packages");
17738                pw.println("    s[hared-users]: dump shared user IDs");
17739                pw.println("    m[essages]: print collected runtime messages");
17740                pw.println("    v[erifiers]: print package verifier info");
17741                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17742                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17743                pw.println("    version: print database version info");
17744                pw.println("    write: write current settings now");
17745                pw.println("    installs: details about install sessions");
17746                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17747                pw.println("    <package.name>: info about given package");
17748                return;
17749            } else if ("--checkin".equals(opt)) {
17750                checkin = true;
17751            } else if ("-f".equals(opt)) {
17752                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17753            } else {
17754                pw.println("Unknown argument: " + opt + "; use -h for help");
17755            }
17756        }
17757
17758        // Is the caller requesting to dump a particular piece of data?
17759        if (opti < args.length) {
17760            String cmd = args[opti];
17761            opti++;
17762            // Is this a package name?
17763            if ("android".equals(cmd) || cmd.contains(".")) {
17764                packageName = cmd;
17765                // When dumping a single package, we always dump all of its
17766                // filter information since the amount of data will be reasonable.
17767                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17768            } else if ("check-permission".equals(cmd)) {
17769                if (opti >= args.length) {
17770                    pw.println("Error: check-permission missing permission argument");
17771                    return;
17772                }
17773                String perm = args[opti];
17774                opti++;
17775                if (opti >= args.length) {
17776                    pw.println("Error: check-permission missing package argument");
17777                    return;
17778                }
17779                String pkg = args[opti];
17780                opti++;
17781                int user = UserHandle.getUserId(Binder.getCallingUid());
17782                if (opti < args.length) {
17783                    try {
17784                        user = Integer.parseInt(args[opti]);
17785                    } catch (NumberFormatException e) {
17786                        pw.println("Error: check-permission user argument is not a number: "
17787                                + args[opti]);
17788                        return;
17789                    }
17790                }
17791                pw.println(checkPermission(perm, pkg, user));
17792                return;
17793            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17794                dumpState.setDump(DumpState.DUMP_LIBS);
17795            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17796                dumpState.setDump(DumpState.DUMP_FEATURES);
17797            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17798                if (opti >= args.length) {
17799                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17800                            | DumpState.DUMP_SERVICE_RESOLVERS
17801                            | DumpState.DUMP_RECEIVER_RESOLVERS
17802                            | DumpState.DUMP_CONTENT_RESOLVERS);
17803                } else {
17804                    while (opti < args.length) {
17805                        String name = args[opti];
17806                        if ("a".equals(name) || "activity".equals(name)) {
17807                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17808                        } else if ("s".equals(name) || "service".equals(name)) {
17809                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17810                        } else if ("r".equals(name) || "receiver".equals(name)) {
17811                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17812                        } else if ("c".equals(name) || "content".equals(name)) {
17813                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17814                        } else {
17815                            pw.println("Error: unknown resolver table type: " + name);
17816                            return;
17817                        }
17818                        opti++;
17819                    }
17820                }
17821            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17822                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17823            } else if ("permission".equals(cmd)) {
17824                if (opti >= args.length) {
17825                    pw.println("Error: permission requires permission name");
17826                    return;
17827                }
17828                permissionNames = new ArraySet<>();
17829                while (opti < args.length) {
17830                    permissionNames.add(args[opti]);
17831                    opti++;
17832                }
17833                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17834                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17835            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17836                dumpState.setDump(DumpState.DUMP_PREFERRED);
17837            } else if ("preferred-xml".equals(cmd)) {
17838                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17839                if (opti < args.length && "--full".equals(args[opti])) {
17840                    fullPreferred = true;
17841                    opti++;
17842                }
17843            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17844                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17845            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17846                dumpState.setDump(DumpState.DUMP_PACKAGES);
17847            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17848                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17849            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17850                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17851            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17852                dumpState.setDump(DumpState.DUMP_MESSAGES);
17853            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17854                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17855            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17856                    || "intent-filter-verifiers".equals(cmd)) {
17857                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17858            } else if ("version".equals(cmd)) {
17859                dumpState.setDump(DumpState.DUMP_VERSION);
17860            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17861                dumpState.setDump(DumpState.DUMP_KEYSETS);
17862            } else if ("installs".equals(cmd)) {
17863                dumpState.setDump(DumpState.DUMP_INSTALLS);
17864            } else if ("frozen".equals(cmd)) {
17865                dumpState.setDump(DumpState.DUMP_FROZEN);
17866            } else if ("write".equals(cmd)) {
17867                synchronized (mPackages) {
17868                    mSettings.writeLPr();
17869                    pw.println("Settings written.");
17870                    return;
17871                }
17872            }
17873        }
17874
17875        if (checkin) {
17876            pw.println("vers,1");
17877        }
17878
17879        // reader
17880        synchronized (mPackages) {
17881            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17882                if (!checkin) {
17883                    if (dumpState.onTitlePrinted())
17884                        pw.println();
17885                    pw.println("Database versions:");
17886                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17887                }
17888            }
17889
17890            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17891                if (!checkin) {
17892                    if (dumpState.onTitlePrinted())
17893                        pw.println();
17894                    pw.println("Verifiers:");
17895                    pw.print("  Required: ");
17896                    pw.print(mRequiredVerifierPackage);
17897                    pw.print(" (uid=");
17898                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17899                            UserHandle.USER_SYSTEM));
17900                    pw.println(")");
17901                } else if (mRequiredVerifierPackage != null) {
17902                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17903                    pw.print(",");
17904                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17905                            UserHandle.USER_SYSTEM));
17906                }
17907            }
17908
17909            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17910                    packageName == null) {
17911                if (mIntentFilterVerifierComponent != null) {
17912                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17913                    if (!checkin) {
17914                        if (dumpState.onTitlePrinted())
17915                            pw.println();
17916                        pw.println("Intent Filter Verifier:");
17917                        pw.print("  Using: ");
17918                        pw.print(verifierPackageName);
17919                        pw.print(" (uid=");
17920                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17921                                UserHandle.USER_SYSTEM));
17922                        pw.println(")");
17923                    } else if (verifierPackageName != null) {
17924                        pw.print("ifv,"); pw.print(verifierPackageName);
17925                        pw.print(",");
17926                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17927                                UserHandle.USER_SYSTEM));
17928                    }
17929                } else {
17930                    pw.println();
17931                    pw.println("No Intent Filter Verifier available!");
17932                }
17933            }
17934
17935            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17936                boolean printedHeader = false;
17937                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17938                while (it.hasNext()) {
17939                    String name = it.next();
17940                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17941                    if (!checkin) {
17942                        if (!printedHeader) {
17943                            if (dumpState.onTitlePrinted())
17944                                pw.println();
17945                            pw.println("Libraries:");
17946                            printedHeader = true;
17947                        }
17948                        pw.print("  ");
17949                    } else {
17950                        pw.print("lib,");
17951                    }
17952                    pw.print(name);
17953                    if (!checkin) {
17954                        pw.print(" -> ");
17955                    }
17956                    if (ent.path != null) {
17957                        if (!checkin) {
17958                            pw.print("(jar) ");
17959                            pw.print(ent.path);
17960                        } else {
17961                            pw.print(",jar,");
17962                            pw.print(ent.path);
17963                        }
17964                    } else {
17965                        if (!checkin) {
17966                            pw.print("(apk) ");
17967                            pw.print(ent.apk);
17968                        } else {
17969                            pw.print(",apk,");
17970                            pw.print(ent.apk);
17971                        }
17972                    }
17973                    pw.println();
17974                }
17975            }
17976
17977            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17978                if (dumpState.onTitlePrinted())
17979                    pw.println();
17980                if (!checkin) {
17981                    pw.println("Features:");
17982                }
17983
17984                for (FeatureInfo feat : mAvailableFeatures.values()) {
17985                    if (checkin) {
17986                        pw.print("feat,");
17987                        pw.print(feat.name);
17988                        pw.print(",");
17989                        pw.println(feat.version);
17990                    } else {
17991                        pw.print("  ");
17992                        pw.print(feat.name);
17993                        if (feat.version > 0) {
17994                            pw.print(" version=");
17995                            pw.print(feat.version);
17996                        }
17997                        pw.println();
17998                    }
17999                }
18000            }
18001
18002            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18003                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18004                        : "Activity Resolver Table:", "  ", packageName,
18005                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18006                    dumpState.setTitlePrinted(true);
18007                }
18008            }
18009            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18010                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18011                        : "Receiver Resolver Table:", "  ", packageName,
18012                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18013                    dumpState.setTitlePrinted(true);
18014                }
18015            }
18016            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18017                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18018                        : "Service Resolver Table:", "  ", packageName,
18019                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18020                    dumpState.setTitlePrinted(true);
18021                }
18022            }
18023            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18024                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18025                        : "Provider Resolver Table:", "  ", packageName,
18026                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18027                    dumpState.setTitlePrinted(true);
18028                }
18029            }
18030
18031            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18032                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18033                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18034                    int user = mSettings.mPreferredActivities.keyAt(i);
18035                    if (pir.dump(pw,
18036                            dumpState.getTitlePrinted()
18037                                ? "\nPreferred Activities User " + user + ":"
18038                                : "Preferred Activities User " + user + ":", "  ",
18039                            packageName, true, false)) {
18040                        dumpState.setTitlePrinted(true);
18041                    }
18042                }
18043            }
18044
18045            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18046                pw.flush();
18047                FileOutputStream fout = new FileOutputStream(fd);
18048                BufferedOutputStream str = new BufferedOutputStream(fout);
18049                XmlSerializer serializer = new FastXmlSerializer();
18050                try {
18051                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18052                    serializer.startDocument(null, true);
18053                    serializer.setFeature(
18054                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18055                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18056                    serializer.endDocument();
18057                    serializer.flush();
18058                } catch (IllegalArgumentException e) {
18059                    pw.println("Failed writing: " + e);
18060                } catch (IllegalStateException e) {
18061                    pw.println("Failed writing: " + e);
18062                } catch (IOException e) {
18063                    pw.println("Failed writing: " + e);
18064                }
18065            }
18066
18067            if (!checkin
18068                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18069                    && packageName == null) {
18070                pw.println();
18071                int count = mSettings.mPackages.size();
18072                if (count == 0) {
18073                    pw.println("No applications!");
18074                    pw.println();
18075                } else {
18076                    final String prefix = "  ";
18077                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18078                    if (allPackageSettings.size() == 0) {
18079                        pw.println("No domain preferred apps!");
18080                        pw.println();
18081                    } else {
18082                        pw.println("App verification status:");
18083                        pw.println();
18084                        count = 0;
18085                        for (PackageSetting ps : allPackageSettings) {
18086                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18087                            if (ivi == null || ivi.getPackageName() == null) continue;
18088                            pw.println(prefix + "Package: " + ivi.getPackageName());
18089                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18090                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18091                            pw.println();
18092                            count++;
18093                        }
18094                        if (count == 0) {
18095                            pw.println(prefix + "No app verification established.");
18096                            pw.println();
18097                        }
18098                        for (int userId : sUserManager.getUserIds()) {
18099                            pw.println("App linkages for user " + userId + ":");
18100                            pw.println();
18101                            count = 0;
18102                            for (PackageSetting ps : allPackageSettings) {
18103                                final long status = ps.getDomainVerificationStatusForUser(userId);
18104                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18105                                    continue;
18106                                }
18107                                pw.println(prefix + "Package: " + ps.name);
18108                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18109                                String statusStr = IntentFilterVerificationInfo.
18110                                        getStatusStringFromValue(status);
18111                                pw.println(prefix + "Status:  " + statusStr);
18112                                pw.println();
18113                                count++;
18114                            }
18115                            if (count == 0) {
18116                                pw.println(prefix + "No configured app linkages.");
18117                                pw.println();
18118                            }
18119                        }
18120                    }
18121                }
18122            }
18123
18124            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18125                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18126                if (packageName == null && permissionNames == null) {
18127                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18128                        if (iperm == 0) {
18129                            if (dumpState.onTitlePrinted())
18130                                pw.println();
18131                            pw.println("AppOp Permissions:");
18132                        }
18133                        pw.print("  AppOp Permission ");
18134                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18135                        pw.println(":");
18136                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18137                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18138                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18139                        }
18140                    }
18141                }
18142            }
18143
18144            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18145                boolean printedSomething = false;
18146                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18147                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18148                        continue;
18149                    }
18150                    if (!printedSomething) {
18151                        if (dumpState.onTitlePrinted())
18152                            pw.println();
18153                        pw.println("Registered ContentProviders:");
18154                        printedSomething = true;
18155                    }
18156                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18157                    pw.print("    "); pw.println(p.toString());
18158                }
18159                printedSomething = false;
18160                for (Map.Entry<String, PackageParser.Provider> entry :
18161                        mProvidersByAuthority.entrySet()) {
18162                    PackageParser.Provider p = entry.getValue();
18163                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18164                        continue;
18165                    }
18166                    if (!printedSomething) {
18167                        if (dumpState.onTitlePrinted())
18168                            pw.println();
18169                        pw.println("ContentProvider Authorities:");
18170                        printedSomething = true;
18171                    }
18172                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18173                    pw.print("    "); pw.println(p.toString());
18174                    if (p.info != null && p.info.applicationInfo != null) {
18175                        final String appInfo = p.info.applicationInfo.toString();
18176                        pw.print("      applicationInfo="); pw.println(appInfo);
18177                    }
18178                }
18179            }
18180
18181            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18182                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18183            }
18184
18185            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18186                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18187            }
18188
18189            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18190                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18191            }
18192
18193            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18194                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18195            }
18196
18197            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18198                // XXX should handle packageName != null by dumping only install data that
18199                // the given package is involved with.
18200                if (dumpState.onTitlePrinted()) pw.println();
18201                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18202            }
18203
18204            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18205                // XXX should handle packageName != null by dumping only install data that
18206                // the given package is involved with.
18207                if (dumpState.onTitlePrinted()) pw.println();
18208
18209                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18210                ipw.println();
18211                ipw.println("Frozen packages:");
18212                ipw.increaseIndent();
18213                if (mFrozenPackages.size() == 0) {
18214                    ipw.println("(none)");
18215                } else {
18216                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18217                        ipw.println(mFrozenPackages.valueAt(i));
18218                    }
18219                }
18220                ipw.decreaseIndent();
18221            }
18222
18223            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18224                if (dumpState.onTitlePrinted()) pw.println();
18225                mSettings.dumpReadMessagesLPr(pw, dumpState);
18226
18227                pw.println();
18228                pw.println("Package warning messages:");
18229                BufferedReader in = null;
18230                String line = null;
18231                try {
18232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18233                    while ((line = in.readLine()) != null) {
18234                        if (line.contains("ignored: updated version")) continue;
18235                        pw.println(line);
18236                    }
18237                } catch (IOException ignored) {
18238                } finally {
18239                    IoUtils.closeQuietly(in);
18240                }
18241            }
18242
18243            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18244                BufferedReader in = null;
18245                String line = null;
18246                try {
18247                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18248                    while ((line = in.readLine()) != null) {
18249                        if (line.contains("ignored: updated version")) continue;
18250                        pw.print("msg,");
18251                        pw.println(line);
18252                    }
18253                } catch (IOException ignored) {
18254                } finally {
18255                    IoUtils.closeQuietly(in);
18256                }
18257            }
18258        }
18259    }
18260
18261    private String dumpDomainString(String packageName) {
18262        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18263                .getList();
18264        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18265
18266        ArraySet<String> result = new ArraySet<>();
18267        if (iviList.size() > 0) {
18268            for (IntentFilterVerificationInfo ivi : iviList) {
18269                for (String host : ivi.getDomains()) {
18270                    result.add(host);
18271                }
18272            }
18273        }
18274        if (filters != null && filters.size() > 0) {
18275            for (IntentFilter filter : filters) {
18276                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18277                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18278                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18279                    result.addAll(filter.getHostsList());
18280                }
18281            }
18282        }
18283
18284        StringBuilder sb = new StringBuilder(result.size() * 16);
18285        for (String domain : result) {
18286            if (sb.length() > 0) sb.append(" ");
18287            sb.append(domain);
18288        }
18289        return sb.toString();
18290    }
18291
18292    // ------- apps on sdcard specific code -------
18293    static final boolean DEBUG_SD_INSTALL = false;
18294
18295    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18296
18297    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18298
18299    private boolean mMediaMounted = false;
18300
18301    static String getEncryptKey() {
18302        try {
18303            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18304                    SD_ENCRYPTION_KEYSTORE_NAME);
18305            if (sdEncKey == null) {
18306                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18307                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18308                if (sdEncKey == null) {
18309                    Slog.e(TAG, "Failed to create encryption keys");
18310                    return null;
18311                }
18312            }
18313            return sdEncKey;
18314        } catch (NoSuchAlgorithmException nsae) {
18315            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18316            return null;
18317        } catch (IOException ioe) {
18318            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18319            return null;
18320        }
18321    }
18322
18323    /*
18324     * Update media status on PackageManager.
18325     */
18326    @Override
18327    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18328        int callingUid = Binder.getCallingUid();
18329        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18330            throw new SecurityException("Media status can only be updated by the system");
18331        }
18332        // reader; this apparently protects mMediaMounted, but should probably
18333        // be a different lock in that case.
18334        synchronized (mPackages) {
18335            Log.i(TAG, "Updating external media status from "
18336                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18337                    + (mediaStatus ? "mounted" : "unmounted"));
18338            if (DEBUG_SD_INSTALL)
18339                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18340                        + ", mMediaMounted=" + mMediaMounted);
18341            if (mediaStatus == mMediaMounted) {
18342                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18343                        : 0, -1);
18344                mHandler.sendMessage(msg);
18345                return;
18346            }
18347            mMediaMounted = mediaStatus;
18348        }
18349        // Queue up an async operation since the package installation may take a
18350        // little while.
18351        mHandler.post(new Runnable() {
18352            public void run() {
18353                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18354            }
18355        });
18356    }
18357
18358    /**
18359     * Called by MountService when the initial ASECs to scan are available.
18360     * Should block until all the ASEC containers are finished being scanned.
18361     */
18362    public void scanAvailableAsecs() {
18363        updateExternalMediaStatusInner(true, false, false);
18364    }
18365
18366    /*
18367     * Collect information of applications on external media, map them against
18368     * existing containers and update information based on current mount status.
18369     * Please note that we always have to report status if reportStatus has been
18370     * set to true especially when unloading packages.
18371     */
18372    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18373            boolean externalStorage) {
18374        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18375        int[] uidArr = EmptyArray.INT;
18376
18377        final String[] list = PackageHelper.getSecureContainerList();
18378        if (ArrayUtils.isEmpty(list)) {
18379            Log.i(TAG, "No secure containers found");
18380        } else {
18381            // Process list of secure containers and categorize them
18382            // as active or stale based on their package internal state.
18383
18384            // reader
18385            synchronized (mPackages) {
18386                for (String cid : list) {
18387                    // Leave stages untouched for now; installer service owns them
18388                    if (PackageInstallerService.isStageName(cid)) continue;
18389
18390                    if (DEBUG_SD_INSTALL)
18391                        Log.i(TAG, "Processing container " + cid);
18392                    String pkgName = getAsecPackageName(cid);
18393                    if (pkgName == null) {
18394                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18395                        continue;
18396                    }
18397                    if (DEBUG_SD_INSTALL)
18398                        Log.i(TAG, "Looking for pkg : " + pkgName);
18399
18400                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18401                    if (ps == null) {
18402                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18403                        continue;
18404                    }
18405
18406                    /*
18407                     * Skip packages that are not external if we're unmounting
18408                     * external storage.
18409                     */
18410                    if (externalStorage && !isMounted && !isExternal(ps)) {
18411                        continue;
18412                    }
18413
18414                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18415                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18416                    // The package status is changed only if the code path
18417                    // matches between settings and the container id.
18418                    if (ps.codePathString != null
18419                            && ps.codePathString.startsWith(args.getCodePath())) {
18420                        if (DEBUG_SD_INSTALL) {
18421                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18422                                    + " at code path: " + ps.codePathString);
18423                        }
18424
18425                        // We do have a valid package installed on sdcard
18426                        processCids.put(args, ps.codePathString);
18427                        final int uid = ps.appId;
18428                        if (uid != -1) {
18429                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18430                        }
18431                    } else {
18432                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18433                                + ps.codePathString);
18434                    }
18435                }
18436            }
18437
18438            Arrays.sort(uidArr);
18439        }
18440
18441        // Process packages with valid entries.
18442        if (isMounted) {
18443            if (DEBUG_SD_INSTALL)
18444                Log.i(TAG, "Loading packages");
18445            loadMediaPackages(processCids, uidArr, externalStorage);
18446            startCleaningPackages();
18447            mInstallerService.onSecureContainersAvailable();
18448        } else {
18449            if (DEBUG_SD_INSTALL)
18450                Log.i(TAG, "Unloading packages");
18451            unloadMediaPackages(processCids, uidArr, reportStatus);
18452        }
18453    }
18454
18455    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18456            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18457        final int size = infos.size();
18458        final String[] packageNames = new String[size];
18459        final int[] packageUids = new int[size];
18460        for (int i = 0; i < size; i++) {
18461            final ApplicationInfo info = infos.get(i);
18462            packageNames[i] = info.packageName;
18463            packageUids[i] = info.uid;
18464        }
18465        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18466                finishedReceiver);
18467    }
18468
18469    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18470            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18471        sendResourcesChangedBroadcast(mediaStatus, replacing,
18472                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18473    }
18474
18475    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18476            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18477        int size = pkgList.length;
18478        if (size > 0) {
18479            // Send broadcasts here
18480            Bundle extras = new Bundle();
18481            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18482            if (uidArr != null) {
18483                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18484            }
18485            if (replacing) {
18486                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18487            }
18488            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18489                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18490            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18491        }
18492    }
18493
18494   /*
18495     * Look at potentially valid container ids from processCids If package
18496     * information doesn't match the one on record or package scanning fails,
18497     * the cid is added to list of removeCids. We currently don't delete stale
18498     * containers.
18499     */
18500    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18501            boolean externalStorage) {
18502        ArrayList<String> pkgList = new ArrayList<String>();
18503        Set<AsecInstallArgs> keys = processCids.keySet();
18504
18505        for (AsecInstallArgs args : keys) {
18506            String codePath = processCids.get(args);
18507            if (DEBUG_SD_INSTALL)
18508                Log.i(TAG, "Loading container : " + args.cid);
18509            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18510            try {
18511                // Make sure there are no container errors first.
18512                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18513                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18514                            + " when installing from sdcard");
18515                    continue;
18516                }
18517                // Check code path here.
18518                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18519                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18520                            + " does not match one in settings " + codePath);
18521                    continue;
18522                }
18523                // Parse package
18524                int parseFlags = mDefParseFlags;
18525                if (args.isExternalAsec()) {
18526                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18527                }
18528                if (args.isFwdLocked()) {
18529                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18530                }
18531
18532                synchronized (mInstallLock) {
18533                    PackageParser.Package pkg = null;
18534                    try {
18535                        // Sadly we don't know the package name yet to freeze it
18536                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18537                                SCAN_IGNORE_FROZEN, 0, null);
18538                    } catch (PackageManagerException e) {
18539                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18540                    }
18541                    // Scan the package
18542                    if (pkg != null) {
18543                        /*
18544                         * TODO why is the lock being held? doPostInstall is
18545                         * called in other places without the lock. This needs
18546                         * to be straightened out.
18547                         */
18548                        // writer
18549                        synchronized (mPackages) {
18550                            retCode = PackageManager.INSTALL_SUCCEEDED;
18551                            pkgList.add(pkg.packageName);
18552                            // Post process args
18553                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18554                                    pkg.applicationInfo.uid);
18555                        }
18556                    } else {
18557                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18558                    }
18559                }
18560
18561            } finally {
18562                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18563                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18564                }
18565            }
18566        }
18567        // writer
18568        synchronized (mPackages) {
18569            // If the platform SDK has changed since the last time we booted,
18570            // we need to re-grant app permission to catch any new ones that
18571            // appear. This is really a hack, and means that apps can in some
18572            // cases get permissions that the user didn't initially explicitly
18573            // allow... it would be nice to have some better way to handle
18574            // this situation.
18575            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18576                    : mSettings.getInternalVersion();
18577            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18578                    : StorageManager.UUID_PRIVATE_INTERNAL;
18579
18580            int updateFlags = UPDATE_PERMISSIONS_ALL;
18581            if (ver.sdkVersion != mSdkVersion) {
18582                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18583                        + mSdkVersion + "; regranting permissions for external");
18584                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18585            }
18586            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18587
18588            // Yay, everything is now upgraded
18589            ver.forceCurrent();
18590
18591            // can downgrade to reader
18592            // Persist settings
18593            mSettings.writeLPr();
18594        }
18595        // Send a broadcast to let everyone know we are done processing
18596        if (pkgList.size() > 0) {
18597            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18598        }
18599    }
18600
18601   /*
18602     * Utility method to unload a list of specified containers
18603     */
18604    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18605        // Just unmount all valid containers.
18606        for (AsecInstallArgs arg : cidArgs) {
18607            synchronized (mInstallLock) {
18608                arg.doPostDeleteLI(false);
18609           }
18610       }
18611   }
18612
18613    /*
18614     * Unload packages mounted on external media. This involves deleting package
18615     * data from internal structures, sending broadcasts about disabled packages,
18616     * gc'ing to free up references, unmounting all secure containers
18617     * corresponding to packages on external media, and posting a
18618     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18619     * that we always have to post this message if status has been requested no
18620     * matter what.
18621     */
18622    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18623            final boolean reportStatus) {
18624        if (DEBUG_SD_INSTALL)
18625            Log.i(TAG, "unloading media packages");
18626        ArrayList<String> pkgList = new ArrayList<String>();
18627        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18628        final Set<AsecInstallArgs> keys = processCids.keySet();
18629        for (AsecInstallArgs args : keys) {
18630            String pkgName = args.getPackageName();
18631            if (DEBUG_SD_INSTALL)
18632                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18633            // Delete package internally
18634            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18635            synchronized (mInstallLock) {
18636                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18637                final boolean res;
18638                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18639                        "unloadMediaPackages")) {
18640                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18641                            null);
18642                }
18643                if (res) {
18644                    pkgList.add(pkgName);
18645                } else {
18646                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18647                    failedList.add(args);
18648                }
18649            }
18650        }
18651
18652        // reader
18653        synchronized (mPackages) {
18654            // We didn't update the settings after removing each package;
18655            // write them now for all packages.
18656            mSettings.writeLPr();
18657        }
18658
18659        // We have to absolutely send UPDATED_MEDIA_STATUS only
18660        // after confirming that all the receivers processed the ordered
18661        // broadcast when packages get disabled, force a gc to clean things up.
18662        // and unload all the containers.
18663        if (pkgList.size() > 0) {
18664            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18665                    new IIntentReceiver.Stub() {
18666                public void performReceive(Intent intent, int resultCode, String data,
18667                        Bundle extras, boolean ordered, boolean sticky,
18668                        int sendingUser) throws RemoteException {
18669                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18670                            reportStatus ? 1 : 0, 1, keys);
18671                    mHandler.sendMessage(msg);
18672                }
18673            });
18674        } else {
18675            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18676                    keys);
18677            mHandler.sendMessage(msg);
18678        }
18679    }
18680
18681    private void loadPrivatePackages(final VolumeInfo vol) {
18682        mHandler.post(new Runnable() {
18683            @Override
18684            public void run() {
18685                loadPrivatePackagesInner(vol);
18686            }
18687        });
18688    }
18689
18690    private void loadPrivatePackagesInner(VolumeInfo vol) {
18691        final String volumeUuid = vol.fsUuid;
18692        if (TextUtils.isEmpty(volumeUuid)) {
18693            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18694            return;
18695        }
18696
18697        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18698        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18699        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18700
18701        final VersionInfo ver;
18702        final List<PackageSetting> packages;
18703        synchronized (mPackages) {
18704            ver = mSettings.findOrCreateVersion(volumeUuid);
18705            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18706        }
18707
18708        for (PackageSetting ps : packages) {
18709            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18710            synchronized (mInstallLock) {
18711                final PackageParser.Package pkg;
18712                try {
18713                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18714                    loaded.add(pkg.applicationInfo);
18715
18716                } catch (PackageManagerException e) {
18717                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18718                }
18719
18720                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18721                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18722                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18723                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18724                }
18725            }
18726        }
18727
18728        // Reconcile app data for all started/unlocked users
18729        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18730        final UserManager um = mContext.getSystemService(UserManager.class);
18731        for (UserInfo user : um.getUsers()) {
18732            final int flags;
18733            if (um.isUserUnlocked(user.id)) {
18734                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18735            } else if (um.isUserRunning(user.id)) {
18736                flags = StorageManager.FLAG_STORAGE_DE;
18737            } else {
18738                continue;
18739            }
18740
18741            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18742            synchronized (mInstallLock) {
18743                reconcileAppsDataLI(volumeUuid, user.id, flags);
18744            }
18745        }
18746
18747        synchronized (mPackages) {
18748            int updateFlags = UPDATE_PERMISSIONS_ALL;
18749            if (ver.sdkVersion != mSdkVersion) {
18750                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18751                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18752                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18753            }
18754            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18755
18756            // Yay, everything is now upgraded
18757            ver.forceCurrent();
18758
18759            mSettings.writeLPr();
18760        }
18761
18762        for (PackageFreezer freezer : freezers) {
18763            freezer.close();
18764        }
18765
18766        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18767        sendResourcesChangedBroadcast(true, false, loaded, null);
18768    }
18769
18770    private void unloadPrivatePackages(final VolumeInfo vol) {
18771        mHandler.post(new Runnable() {
18772            @Override
18773            public void run() {
18774                unloadPrivatePackagesInner(vol);
18775            }
18776        });
18777    }
18778
18779    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18780        final String volumeUuid = vol.fsUuid;
18781        if (TextUtils.isEmpty(volumeUuid)) {
18782            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18783            return;
18784        }
18785
18786        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18787        synchronized (mInstallLock) {
18788        synchronized (mPackages) {
18789            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18790            for (PackageSetting ps : packages) {
18791                if (ps.pkg == null) continue;
18792
18793                final ApplicationInfo info = ps.pkg.applicationInfo;
18794                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18795                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18796
18797                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18798                        "unloadPrivatePackagesInner")) {
18799                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18800                            false, null)) {
18801                        unloaded.add(info);
18802                    } else {
18803                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18804                    }
18805                }
18806            }
18807
18808            mSettings.writeLPr();
18809        }
18810        }
18811
18812        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18813        sendResourcesChangedBroadcast(false, false, unloaded, null);
18814    }
18815
18816    /**
18817     * Prepare storage areas for given user on all mounted devices.
18818     */
18819    void prepareUserData(int userId, int userSerial, int flags) {
18820        synchronized (mInstallLock) {
18821            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18822            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18823                final String volumeUuid = vol.getFsUuid();
18824                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18825            }
18826        }
18827    }
18828
18829    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18830            boolean allowRecover) {
18831        // Prepare storage and verify that serial numbers are consistent; if
18832        // there's a mismatch we need to destroy to avoid leaking data
18833        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18834        try {
18835            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18836
18837            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18838                UserManagerService.enforceSerialNumber(
18839                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18840            }
18841            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18842                UserManagerService.enforceSerialNumber(
18843                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18844            }
18845
18846            synchronized (mInstallLock) {
18847                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18848            }
18849        } catch (Exception e) {
18850            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18851                    + " because we failed to prepare: " + e);
18852            destroyUserDataLI(volumeUuid, userId,
18853                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18854
18855            if (allowRecover) {
18856                // Try one last time; if we fail again we're really in trouble
18857                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18858            }
18859        }
18860    }
18861
18862    /**
18863     * Destroy storage areas for given user on all mounted devices.
18864     */
18865    void destroyUserData(int userId, int flags) {
18866        synchronized (mInstallLock) {
18867            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18868            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18869                final String volumeUuid = vol.getFsUuid();
18870                destroyUserDataLI(volumeUuid, userId, flags);
18871            }
18872        }
18873    }
18874
18875    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18876        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18877        try {
18878            // Clean up app data, profile data, and media data
18879            mInstaller.destroyUserData(volumeUuid, userId, flags);
18880
18881            // Clean up system data
18882            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18883                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18884                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18885                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18886                }
18887                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18888                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18889                }
18890            }
18891
18892            // Data with special labels is now gone, so finish the job
18893            storage.destroyUserStorage(volumeUuid, userId, flags);
18894
18895        } catch (Exception e) {
18896            logCriticalInfo(Log.WARN,
18897                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18898        }
18899    }
18900
18901    /**
18902     * Examine all users present on given mounted volume, and destroy data
18903     * belonging to users that are no longer valid, or whose user ID has been
18904     * recycled.
18905     */
18906    private void reconcileUsers(String volumeUuid) {
18907        final List<File> files = new ArrayList<>();
18908        Collections.addAll(files, FileUtils
18909                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18910        Collections.addAll(files, FileUtils
18911                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18912        for (File file : files) {
18913            if (!file.isDirectory()) continue;
18914
18915            final int userId;
18916            final UserInfo info;
18917            try {
18918                userId = Integer.parseInt(file.getName());
18919                info = sUserManager.getUserInfo(userId);
18920            } catch (NumberFormatException e) {
18921                Slog.w(TAG, "Invalid user directory " + file);
18922                continue;
18923            }
18924
18925            boolean destroyUser = false;
18926            if (info == null) {
18927                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18928                        + " because no matching user was found");
18929                destroyUser = true;
18930            } else if (!mOnlyCore) {
18931                try {
18932                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18933                } catch (IOException e) {
18934                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18935                            + " because we failed to enforce serial number: " + e);
18936                    destroyUser = true;
18937                }
18938            }
18939
18940            if (destroyUser) {
18941                synchronized (mInstallLock) {
18942                    destroyUserDataLI(volumeUuid, userId,
18943                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18944                }
18945            }
18946        }
18947    }
18948
18949    private void assertPackageKnown(String volumeUuid, String packageName)
18950            throws PackageManagerException {
18951        synchronized (mPackages) {
18952            final PackageSetting ps = mSettings.mPackages.get(packageName);
18953            if (ps == null) {
18954                throw new PackageManagerException("Package " + packageName + " is unknown");
18955            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18956                throw new PackageManagerException(
18957                        "Package " + packageName + " found on unknown volume " + volumeUuid
18958                                + "; expected volume " + ps.volumeUuid);
18959            }
18960        }
18961    }
18962
18963    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18964            throws PackageManagerException {
18965        synchronized (mPackages) {
18966            final PackageSetting ps = mSettings.mPackages.get(packageName);
18967            if (ps == null) {
18968                throw new PackageManagerException("Package " + packageName + " is unknown");
18969            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18970                throw new PackageManagerException(
18971                        "Package " + packageName + " found on unknown volume " + volumeUuid
18972                                + "; expected volume " + ps.volumeUuid);
18973            } else if (!ps.getInstalled(userId)) {
18974                throw new PackageManagerException(
18975                        "Package " + packageName + " not installed for user " + userId);
18976            }
18977        }
18978    }
18979
18980    /**
18981     * Examine all apps present on given mounted volume, and destroy apps that
18982     * aren't expected, either due to uninstallation or reinstallation on
18983     * another volume.
18984     */
18985    private void reconcileApps(String volumeUuid) {
18986        final File[] files = FileUtils
18987                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18988        for (File file : files) {
18989            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18990                    && !PackageInstallerService.isStageName(file.getName());
18991            if (!isPackage) {
18992                // Ignore entries which are not packages
18993                continue;
18994            }
18995
18996            try {
18997                final PackageLite pkg = PackageParser.parsePackageLite(file,
18998                        PackageParser.PARSE_MUST_BE_APK);
18999                assertPackageKnown(volumeUuid, pkg.packageName);
19000
19001            } catch (PackageParserException | PackageManagerException e) {
19002                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19003                synchronized (mInstallLock) {
19004                    removeCodePathLI(file);
19005                }
19006            }
19007        }
19008    }
19009
19010    /**
19011     * Reconcile all app data for the given user.
19012     * <p>
19013     * Verifies that directories exist and that ownership and labeling is
19014     * correct for all installed apps on all mounted volumes.
19015     */
19016    void reconcileAppsData(int userId, int flags) {
19017        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19018        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19019            final String volumeUuid = vol.getFsUuid();
19020            synchronized (mInstallLock) {
19021                reconcileAppsDataLI(volumeUuid, userId, flags);
19022            }
19023        }
19024    }
19025
19026    /**
19027     * Reconcile all app data on given mounted volume.
19028     * <p>
19029     * Destroys app data that isn't expected, either due to uninstallation or
19030     * reinstallation on another volume.
19031     * <p>
19032     * Verifies that directories exist and that ownership and labeling is
19033     * correct for all installed apps.
19034     */
19035    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19036        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19037                + Integer.toHexString(flags));
19038
19039        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19040        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19041
19042        boolean restoreconNeeded = false;
19043
19044        // First look for stale data that doesn't belong, and check if things
19045        // have changed since we did our last restorecon
19046        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19047            if (!isUserKeyUnlocked(userId)) {
19048                throw new RuntimeException(
19049                        "Yikes, someone asked us to reconcile CE storage while " + userId
19050                                + " was still locked; this would have caused massive data loss!");
19051            }
19052
19053            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19054
19055            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19056            for (File file : files) {
19057                final String packageName = file.getName();
19058                try {
19059                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19060                } catch (PackageManagerException e) {
19061                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19062                    try {
19063                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19064                                StorageManager.FLAG_STORAGE_CE, 0);
19065                    } catch (InstallerException e2) {
19066                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19067                    }
19068                }
19069            }
19070        }
19071        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19072            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19073
19074            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19075            for (File file : files) {
19076                final String packageName = file.getName();
19077                try {
19078                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19079                } catch (PackageManagerException e) {
19080                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19081                    try {
19082                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19083                                StorageManager.FLAG_STORAGE_DE, 0);
19084                    } catch (InstallerException e2) {
19085                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19086                    }
19087                }
19088            }
19089        }
19090
19091        // Ensure that data directories are ready to roll for all packages
19092        // installed for this volume and user
19093        final List<PackageSetting> packages;
19094        synchronized (mPackages) {
19095            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19096        }
19097        int preparedCount = 0;
19098        for (PackageSetting ps : packages) {
19099            final String packageName = ps.name;
19100            if (ps.pkg == null) {
19101                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19102                // TODO: might be due to legacy ASEC apps; we should circle back
19103                // and reconcile again once they're scanned
19104                continue;
19105            }
19106
19107            if (ps.getInstalled(userId)) {
19108                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19109
19110                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19111                    // We may have just shuffled around app data directories, so
19112                    // prepare them one more time
19113                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19114                }
19115
19116                preparedCount++;
19117            }
19118        }
19119
19120        if (restoreconNeeded) {
19121            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19122                SELinuxMMAC.setRestoreconDone(ceDir);
19123            }
19124            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19125                SELinuxMMAC.setRestoreconDone(deDir);
19126            }
19127        }
19128
19129        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19130                + " packages; restoreconNeeded was " + restoreconNeeded);
19131    }
19132
19133    /**
19134     * Prepare app data for the given app just after it was installed or
19135     * upgraded. This method carefully only touches users that it's installed
19136     * for, and it forces a restorecon to handle any seinfo changes.
19137     * <p>
19138     * Verifies that directories exist and that ownership and labeling is
19139     * correct for all installed apps. If there is an ownership mismatch, it
19140     * will try recovering system apps by wiping data; third-party app data is
19141     * left intact.
19142     * <p>
19143     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19144     */
19145    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19146        final PackageSetting ps;
19147        synchronized (mPackages) {
19148            ps = mSettings.mPackages.get(pkg.packageName);
19149            mSettings.writeKernelMappingLPr(ps);
19150        }
19151
19152        final UserManager um = mContext.getSystemService(UserManager.class);
19153        for (UserInfo user : um.getUsers()) {
19154            final int flags;
19155            if (um.isUserUnlocked(user.id)) {
19156                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19157            } else if (um.isUserRunning(user.id)) {
19158                flags = StorageManager.FLAG_STORAGE_DE;
19159            } else {
19160                continue;
19161            }
19162
19163            if (ps.getInstalled(user.id)) {
19164                // Whenever an app changes, force a restorecon of its data
19165                // TODO: when user data is locked, mark that we're still dirty
19166                prepareAppDataLIF(pkg, user.id, flags, true);
19167            }
19168        }
19169    }
19170
19171    /**
19172     * Prepare app data for the given app.
19173     * <p>
19174     * Verifies that directories exist and that ownership and labeling is
19175     * correct for all installed apps. If there is an ownership mismatch, this
19176     * will try recovering system apps by wiping data; third-party app data is
19177     * left intact.
19178     */
19179    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19180            boolean restoreconNeeded) {
19181        if (pkg == null) {
19182            Slog.wtf(TAG, "Package was null!", new Throwable());
19183            return;
19184        }
19185        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19186        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19187        for (int i = 0; i < childCount; i++) {
19188            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19189        }
19190    }
19191
19192    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19193            boolean restoreconNeeded) {
19194        if (DEBUG_APP_DATA) {
19195            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19196                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19197        }
19198
19199        final String volumeUuid = pkg.volumeUuid;
19200        final String packageName = pkg.packageName;
19201        final ApplicationInfo app = pkg.applicationInfo;
19202        final int appId = UserHandle.getAppId(app.uid);
19203
19204        Preconditions.checkNotNull(app.seinfo);
19205
19206        try {
19207            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19208                    appId, app.seinfo, app.targetSdkVersion);
19209        } catch (InstallerException e) {
19210            if (app.isSystemApp()) {
19211                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19212                        + ", but trying to recover: " + e);
19213                destroyAppDataLeafLIF(pkg, userId, flags);
19214                try {
19215                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19216                            appId, app.seinfo, app.targetSdkVersion);
19217                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19218                } catch (InstallerException e2) {
19219                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19220                }
19221            } else {
19222                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19223            }
19224        }
19225
19226        if (restoreconNeeded) {
19227            try {
19228                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19229                        app.seinfo);
19230            } catch (InstallerException e) {
19231                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19232            }
19233        }
19234
19235        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19236            try {
19237                // CE storage is unlocked right now, so read out the inode and
19238                // remember for use later when it's locked
19239                // TODO: mark this structure as dirty so we persist it!
19240                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19241                        StorageManager.FLAG_STORAGE_CE);
19242                synchronized (mPackages) {
19243                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19244                    if (ps != null) {
19245                        ps.setCeDataInode(ceDataInode, userId);
19246                    }
19247                }
19248            } catch (InstallerException e) {
19249                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19250            }
19251        }
19252
19253        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19254    }
19255
19256    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19257        if (pkg == null) {
19258            Slog.wtf(TAG, "Package was null!", new Throwable());
19259            return;
19260        }
19261        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19262        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19263        for (int i = 0; i < childCount; i++) {
19264            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19265        }
19266    }
19267
19268    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19269        final String volumeUuid = pkg.volumeUuid;
19270        final String packageName = pkg.packageName;
19271        final ApplicationInfo app = pkg.applicationInfo;
19272
19273        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19274            // Create a native library symlink only if we have native libraries
19275            // and if the native libraries are 32 bit libraries. We do not provide
19276            // this symlink for 64 bit libraries.
19277            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19278                final String nativeLibPath = app.nativeLibraryDir;
19279                try {
19280                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19281                            nativeLibPath, userId);
19282                } catch (InstallerException e) {
19283                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19284                }
19285            }
19286        }
19287    }
19288
19289    /**
19290     * For system apps on non-FBE devices, this method migrates any existing
19291     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19292     * requested by the app.
19293     */
19294    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19295        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19296                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19297            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19298                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19299            try {
19300                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19301                        storageTarget);
19302            } catch (InstallerException e) {
19303                logCriticalInfo(Log.WARN,
19304                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19305            }
19306            return true;
19307        } else {
19308            return false;
19309        }
19310    }
19311
19312    public PackageFreezer freezePackage(String packageName, String killReason) {
19313        return new PackageFreezer(packageName, killReason);
19314    }
19315
19316    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19317            String killReason) {
19318        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19319            return new PackageFreezer();
19320        } else {
19321            return freezePackage(packageName, killReason);
19322        }
19323    }
19324
19325    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19326            String killReason) {
19327        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19328            return new PackageFreezer();
19329        } else {
19330            return freezePackage(packageName, killReason);
19331        }
19332    }
19333
19334    /**
19335     * Class that freezes and kills the given package upon creation, and
19336     * unfreezes it upon closing. This is typically used when doing surgery on
19337     * app code/data to prevent the app from running while you're working.
19338     */
19339    private class PackageFreezer implements AutoCloseable {
19340        private final String mPackageName;
19341        private final PackageFreezer[] mChildren;
19342
19343        private final boolean mWeFroze;
19344
19345        private final AtomicBoolean mClosed = new AtomicBoolean();
19346        private final CloseGuard mCloseGuard = CloseGuard.get();
19347
19348        /**
19349         * Create and return a stub freezer that doesn't actually do anything,
19350         * typically used when someone requested
19351         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19352         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19353         */
19354        public PackageFreezer() {
19355            mPackageName = null;
19356            mChildren = null;
19357            mWeFroze = false;
19358            mCloseGuard.open("close");
19359        }
19360
19361        public PackageFreezer(String packageName, String killReason) {
19362            synchronized (mPackages) {
19363                mPackageName = packageName;
19364                mWeFroze = mFrozenPackages.add(mPackageName);
19365
19366                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19367                if (ps != null) {
19368                    killApplication(ps.name, ps.appId, killReason);
19369                }
19370
19371                final PackageParser.Package p = mPackages.get(packageName);
19372                if (p != null && p.childPackages != null) {
19373                    final int N = p.childPackages.size();
19374                    mChildren = new PackageFreezer[N];
19375                    for (int i = 0; i < N; i++) {
19376                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19377                                killReason);
19378                    }
19379                } else {
19380                    mChildren = null;
19381                }
19382            }
19383            mCloseGuard.open("close");
19384        }
19385
19386        @Override
19387        protected void finalize() throws Throwable {
19388            try {
19389                mCloseGuard.warnIfOpen();
19390                close();
19391            } finally {
19392                super.finalize();
19393            }
19394        }
19395
19396        @Override
19397        public void close() {
19398            mCloseGuard.close();
19399            if (mClosed.compareAndSet(false, true)) {
19400                synchronized (mPackages) {
19401                    if (mWeFroze) {
19402                        mFrozenPackages.remove(mPackageName);
19403                    }
19404
19405                    if (mChildren != null) {
19406                        for (PackageFreezer freezer : mChildren) {
19407                            freezer.close();
19408                        }
19409                    }
19410                }
19411            }
19412        }
19413    }
19414
19415    /**
19416     * Verify that given package is currently frozen.
19417     */
19418    private void checkPackageFrozen(String packageName) {
19419        synchronized (mPackages) {
19420            if (!mFrozenPackages.contains(packageName)) {
19421                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19422            }
19423        }
19424    }
19425
19426    @Override
19427    public int movePackage(final String packageName, final String volumeUuid) {
19428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19429
19430        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19431        final int moveId = mNextMoveId.getAndIncrement();
19432        mHandler.post(new Runnable() {
19433            @Override
19434            public void run() {
19435                try {
19436                    movePackageInternal(packageName, volumeUuid, moveId, user);
19437                } catch (PackageManagerException e) {
19438                    Slog.w(TAG, "Failed to move " + packageName, e);
19439                    mMoveCallbacks.notifyStatusChanged(moveId,
19440                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19441                }
19442            }
19443        });
19444        return moveId;
19445    }
19446
19447    private void movePackageInternal(final String packageName, final String volumeUuid,
19448            final int moveId, UserHandle user) throws PackageManagerException {
19449        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19450        final PackageManager pm = mContext.getPackageManager();
19451
19452        final boolean currentAsec;
19453        final String currentVolumeUuid;
19454        final File codeFile;
19455        final String installerPackageName;
19456        final String packageAbiOverride;
19457        final int appId;
19458        final String seinfo;
19459        final String label;
19460        final int targetSdkVersion;
19461        final PackageFreezer freezer;
19462
19463        // reader
19464        synchronized (mPackages) {
19465            final PackageParser.Package pkg = mPackages.get(packageName);
19466            final PackageSetting ps = mSettings.mPackages.get(packageName);
19467            if (pkg == null || ps == null) {
19468                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19469            }
19470
19471            if (pkg.applicationInfo.isSystemApp()) {
19472                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19473                        "Cannot move system application");
19474            }
19475
19476            if (pkg.applicationInfo.isExternalAsec()) {
19477                currentAsec = true;
19478                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19479            } else if (pkg.applicationInfo.isForwardLocked()) {
19480                currentAsec = true;
19481                currentVolumeUuid = "forward_locked";
19482            } else {
19483                currentAsec = false;
19484                currentVolumeUuid = ps.volumeUuid;
19485
19486                final File probe = new File(pkg.codePath);
19487                final File probeOat = new File(probe, "oat");
19488                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19489                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19490                            "Move only supported for modern cluster style installs");
19491                }
19492            }
19493
19494            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19495                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19496                        "Package already moved to " + volumeUuid);
19497            }
19498            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19499                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19500                        "Device admin cannot be moved");
19501            }
19502
19503            if (mFrozenPackages.contains(packageName)) {
19504                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19505                        "Failed to move already frozen package");
19506            }
19507
19508            codeFile = new File(pkg.codePath);
19509            installerPackageName = ps.installerPackageName;
19510            packageAbiOverride = ps.cpuAbiOverrideString;
19511            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19512            seinfo = pkg.applicationInfo.seinfo;
19513            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19514            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19515            freezer = new PackageFreezer(packageName, "movePackageInternal");
19516        }
19517
19518        final Bundle extras = new Bundle();
19519        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19520        extras.putString(Intent.EXTRA_TITLE, label);
19521        mMoveCallbacks.notifyCreated(moveId, extras);
19522
19523        int installFlags;
19524        final boolean moveCompleteApp;
19525        final File measurePath;
19526
19527        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19528            installFlags = INSTALL_INTERNAL;
19529            moveCompleteApp = !currentAsec;
19530            measurePath = Environment.getDataAppDirectory(volumeUuid);
19531        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19532            installFlags = INSTALL_EXTERNAL;
19533            moveCompleteApp = false;
19534            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19535        } else {
19536            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19537            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19538                    || !volume.isMountedWritable()) {
19539                freezer.close();
19540                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19541                        "Move location not mounted private volume");
19542            }
19543
19544            Preconditions.checkState(!currentAsec);
19545
19546            installFlags = INSTALL_INTERNAL;
19547            moveCompleteApp = true;
19548            measurePath = Environment.getDataAppDirectory(volumeUuid);
19549        }
19550
19551        final PackageStats stats = new PackageStats(null, -1);
19552        synchronized (mInstaller) {
19553            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19554                freezer.close();
19555                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19556                        "Failed to measure package size");
19557            }
19558        }
19559
19560        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19561                + stats.dataSize);
19562
19563        final long startFreeBytes = measurePath.getFreeSpace();
19564        final long sizeBytes;
19565        if (moveCompleteApp) {
19566            sizeBytes = stats.codeSize + stats.dataSize;
19567        } else {
19568            sizeBytes = stats.codeSize;
19569        }
19570
19571        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19572            freezer.close();
19573            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19574                    "Not enough free space to move");
19575        }
19576
19577        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19578
19579        final CountDownLatch installedLatch = new CountDownLatch(1);
19580        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19581            @Override
19582            public void onUserActionRequired(Intent intent) throws RemoteException {
19583                throw new IllegalStateException();
19584            }
19585
19586            @Override
19587            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19588                    Bundle extras) throws RemoteException {
19589                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19590                        + PackageManager.installStatusToString(returnCode, msg));
19591
19592                installedLatch.countDown();
19593                freezer.close();
19594
19595                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19596                switch (status) {
19597                    case PackageInstaller.STATUS_SUCCESS:
19598                        mMoveCallbacks.notifyStatusChanged(moveId,
19599                                PackageManager.MOVE_SUCCEEDED);
19600                        break;
19601                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19602                        mMoveCallbacks.notifyStatusChanged(moveId,
19603                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19604                        break;
19605                    default:
19606                        mMoveCallbacks.notifyStatusChanged(moveId,
19607                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19608                        break;
19609                }
19610            }
19611        };
19612
19613        final MoveInfo move;
19614        if (moveCompleteApp) {
19615            // Kick off a thread to report progress estimates
19616            new Thread() {
19617                @Override
19618                public void run() {
19619                    while (true) {
19620                        try {
19621                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19622                                break;
19623                            }
19624                        } catch (InterruptedException ignored) {
19625                        }
19626
19627                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19628                        final int progress = 10 + (int) MathUtils.constrain(
19629                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19630                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19631                    }
19632                }
19633            }.start();
19634
19635            final String dataAppName = codeFile.getName();
19636            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19637                    dataAppName, appId, seinfo, targetSdkVersion);
19638        } else {
19639            move = null;
19640        }
19641
19642        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19643
19644        final Message msg = mHandler.obtainMessage(INIT_COPY);
19645        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19646        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19647                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19648                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19649        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19650        msg.obj = params;
19651
19652        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19653                System.identityHashCode(msg.obj));
19654        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19655                System.identityHashCode(msg.obj));
19656
19657        mHandler.sendMessage(msg);
19658    }
19659
19660    @Override
19661    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19662        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19663
19664        final int realMoveId = mNextMoveId.getAndIncrement();
19665        final Bundle extras = new Bundle();
19666        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19667        mMoveCallbacks.notifyCreated(realMoveId, extras);
19668
19669        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19670            @Override
19671            public void onCreated(int moveId, Bundle extras) {
19672                // Ignored
19673            }
19674
19675            @Override
19676            public void onStatusChanged(int moveId, int status, long estMillis) {
19677                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19678            }
19679        };
19680
19681        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19682        storage.setPrimaryStorageUuid(volumeUuid, callback);
19683        return realMoveId;
19684    }
19685
19686    @Override
19687    public int getMoveStatus(int moveId) {
19688        mContext.enforceCallingOrSelfPermission(
19689                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19690        return mMoveCallbacks.mLastStatus.get(moveId);
19691    }
19692
19693    @Override
19694    public void registerMoveCallback(IPackageMoveObserver callback) {
19695        mContext.enforceCallingOrSelfPermission(
19696                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19697        mMoveCallbacks.register(callback);
19698    }
19699
19700    @Override
19701    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19702        mContext.enforceCallingOrSelfPermission(
19703                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19704        mMoveCallbacks.unregister(callback);
19705    }
19706
19707    @Override
19708    public boolean setInstallLocation(int loc) {
19709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19710                null);
19711        if (getInstallLocation() == loc) {
19712            return true;
19713        }
19714        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19715                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19716            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19717                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19718            return true;
19719        }
19720        return false;
19721   }
19722
19723    @Override
19724    public int getInstallLocation() {
19725        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19726                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19727                PackageHelper.APP_INSTALL_AUTO);
19728    }
19729
19730    /** Called by UserManagerService */
19731    void cleanUpUser(UserManagerService userManager, int userHandle) {
19732        synchronized (mPackages) {
19733            mDirtyUsers.remove(userHandle);
19734            mUserNeedsBadging.delete(userHandle);
19735            mSettings.removeUserLPw(userHandle);
19736            mPendingBroadcasts.remove(userHandle);
19737            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19738            removeUnusedPackagesLPw(userManager, userHandle);
19739        }
19740    }
19741
19742    /**
19743     * We're removing userHandle and would like to remove any downloaded packages
19744     * that are no longer in use by any other user.
19745     * @param userHandle the user being removed
19746     */
19747    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19748        final boolean DEBUG_CLEAN_APKS = false;
19749        int [] users = userManager.getUserIds();
19750        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19751        while (psit.hasNext()) {
19752            PackageSetting ps = psit.next();
19753            if (ps.pkg == null) {
19754                continue;
19755            }
19756            final String packageName = ps.pkg.packageName;
19757            // Skip over if system app
19758            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19759                continue;
19760            }
19761            if (DEBUG_CLEAN_APKS) {
19762                Slog.i(TAG, "Checking package " + packageName);
19763            }
19764            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19765            if (keep) {
19766                if (DEBUG_CLEAN_APKS) {
19767                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19768                }
19769            } else {
19770                for (int i = 0; i < users.length; i++) {
19771                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19772                        keep = true;
19773                        if (DEBUG_CLEAN_APKS) {
19774                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19775                                    + users[i]);
19776                        }
19777                        break;
19778                    }
19779                }
19780            }
19781            if (!keep) {
19782                if (DEBUG_CLEAN_APKS) {
19783                    Slog.i(TAG, "  Removing package " + packageName);
19784                }
19785                mHandler.post(new Runnable() {
19786                    public void run() {
19787                        deletePackageX(packageName, userHandle, 0);
19788                    } //end run
19789                });
19790            }
19791        }
19792    }
19793
19794    /** Called by UserManagerService */
19795    void createNewUser(int userHandle) {
19796        synchronized (mInstallLock) {
19797            mSettings.createNewUserLI(this, mInstaller, userHandle);
19798        }
19799        synchronized (mPackages) {
19800            applyFactoryDefaultBrowserLPw(userHandle);
19801            primeDomainVerificationsLPw(userHandle);
19802        }
19803    }
19804
19805    void newUserCreated(final int userHandle) {
19806        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19807        // If permission review for legacy apps is required, we represent
19808        // dagerous permissions for such apps as always granted runtime
19809        // permissions to keep per user flag state whether review is needed.
19810        // Hence, if a new user is added we have to propagate dangerous
19811        // permission grants for these legacy apps.
19812        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19813            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19814                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19815        }
19816    }
19817
19818    @Override
19819    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19820        mContext.enforceCallingOrSelfPermission(
19821                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19822                "Only package verification agents can read the verifier device identity");
19823
19824        synchronized (mPackages) {
19825            return mSettings.getVerifierDeviceIdentityLPw();
19826        }
19827    }
19828
19829    @Override
19830    public void setPermissionEnforced(String permission, boolean enforced) {
19831        // TODO: Now that we no longer change GID for storage, this should to away.
19832        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19833                "setPermissionEnforced");
19834        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19835            synchronized (mPackages) {
19836                if (mSettings.mReadExternalStorageEnforced == null
19837                        || mSettings.mReadExternalStorageEnforced != enforced) {
19838                    mSettings.mReadExternalStorageEnforced = enforced;
19839                    mSettings.writeLPr();
19840                }
19841            }
19842            // kill any non-foreground processes so we restart them and
19843            // grant/revoke the GID.
19844            final IActivityManager am = ActivityManagerNative.getDefault();
19845            if (am != null) {
19846                final long token = Binder.clearCallingIdentity();
19847                try {
19848                    am.killProcessesBelowForeground("setPermissionEnforcement");
19849                } catch (RemoteException e) {
19850                } finally {
19851                    Binder.restoreCallingIdentity(token);
19852                }
19853            }
19854        } else {
19855            throw new IllegalArgumentException("No selective enforcement for " + permission);
19856        }
19857    }
19858
19859    @Override
19860    @Deprecated
19861    public boolean isPermissionEnforced(String permission) {
19862        return true;
19863    }
19864
19865    @Override
19866    public boolean isStorageLow() {
19867        final long token = Binder.clearCallingIdentity();
19868        try {
19869            final DeviceStorageMonitorInternal
19870                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19871            if (dsm != null) {
19872                return dsm.isMemoryLow();
19873            } else {
19874                return false;
19875            }
19876        } finally {
19877            Binder.restoreCallingIdentity(token);
19878        }
19879    }
19880
19881    @Override
19882    public IPackageInstaller getPackageInstaller() {
19883        return mInstallerService;
19884    }
19885
19886    private boolean userNeedsBadging(int userId) {
19887        int index = mUserNeedsBadging.indexOfKey(userId);
19888        if (index < 0) {
19889            final UserInfo userInfo;
19890            final long token = Binder.clearCallingIdentity();
19891            try {
19892                userInfo = sUserManager.getUserInfo(userId);
19893            } finally {
19894                Binder.restoreCallingIdentity(token);
19895            }
19896            final boolean b;
19897            if (userInfo != null && userInfo.isManagedProfile()) {
19898                b = true;
19899            } else {
19900                b = false;
19901            }
19902            mUserNeedsBadging.put(userId, b);
19903            return b;
19904        }
19905        return mUserNeedsBadging.valueAt(index);
19906    }
19907
19908    @Override
19909    public KeySet getKeySetByAlias(String packageName, String alias) {
19910        if (packageName == null || alias == null) {
19911            return null;
19912        }
19913        synchronized(mPackages) {
19914            final PackageParser.Package pkg = mPackages.get(packageName);
19915            if (pkg == null) {
19916                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19917                throw new IllegalArgumentException("Unknown package: " + packageName);
19918            }
19919            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19920            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19921        }
19922    }
19923
19924    @Override
19925    public KeySet getSigningKeySet(String packageName) {
19926        if (packageName == null) {
19927            return null;
19928        }
19929        synchronized(mPackages) {
19930            final PackageParser.Package pkg = mPackages.get(packageName);
19931            if (pkg == null) {
19932                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19933                throw new IllegalArgumentException("Unknown package: " + packageName);
19934            }
19935            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19936                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19937                throw new SecurityException("May not access signing KeySet of other apps.");
19938            }
19939            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19940            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19941        }
19942    }
19943
19944    @Override
19945    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19946        if (packageName == null || ks == null) {
19947            return false;
19948        }
19949        synchronized(mPackages) {
19950            final PackageParser.Package pkg = mPackages.get(packageName);
19951            if (pkg == null) {
19952                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19953                throw new IllegalArgumentException("Unknown package: " + packageName);
19954            }
19955            IBinder ksh = ks.getToken();
19956            if (ksh instanceof KeySetHandle) {
19957                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19958                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19959            }
19960            return false;
19961        }
19962    }
19963
19964    @Override
19965    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19966        if (packageName == null || ks == null) {
19967            return false;
19968        }
19969        synchronized(mPackages) {
19970            final PackageParser.Package pkg = mPackages.get(packageName);
19971            if (pkg == null) {
19972                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19973                throw new IllegalArgumentException("Unknown package: " + packageName);
19974            }
19975            IBinder ksh = ks.getToken();
19976            if (ksh instanceof KeySetHandle) {
19977                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19978                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19979            }
19980            return false;
19981        }
19982    }
19983
19984    private void deletePackageIfUnusedLPr(final String packageName) {
19985        PackageSetting ps = mSettings.mPackages.get(packageName);
19986        if (ps == null) {
19987            return;
19988        }
19989        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19990            // TODO Implement atomic delete if package is unused
19991            // It is currently possible that the package will be deleted even if it is installed
19992            // after this method returns.
19993            mHandler.post(new Runnable() {
19994                public void run() {
19995                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19996                }
19997            });
19998        }
19999    }
20000
20001    /**
20002     * Check and throw if the given before/after packages would be considered a
20003     * downgrade.
20004     */
20005    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20006            throws PackageManagerException {
20007        if (after.versionCode < before.mVersionCode) {
20008            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20009                    "Update version code " + after.versionCode + " is older than current "
20010                    + before.mVersionCode);
20011        } else if (after.versionCode == before.mVersionCode) {
20012            if (after.baseRevisionCode < before.baseRevisionCode) {
20013                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20014                        "Update base revision code " + after.baseRevisionCode
20015                        + " is older than current " + before.baseRevisionCode);
20016            }
20017
20018            if (!ArrayUtils.isEmpty(after.splitNames)) {
20019                for (int i = 0; i < after.splitNames.length; i++) {
20020                    final String splitName = after.splitNames[i];
20021                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20022                    if (j != -1) {
20023                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20024                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20025                                    "Update split " + splitName + " revision code "
20026                                    + after.splitRevisionCodes[i] + " is older than current "
20027                                    + before.splitRevisionCodes[j]);
20028                        }
20029                    }
20030                }
20031            }
20032        }
20033    }
20034
20035    private static class MoveCallbacks extends Handler {
20036        private static final int MSG_CREATED = 1;
20037        private static final int MSG_STATUS_CHANGED = 2;
20038
20039        private final RemoteCallbackList<IPackageMoveObserver>
20040                mCallbacks = new RemoteCallbackList<>();
20041
20042        private final SparseIntArray mLastStatus = new SparseIntArray();
20043
20044        public MoveCallbacks(Looper looper) {
20045            super(looper);
20046        }
20047
20048        public void register(IPackageMoveObserver callback) {
20049            mCallbacks.register(callback);
20050        }
20051
20052        public void unregister(IPackageMoveObserver callback) {
20053            mCallbacks.unregister(callback);
20054        }
20055
20056        @Override
20057        public void handleMessage(Message msg) {
20058            final SomeArgs args = (SomeArgs) msg.obj;
20059            final int n = mCallbacks.beginBroadcast();
20060            for (int i = 0; i < n; i++) {
20061                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20062                try {
20063                    invokeCallback(callback, msg.what, args);
20064                } catch (RemoteException ignored) {
20065                }
20066            }
20067            mCallbacks.finishBroadcast();
20068            args.recycle();
20069        }
20070
20071        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20072                throws RemoteException {
20073            switch (what) {
20074                case MSG_CREATED: {
20075                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20076                    break;
20077                }
20078                case MSG_STATUS_CHANGED: {
20079                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20080                    break;
20081                }
20082            }
20083        }
20084
20085        private void notifyCreated(int moveId, Bundle extras) {
20086            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20087
20088            final SomeArgs args = SomeArgs.obtain();
20089            args.argi1 = moveId;
20090            args.arg2 = extras;
20091            obtainMessage(MSG_CREATED, args).sendToTarget();
20092        }
20093
20094        private void notifyStatusChanged(int moveId, int status) {
20095            notifyStatusChanged(moveId, status, -1);
20096        }
20097
20098        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20099            Slog.v(TAG, "Move " + moveId + " status " + status);
20100
20101            final SomeArgs args = SomeArgs.obtain();
20102            args.argi1 = moveId;
20103            args.argi2 = status;
20104            args.arg3 = estMillis;
20105            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20106
20107            synchronized (mLastStatus) {
20108                mLastStatus.put(moveId, status);
20109            }
20110        }
20111    }
20112
20113    private final static class OnPermissionChangeListeners extends Handler {
20114        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20115
20116        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20117                new RemoteCallbackList<>();
20118
20119        public OnPermissionChangeListeners(Looper looper) {
20120            super(looper);
20121        }
20122
20123        @Override
20124        public void handleMessage(Message msg) {
20125            switch (msg.what) {
20126                case MSG_ON_PERMISSIONS_CHANGED: {
20127                    final int uid = msg.arg1;
20128                    handleOnPermissionsChanged(uid);
20129                } break;
20130            }
20131        }
20132
20133        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20134            mPermissionListeners.register(listener);
20135
20136        }
20137
20138        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20139            mPermissionListeners.unregister(listener);
20140        }
20141
20142        public void onPermissionsChanged(int uid) {
20143            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20144                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20145            }
20146        }
20147
20148        private void handleOnPermissionsChanged(int uid) {
20149            final int count = mPermissionListeners.beginBroadcast();
20150            try {
20151                for (int i = 0; i < count; i++) {
20152                    IOnPermissionsChangeListener callback = mPermissionListeners
20153                            .getBroadcastItem(i);
20154                    try {
20155                        callback.onPermissionsChanged(uid);
20156                    } catch (RemoteException e) {
20157                        Log.e(TAG, "Permission listener is dead", e);
20158                    }
20159                }
20160            } finally {
20161                mPermissionListeners.finishBroadcast();
20162            }
20163        }
20164    }
20165
20166    private class PackageManagerInternalImpl extends PackageManagerInternal {
20167        @Override
20168        public void setLocationPackagesProvider(PackagesProvider provider) {
20169            synchronized (mPackages) {
20170                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20171            }
20172        }
20173
20174        @Override
20175        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20176            synchronized (mPackages) {
20177                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20178            }
20179        }
20180
20181        @Override
20182        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20183            synchronized (mPackages) {
20184                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20185            }
20186        }
20187
20188        @Override
20189        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20190            synchronized (mPackages) {
20191                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20192            }
20193        }
20194
20195        @Override
20196        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20197            synchronized (mPackages) {
20198                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20199            }
20200        }
20201
20202        @Override
20203        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20204            synchronized (mPackages) {
20205                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20206            }
20207        }
20208
20209        @Override
20210        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20211            synchronized (mPackages) {
20212                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20213                        packageName, userId);
20214            }
20215        }
20216
20217        @Override
20218        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20219            synchronized (mPackages) {
20220                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20221                        packageName, userId);
20222            }
20223        }
20224
20225        @Override
20226        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20227            synchronized (mPackages) {
20228                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20229                        packageName, userId);
20230            }
20231        }
20232
20233        @Override
20234        public void setKeepUninstalledPackages(final List<String> packageList) {
20235            Preconditions.checkNotNull(packageList);
20236            List<String> removedFromList = null;
20237            synchronized (mPackages) {
20238                if (mKeepUninstalledPackages != null) {
20239                    final int packagesCount = mKeepUninstalledPackages.size();
20240                    for (int i = 0; i < packagesCount; i++) {
20241                        String oldPackage = mKeepUninstalledPackages.get(i);
20242                        if (packageList != null && packageList.contains(oldPackage)) {
20243                            continue;
20244                        }
20245                        if (removedFromList == null) {
20246                            removedFromList = new ArrayList<>();
20247                        }
20248                        removedFromList.add(oldPackage);
20249                    }
20250                }
20251                mKeepUninstalledPackages = new ArrayList<>(packageList);
20252                if (removedFromList != null) {
20253                    final int removedCount = removedFromList.size();
20254                    for (int i = 0; i < removedCount; i++) {
20255                        deletePackageIfUnusedLPr(removedFromList.get(i));
20256                    }
20257                }
20258            }
20259        }
20260
20261        @Override
20262        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20263            synchronized (mPackages) {
20264                // If we do not support permission review, done.
20265                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20266                    return false;
20267                }
20268
20269                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20270                if (packageSetting == null) {
20271                    return false;
20272                }
20273
20274                // Permission review applies only to apps not supporting the new permission model.
20275                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20276                    return false;
20277                }
20278
20279                // Legacy apps have the permission and get user consent on launch.
20280                PermissionsState permissionsState = packageSetting.getPermissionsState();
20281                return permissionsState.isPermissionReviewRequired(userId);
20282            }
20283        }
20284
20285        @Override
20286        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20287            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20288        }
20289
20290        @Override
20291        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20292                int userId) {
20293            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20294        }
20295    }
20296
20297    @Override
20298    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20299        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20300        synchronized (mPackages) {
20301            final long identity = Binder.clearCallingIdentity();
20302            try {
20303                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20304                        packageNames, userId);
20305            } finally {
20306                Binder.restoreCallingIdentity(identity);
20307            }
20308        }
20309    }
20310
20311    private static void enforceSystemOrPhoneCaller(String tag) {
20312        int callingUid = Binder.getCallingUid();
20313        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20314            throw new SecurityException(
20315                    "Cannot call " + tag + " from UID " + callingUid);
20316        }
20317    }
20318
20319    boolean isHistoricalPackageUsageAvailable() {
20320        return mPackageUsage.isHistoricalPackageUsageAvailable();
20321    }
20322
20323    /**
20324     * Return a <b>copy</b> of the collection of packages known to the package manager.
20325     * @return A copy of the values of mPackages.
20326     */
20327    Collection<PackageParser.Package> getPackages() {
20328        synchronized (mPackages) {
20329            return new ArrayList<>(mPackages.values());
20330        }
20331    }
20332
20333    /**
20334     * Logs process start information (including base APK hash) to the security log.
20335     * @hide
20336     */
20337    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20338            String apkFile, int pid) {
20339        if (!SecurityLog.isLoggingEnabled()) {
20340            return;
20341        }
20342        Bundle data = new Bundle();
20343        data.putLong("startTimestamp", System.currentTimeMillis());
20344        data.putString("processName", processName);
20345        data.putInt("uid", uid);
20346        data.putString("seinfo", seinfo);
20347        data.putString("apkFile", apkFile);
20348        data.putInt("pid", pid);
20349        Message msg = mProcessLoggingHandler.obtainMessage(
20350                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20351        msg.setData(data);
20352        mProcessLoggingHandler.sendMessage(msg);
20353    }
20354}
20355