PackageManagerService.java revision f9e2ad0b3c2efb3bd93bb8b4ce2580512563005a
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.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.annotation.UserIdInt;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
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.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.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.logging.MetricsLogger;
229import com.android.internal.os.IParcelFileDescriptorFactory;
230import com.android.internal.os.InstallerConnection.InstallerException;
231import com.android.internal.os.SomeArgs;
232import com.android.internal.os.Zygote;
233import com.android.internal.telephony.CarrierAppUtils;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.AttributeCache;
241import com.android.server.EventLogTags;
242import com.android.server.FgThread;
243import com.android.server.IntentResolver;
244import com.android.server.LocalServices;
245import com.android.server.ServiceThread;
246import com.android.server.SystemConfig;
247import com.android.server.Watchdog;
248import com.android.server.net.NetworkPolicyManagerInternal;
249import com.android.server.pm.PermissionsState.PermissionState;
250import com.android.server.pm.Settings.DatabaseVersion;
251import com.android.server.pm.Settings.VersionInfo;
252import com.android.server.storage.DeviceStorageMonitorInternal;
253
254import dalvik.system.CloseGuard;
255import dalvik.system.DexFile;
256import dalvik.system.VMRuntime;
257
258import libcore.io.IoUtils;
259import libcore.util.EmptyArray;
260
261import org.xmlpull.v1.XmlPullParser;
262import org.xmlpull.v1.XmlPullParserException;
263import org.xmlpull.v1.XmlSerializer;
264
265import java.io.BufferedOutputStream;
266import java.io.BufferedReader;
267import java.io.ByteArrayInputStream;
268import java.io.ByteArrayOutputStream;
269import java.io.File;
270import java.io.FileDescriptor;
271import java.io.FileInputStream;
272import java.io.FileNotFoundException;
273import java.io.FileOutputStream;
274import java.io.FileReader;
275import java.io.FilenameFilter;
276import java.io.IOException;
277import java.io.PrintWriter;
278import java.nio.charset.StandardCharsets;
279import java.security.DigestInputStream;
280import java.security.MessageDigest;
281import java.security.NoSuchAlgorithmException;
282import java.security.PublicKey;
283import java.security.cert.Certificate;
284import java.security.cert.CertificateEncodingException;
285import java.security.cert.CertificateException;
286import java.text.SimpleDateFormat;
287import java.util.ArrayList;
288import java.util.Arrays;
289import java.util.Collection;
290import java.util.Collections;
291import java.util.Comparator;
292import java.util.Date;
293import java.util.HashSet;
294import java.util.Iterator;
295import java.util.List;
296import java.util.Map;
297import java.util.Objects;
298import java.util.Set;
299import java.util.concurrent.CountDownLatch;
300import java.util.concurrent.TimeUnit;
301import java.util.concurrent.atomic.AtomicBoolean;
302import java.util.concurrent.atomic.AtomicInteger;
303
304/**
305 * Keep track of all those APKs everywhere.
306 * <p>
307 * Internally there are two important locks:
308 * <ul>
309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
310 * and other related state. It is a fine-grained lock that should only be held
311 * momentarily, as it's one of the most contended locks in the system.
312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
313 * operations typically involve heavy lifting of application data on disk. Since
314 * {@code installd} is single-threaded, and it's operations can often be slow,
315 * this lock should never be acquired while already holding {@link #mPackages}.
316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
317 * holding {@link #mInstallLock}.
318 * </ul>
319 * Many internal methods rely on the caller to hold the appropriate locks, and
320 * this contract is expressed through method name suffixes:
321 * <ul>
322 * <li>fooLI(): the caller must hold {@link #mInstallLock}
323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
324 * being modified must be frozen
325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
327 * </ul>
328 * <p>
329 * Because this class is very central to the platform's security; please run all
330 * CTS and unit tests whenever making modifications:
331 *
332 * <pre>
333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
335 * </pre>
336 */
337public class PackageManagerService extends IPackageManager.Stub {
338    static final String TAG = "PackageManager";
339    static final boolean DEBUG_SETTINGS = false;
340    static final boolean DEBUG_PREFERRED = false;
341    static final boolean DEBUG_UPGRADE = false;
342    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
343    private static final boolean DEBUG_BACKUP = false;
344    private static final boolean DEBUG_INSTALL = false;
345    private static final boolean DEBUG_REMOVE = false;
346    private static final boolean DEBUG_BROADCASTS = false;
347    private static final boolean DEBUG_SHOW_INFO = false;
348    private static final boolean DEBUG_PACKAGE_INFO = false;
349    private static final boolean DEBUG_INTENT_MATCHING = false;
350    private static final boolean DEBUG_PACKAGE_SCANNING = false;
351    private static final boolean DEBUG_VERIFY = false;
352    private static final boolean DEBUG_FILTERS = false;
353
354    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
355    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
356    // user, but by default initialize to this.
357    static final boolean DEBUG_DEXOPT = false;
358
359    private static final boolean DEBUG_ABI_SELECTION = false;
360    private static final boolean DEBUG_EPHEMERAL = false;
361    private static final boolean DEBUG_TRIAGED_MISSING = false;
362    private static final boolean DEBUG_APP_DATA = false;
363
364    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
365
366    private static final boolean DISABLE_EPHEMERAL_APPS = true;
367
368    private static final int RADIO_UID = Process.PHONE_UID;
369    private static final int LOG_UID = Process.LOG_UID;
370    private static final int NFC_UID = Process.NFC_UID;
371    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
372    private static final int SHELL_UID = Process.SHELL_UID;
373
374    // Cap the size of permission trees that 3rd party apps can define
375    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
376
377    // Suffix used during package installation when copying/moving
378    // package apks to install directory.
379    private static final String INSTALL_PACKAGE_SUFFIX = "-";
380
381    static final int SCAN_NO_DEX = 1<<1;
382    static final int SCAN_FORCE_DEX = 1<<2;
383    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
384    static final int SCAN_NEW_INSTALL = 1<<4;
385    static final int SCAN_NO_PATHS = 1<<5;
386    static final int SCAN_UPDATE_TIME = 1<<6;
387    static final int SCAN_DEFER_DEX = 1<<7;
388    static final int SCAN_BOOTING = 1<<8;
389    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
390    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
391    static final int SCAN_REPLACING = 1<<11;
392    static final int SCAN_REQUIRE_KNOWN = 1<<12;
393    static final int SCAN_MOVE = 1<<13;
394    static final int SCAN_INITIAL = 1<<14;
395    static final int SCAN_CHECK_ONLY = 1<<15;
396    static final int SCAN_DONT_KILL_APP = 1<<17;
397    static final int SCAN_IGNORE_FROZEN = 1<<18;
398
399    static final int REMOVE_CHATTY = 1<<16;
400
401    private static final int[] EMPTY_INT_ARRAY = new int[0];
402
403    /**
404     * Timeout (in milliseconds) after which the watchdog should declare that
405     * our handler thread is wedged.  The usual default for such things is one
406     * minute but we sometimes do very lengthy I/O operations on this thread,
407     * such as installing multi-gigabyte applications, so ours needs to be longer.
408     */
409    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
410
411    /**
412     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
413     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
414     * settings entry if available, otherwise we use the hardcoded default.  If it's been
415     * more than this long since the last fstrim, we force one during the boot sequence.
416     *
417     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
418     * one gets run at the next available charging+idle time.  This final mandatory
419     * no-fstrim check kicks in only of the other scheduling criteria is never met.
420     */
421    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
422
423    /**
424     * Whether verification is enabled by default.
425     */
426    private static final boolean DEFAULT_VERIFY_ENABLE = true;
427
428    /**
429     * The default maximum time to wait for the verification agent to return in
430     * milliseconds.
431     */
432    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
433
434    /**
435     * The default response for package verification timeout.
436     *
437     * This can be either PackageManager.VERIFICATION_ALLOW or
438     * PackageManager.VERIFICATION_REJECT.
439     */
440    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
441
442    static final String PLATFORM_PACKAGE_NAME = "android";
443
444    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
445
446    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
447            DEFAULT_CONTAINER_PACKAGE,
448            "com.android.defcontainer.DefaultContainerService");
449
450    private static final String KILL_APP_REASON_GIDS_CHANGED =
451            "permission grant or revoke changed gids";
452
453    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
454            "permissions revoked";
455
456    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
457
458    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
459
460    /** Permission grant: not grant the permission. */
461    private static final int GRANT_DENIED = 1;
462
463    /** Permission grant: grant the permission as an install permission. */
464    private static final int GRANT_INSTALL = 2;
465
466    /** Permission grant: grant the permission as a runtime one. */
467    private static final int GRANT_RUNTIME = 3;
468
469    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
470    private static final int GRANT_UPGRADE = 4;
471
472    /** Canonical intent used to identify what counts as a "web browser" app */
473    private static final Intent sBrowserIntent;
474    static {
475        sBrowserIntent = new Intent();
476        sBrowserIntent.setAction(Intent.ACTION_VIEW);
477        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
478        sBrowserIntent.setData(Uri.parse("http:"));
479    }
480
481    /**
482     * The set of all protected actions [i.e. those actions for which a high priority
483     * intent filter is disallowed].
484     */
485    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
486    static {
487        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
488        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
489        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
490        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
491    }
492
493    // Compilation reasons.
494    public static final int REASON_FIRST_BOOT = 0;
495    public static final int REASON_BOOT = 1;
496    public static final int REASON_INSTALL = 2;
497    public static final int REASON_BACKGROUND_DEXOPT = 3;
498    public static final int REASON_AB_OTA = 4;
499    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
500    public static final int REASON_SHARED_APK = 6;
501    public static final int REASON_FORCED_DEXOPT = 7;
502    public static final int REASON_CORE_APP = 8;
503
504    public static final int REASON_LAST = REASON_CORE_APP;
505
506    /** Special library name that skips shared libraries check during compilation. */
507    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
508
509    final ServiceThread mHandlerThread;
510
511    final PackageHandler mHandler;
512
513    private final ProcessLoggingHandler mProcessLoggingHandler;
514
515    /**
516     * Messages for {@link #mHandler} that need to wait for system ready before
517     * being dispatched.
518     */
519    private ArrayList<Message> mPostSystemReadyMessages;
520
521    final int mSdkVersion = Build.VERSION.SDK_INT;
522
523    final Context mContext;
524    final boolean mFactoryTest;
525    final boolean mOnlyCore;
526    final DisplayMetrics mMetrics;
527    final int mDefParseFlags;
528    final String[] mSeparateProcesses;
529    final boolean mIsUpgrade;
530    final boolean mIsPreNUpgrade;
531
532    /** The location for ASEC container files on internal storage. */
533    final String mAsecInternalPath;
534
535    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
536    // LOCK HELD.  Can be called with mInstallLock held.
537    @GuardedBy("mInstallLock")
538    final Installer mInstaller;
539
540    /** Directory where installed third-party apps stored */
541    final File mAppInstallDir;
542    final File mEphemeralInstallDir;
543
544    /**
545     * Directory to which applications installed internally have their
546     * 32 bit native libraries copied.
547     */
548    private File mAppLib32InstallDir;
549
550    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
551    // apps.
552    final File mDrmAppPrivateInstallDir;
553
554    // ----------------------------------------------------------------
555
556    // Lock for state used when installing and doing other long running
557    // operations.  Methods that must be called with this lock held have
558    // the suffix "LI".
559    final Object mInstallLock = new Object();
560
561    // ----------------------------------------------------------------
562
563    // Keys are String (package name), values are Package.  This also serves
564    // as the lock for the global state.  Methods that must be called with
565    // this lock held have the prefix "LP".
566    @GuardedBy("mPackages")
567    final ArrayMap<String, PackageParser.Package> mPackages =
568            new ArrayMap<String, PackageParser.Package>();
569
570    final ArrayMap<String, Set<String>> mKnownCodebase =
571            new ArrayMap<String, Set<String>>();
572
573    // Tracks available target package names -> overlay package paths.
574    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
575        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
576
577    /**
578     * Tracks new system packages [received in an OTA] that we expect to
579     * find updated user-installed versions. Keys are package name, values
580     * are package location.
581     */
582    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
583    /**
584     * Tracks high priority intent filters for protected actions. During boot, certain
585     * filter actions are protected and should never be allowed to have a high priority
586     * intent filter for them. However, there is one, and only one exception -- the
587     * setup wizard. It must be able to define a high priority intent filter for these
588     * actions to ensure there are no escapes from the wizard. We need to delay processing
589     * of these during boot as we need to look at all of the system packages in order
590     * to know which component is the setup wizard.
591     */
592    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
593    /**
594     * Whether or not processing protected filters should be deferred.
595     */
596    private boolean mDeferProtectedFilters = true;
597
598    /**
599     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
600     */
601    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
602    /**
603     * Whether or not system app permissions should be promoted from install to runtime.
604     */
605    boolean mPromoteSystemApps;
606
607    @GuardedBy("mPackages")
608    final Settings mSettings;
609
610    /**
611     * Set of package names that are currently "frozen", which means active
612     * surgery is being done on the code/data for that package. The platform
613     * will refuse to launch frozen packages to avoid race conditions.
614     *
615     * @see PackageFreezer
616     */
617    @GuardedBy("mPackages")
618    final ArraySet<String> mFrozenPackages = new ArraySet<>();
619
620    final ProtectedPackages mProtectedPackages = new ProtectedPackages();
621
622    boolean mFirstBoot;
623
624    // System configuration read by SystemConfig.
625    final int[] mGlobalGids;
626    final SparseArray<ArraySet<String>> mSystemPermissions;
627    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
628
629    // If mac_permissions.xml was found for seinfo labeling.
630    boolean mFoundPolicyFile;
631
632    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
633
634    public static final class SharedLibraryEntry {
635        public final String path;
636        public final String apk;
637
638        SharedLibraryEntry(String _path, String _apk) {
639            path = _path;
640            apk = _apk;
641        }
642    }
643
644    // Currently known shared libraries.
645    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
646            new ArrayMap<String, SharedLibraryEntry>();
647
648    // All available activities, for your resolving pleasure.
649    final ActivityIntentResolver mActivities =
650            new ActivityIntentResolver();
651
652    // All available receivers, for your resolving pleasure.
653    final ActivityIntentResolver mReceivers =
654            new ActivityIntentResolver();
655
656    // All available services, for your resolving pleasure.
657    final ServiceIntentResolver mServices = new ServiceIntentResolver();
658
659    // All available providers, for your resolving pleasure.
660    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
661
662    // Mapping from provider base names (first directory in content URI codePath)
663    // to the provider information.
664    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
665            new ArrayMap<String, PackageParser.Provider>();
666
667    // Mapping from instrumentation class names to info about them.
668    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
669            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
670
671    // Mapping from permission names to info about them.
672    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
673            new ArrayMap<String, PackageParser.PermissionGroup>();
674
675    // Packages whose data we have transfered into another package, thus
676    // should no longer exist.
677    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
678
679    // Broadcast actions that are only available to the system.
680    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
681
682    /** List of packages waiting for verification. */
683    final SparseArray<PackageVerificationState> mPendingVerification
684            = new SparseArray<PackageVerificationState>();
685
686    /** Set of packages associated with each app op permission. */
687    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
688
689    final PackageInstallerService mInstallerService;
690
691    private final PackageDexOptimizer mPackageDexOptimizer;
692
693    private AtomicInteger mNextMoveId = new AtomicInteger();
694    private final MoveCallbacks mMoveCallbacks;
695
696    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
697
698    // Cache of users who need badging.
699    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
700
701    /** Token for keys in mPendingVerification. */
702    private int mPendingVerificationToken = 0;
703
704    volatile boolean mSystemReady;
705    volatile boolean mSafeMode;
706    volatile boolean mHasSystemUidErrors;
707
708    ApplicationInfo mAndroidApplication;
709    final ActivityInfo mResolveActivity = new ActivityInfo();
710    final ResolveInfo mResolveInfo = new ResolveInfo();
711    ComponentName mResolveComponentName;
712    PackageParser.Package mPlatformPackage;
713    ComponentName mCustomResolverComponentName;
714
715    boolean mResolverReplaced = false;
716
717    private final @Nullable ComponentName mIntentFilterVerifierComponent;
718    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
719
720    private int mIntentFilterVerificationToken = 0;
721
722    /** Component that knows whether or not an ephemeral application exists */
723    final ComponentName mEphemeralResolverComponent;
724    /** The service connection to the ephemeral resolver */
725    final EphemeralResolverConnection mEphemeralResolverConnection;
726
727    /** Component used to install ephemeral applications */
728    final ComponentName mEphemeralInstallerComponent;
729    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
730    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
731
732    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
733            = new SparseArray<IntentFilterVerificationState>();
734
735    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
736            new DefaultPermissionGrantPolicy(this);
737
738    // List of packages names to keep cached, even if they are uninstalled for all users
739    private List<String> mKeepUninstalledPackages;
740
741    private UserManagerInternal mUserManagerInternal;
742
743    private static class IFVerificationParams {
744        PackageParser.Package pkg;
745        boolean replacing;
746        int userId;
747        int verifierUid;
748
749        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
750                int _userId, int _verifierUid) {
751            pkg = _pkg;
752            replacing = _replacing;
753            userId = _userId;
754            replacing = _replacing;
755            verifierUid = _verifierUid;
756        }
757    }
758
759    private interface IntentFilterVerifier<T extends IntentFilter> {
760        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
761                                               T filter, String packageName);
762        void startVerifications(int userId);
763        void receiveVerificationResponse(int verificationId);
764    }
765
766    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
767        private Context mContext;
768        private ComponentName mIntentFilterVerifierComponent;
769        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
770
771        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
772            mContext = context;
773            mIntentFilterVerifierComponent = verifierComponent;
774        }
775
776        private String getDefaultScheme() {
777            return IntentFilter.SCHEME_HTTPS;
778        }
779
780        @Override
781        public void startVerifications(int userId) {
782            // Launch verifications requests
783            int count = mCurrentIntentFilterVerifications.size();
784            for (int n=0; n<count; n++) {
785                int verificationId = mCurrentIntentFilterVerifications.get(n);
786                final IntentFilterVerificationState ivs =
787                        mIntentFilterVerificationStates.get(verificationId);
788
789                String packageName = ivs.getPackageName();
790
791                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
792                final int filterCount = filters.size();
793                ArraySet<String> domainsSet = new ArraySet<>();
794                for (int m=0; m<filterCount; m++) {
795                    PackageParser.ActivityIntentInfo filter = filters.get(m);
796                    domainsSet.addAll(filter.getHostsList());
797                }
798                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
799                synchronized (mPackages) {
800                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
801                            packageName, domainsList) != null) {
802                        scheduleWriteSettingsLocked();
803                    }
804                }
805                sendVerificationRequest(userId, verificationId, ivs);
806            }
807            mCurrentIntentFilterVerifications.clear();
808        }
809
810        private void sendVerificationRequest(int userId, int verificationId,
811                IntentFilterVerificationState ivs) {
812
813            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
816                    verificationId);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
819                    getDefaultScheme());
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
822                    ivs.getHostsString());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
825                    ivs.getPackageName());
826            verificationIntent.setComponent(mIntentFilterVerifierComponent);
827            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
828
829            UserHandle user = new UserHandle(userId);
830            mContext.sendBroadcastAsUser(verificationIntent, user);
831            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
832                    "Sending IntentFilter verification broadcast");
833        }
834
835        public void receiveVerificationResponse(int verificationId) {
836            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
837
838            final boolean verified = ivs.isVerified();
839
840            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
841            final int count = filters.size();
842            if (DEBUG_DOMAIN_VERIFICATION) {
843                Slog.i(TAG, "Received verification response " + verificationId
844                        + " for " + count + " filters, verified=" + verified);
845            }
846            for (int n=0; n<count; n++) {
847                PackageParser.ActivityIntentInfo filter = filters.get(n);
848                filter.setVerified(verified);
849
850                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
851                        + " verified with result:" + verified + " and hosts:"
852                        + ivs.getHostsString());
853            }
854
855            mIntentFilterVerificationStates.remove(verificationId);
856
857            final String packageName = ivs.getPackageName();
858            IntentFilterVerificationInfo ivi = null;
859
860            synchronized (mPackages) {
861                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
862            }
863            if (ivi == null) {
864                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
865                        + verificationId + " packageName:" + packageName);
866                return;
867            }
868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
869                    "Updating IntentFilterVerificationInfo for package " + packageName
870                            +" verificationId:" + verificationId);
871
872            synchronized (mPackages) {
873                if (verified) {
874                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
875                } else {
876                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
877                }
878                scheduleWriteSettingsLocked();
879
880                final int userId = ivs.getUserId();
881                if (userId != UserHandle.USER_ALL) {
882                    final int userStatus =
883                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
884
885                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
886                    boolean needUpdate = false;
887
888                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
889                    // already been set by the User thru the Disambiguation dialog
890                    switch (userStatus) {
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                            } else {
895                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
896                            }
897                            needUpdate = true;
898                            break;
899
900                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
901                            if (verified) {
902                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
903                                needUpdate = true;
904                            }
905                            break;
906
907                        default:
908                            // Nothing to do
909                    }
910
911                    if (needUpdate) {
912                        mSettings.updateIntentFilterVerificationStatusLPw(
913                                packageName, updatedStatus, userId);
914                        scheduleWritePackageRestrictionsLocked(userId);
915                    }
916                }
917            }
918        }
919
920        @Override
921        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
922                    ActivityIntentInfo filter, String packageName) {
923            if (!hasValidDomains(filter)) {
924                return false;
925            }
926            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
927            if (ivs == null) {
928                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
929                        packageName);
930            }
931            if (DEBUG_DOMAIN_VERIFICATION) {
932                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
933            }
934            ivs.addFilter(filter);
935            return true;
936        }
937
938        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
939                int userId, int verificationId, String packageName) {
940            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
941                    verifierUid, userId, packageName);
942            ivs.setPendingState();
943            synchronized (mPackages) {
944                mIntentFilterVerificationStates.append(verificationId, ivs);
945                mCurrentIntentFilterVerifications.add(verificationId);
946            }
947            return ivs;
948        }
949    }
950
951    private static boolean hasValidDomains(ActivityIntentInfo filter) {
952        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
953                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
954                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
955    }
956
957    // Set of pending broadcasts for aggregating enable/disable of components.
958    static class PendingPackageBroadcasts {
959        // for each user id, a map of <package name -> components within that package>
960        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
961
962        public PendingPackageBroadcasts() {
963            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
964        }
965
966        public ArrayList<String> get(int userId, String packageName) {
967            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
968            return packages.get(packageName);
969        }
970
971        public void put(int userId, String packageName, ArrayList<String> components) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            packages.put(packageName, components);
974        }
975
976        public void remove(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
978            if (packages != null) {
979                packages.remove(packageName);
980            }
981        }
982
983        public void remove(int userId) {
984            mUidMap.remove(userId);
985        }
986
987        public int userIdCount() {
988            return mUidMap.size();
989        }
990
991        public int userIdAt(int n) {
992            return mUidMap.keyAt(n);
993        }
994
995        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
996            return mUidMap.get(userId);
997        }
998
999        public int size() {
1000            // total number of pending broadcast entries across all userIds
1001            int num = 0;
1002            for (int i = 0; i< mUidMap.size(); i++) {
1003                num += mUidMap.valueAt(i).size();
1004            }
1005            return num;
1006        }
1007
1008        public void clear() {
1009            mUidMap.clear();
1010        }
1011
1012        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1013            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1014            if (map == null) {
1015                map = new ArrayMap<String, ArrayList<String>>();
1016                mUidMap.put(userId, map);
1017            }
1018            return map;
1019        }
1020    }
1021    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1022
1023    // Service Connection to remote media container service to copy
1024    // package uri's from external media onto secure containers
1025    // or internal storage.
1026    private IMediaContainerService mContainerService = null;
1027
1028    static final int SEND_PENDING_BROADCAST = 1;
1029    static final int MCS_BOUND = 3;
1030    static final int END_COPY = 4;
1031    static final int INIT_COPY = 5;
1032    static final int MCS_UNBIND = 6;
1033    static final int START_CLEANING_PACKAGE = 7;
1034    static final int FIND_INSTALL_LOC = 8;
1035    static final int POST_INSTALL = 9;
1036    static final int MCS_RECONNECT = 10;
1037    static final int MCS_GIVE_UP = 11;
1038    static final int UPDATED_MEDIA_STATUS = 12;
1039    static final int WRITE_SETTINGS = 13;
1040    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1041    static final int PACKAGE_VERIFIED = 15;
1042    static final int CHECK_PENDING_VERIFICATION = 16;
1043    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1044    static final int INTENT_FILTER_VERIFIED = 18;
1045    static final int WRITE_PACKAGE_LIST = 19;
1046
1047    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1048
1049    // Delay time in millisecs
1050    static final int BROADCAST_DELAY = 10 * 1000;
1051
1052    static UserManagerService sUserManager;
1053
1054    // Stores a list of users whose package restrictions file needs to be updated
1055    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1056
1057    final private DefaultContainerConnection mDefContainerConn =
1058            new DefaultContainerConnection();
1059    class DefaultContainerConnection implements ServiceConnection {
1060        public void onServiceConnected(ComponentName name, IBinder service) {
1061            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1062            IMediaContainerService imcs =
1063                IMediaContainerService.Stub.asInterface(service);
1064            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1065        }
1066
1067        public void onServiceDisconnected(ComponentName name) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1069        }
1070    }
1071
1072    // Recordkeeping of restore-after-install operations that are currently in flight
1073    // between the Package Manager and the Backup Manager
1074    static class PostInstallData {
1075        public InstallArgs args;
1076        public PackageInstalledInfo res;
1077
1078        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1079            args = _a;
1080            res = _r;
1081        }
1082    }
1083
1084    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1085    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1086
1087    // XML tags for backup/restore of various bits of state
1088    private static final String TAG_PREFERRED_BACKUP = "pa";
1089    private static final String TAG_DEFAULT_APPS = "da";
1090    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1091
1092    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1093    private static final String TAG_ALL_GRANTS = "rt-grants";
1094    private static final String TAG_GRANT = "grant";
1095    private static final String ATTR_PACKAGE_NAME = "pkg";
1096
1097    private static final String TAG_PERMISSION = "perm";
1098    private static final String ATTR_PERMISSION_NAME = "name";
1099    private static final String ATTR_IS_GRANTED = "g";
1100    private static final String ATTR_USER_SET = "set";
1101    private static final String ATTR_USER_FIXED = "fixed";
1102    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1103
1104    // System/policy permission grants are not backed up
1105    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1106            FLAG_PERMISSION_POLICY_FIXED
1107            | FLAG_PERMISSION_SYSTEM_FIXED
1108            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1109
1110    // And we back up these user-adjusted states
1111    private static final int USER_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_USER_SET
1113            | FLAG_PERMISSION_USER_FIXED
1114            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1115
1116    final @Nullable String mRequiredVerifierPackage;
1117    final @NonNull String mRequiredInstallerPackage;
1118    final @Nullable String mSetupWizardPackage;
1119    final @NonNull String mServicesSystemSharedLibraryPackageName;
1120    final @NonNull String mSharedSystemSharedLibraryPackageName;
1121
1122    final boolean mPermissionReviewRequired;
1123
1124    private final PackageUsage mPackageUsage = new PackageUsage();
1125    private final CompilerStats mCompilerStats = new CompilerStats();
1126
1127    class PackageHandler extends Handler {
1128        private boolean mBound = false;
1129        final ArrayList<HandlerParams> mPendingInstalls =
1130            new ArrayList<HandlerParams>();
1131
1132        private boolean connectToService() {
1133            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1134                    " DefaultContainerService");
1135            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1138                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1139                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                mBound = true;
1141                return true;
1142            }
1143            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1144            return false;
1145        }
1146
1147        private void disconnectService() {
1148            mContainerService = null;
1149            mBound = false;
1150            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1151            mContext.unbindService(mDefContainerConn);
1152            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1153        }
1154
1155        PackageHandler(Looper looper) {
1156            super(looper);
1157        }
1158
1159        public void handleMessage(Message msg) {
1160            try {
1161                doHandleMessage(msg);
1162            } finally {
1163                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1164            }
1165        }
1166
1167        void doHandleMessage(Message msg) {
1168            switch (msg.what) {
1169                case INIT_COPY: {
1170                    HandlerParams params = (HandlerParams) msg.obj;
1171                    int idx = mPendingInstalls.size();
1172                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1173                    // If a bind was already initiated we dont really
1174                    // need to do anything. The pending install
1175                    // will be processed later on.
1176                    if (!mBound) {
1177                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1178                                System.identityHashCode(mHandler));
1179                        // If this is the only one pending we might
1180                        // have to bind to the service again.
1181                        if (!connectToService()) {
1182                            Slog.e(TAG, "Failed to bind to media container service");
1183                            params.serviceError();
1184                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1185                                    System.identityHashCode(mHandler));
1186                            if (params.traceMethod != null) {
1187                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1188                                        params.traceCookie);
1189                            }
1190                            return;
1191                        } else {
1192                            // Once we bind to the service, the first
1193                            // pending request will be processed.
1194                            mPendingInstalls.add(idx, params);
1195                        }
1196                    } else {
1197                        mPendingInstalls.add(idx, params);
1198                        // Already bound to the service. Just make
1199                        // sure we trigger off processing the first request.
1200                        if (idx == 0) {
1201                            mHandler.sendEmptyMessage(MCS_BOUND);
1202                        }
1203                    }
1204                    break;
1205                }
1206                case MCS_BOUND: {
1207                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1208                    if (msg.obj != null) {
1209                        mContainerService = (IMediaContainerService) msg.obj;
1210                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                System.identityHashCode(mHandler));
1212                    }
1213                    if (mContainerService == null) {
1214                        if (!mBound) {
1215                            // Something seriously wrong since we are not bound and we are not
1216                            // waiting for connection. Bail out.
1217                            Slog.e(TAG, "Cannot bind to media container service");
1218                            for (HandlerParams params : mPendingInstalls) {
1219                                // Indicate service bind error
1220                                params.serviceError();
1221                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1222                                        System.identityHashCode(params));
1223                                if (params.traceMethod != null) {
1224                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1225                                            params.traceMethod, params.traceCookie);
1226                                }
1227                                return;
1228                            }
1229                            mPendingInstalls.clear();
1230                        } else {
1231                            Slog.w(TAG, "Waiting to connect to media container service");
1232                        }
1233                    } else if (mPendingInstalls.size() > 0) {
1234                        HandlerParams params = mPendingInstalls.get(0);
1235                        if (params != null) {
1236                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1237                                    System.identityHashCode(params));
1238                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1239                            if (params.startCopy()) {
1240                                // We are done...  look for more work or to
1241                                // go idle.
1242                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1243                                        "Checking for more work or unbind...");
1244                                // Delete pending install
1245                                if (mPendingInstalls.size() > 0) {
1246                                    mPendingInstalls.remove(0);
1247                                }
1248                                if (mPendingInstalls.size() == 0) {
1249                                    if (mBound) {
1250                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1251                                                "Posting delayed MCS_UNBIND");
1252                                        removeMessages(MCS_UNBIND);
1253                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1254                                        // Unbind after a little delay, to avoid
1255                                        // continual thrashing.
1256                                        sendMessageDelayed(ubmsg, 10000);
1257                                    }
1258                                } else {
1259                                    // There are more pending requests in queue.
1260                                    // Just post MCS_BOUND message to trigger processing
1261                                    // of next pending install.
1262                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1263                                            "Posting MCS_BOUND for next work");
1264                                    mHandler.sendEmptyMessage(MCS_BOUND);
1265                                }
1266                            }
1267                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1268                        }
1269                    } else {
1270                        // Should never happen ideally.
1271                        Slog.w(TAG, "Empty queue");
1272                    }
1273                    break;
1274                }
1275                case MCS_RECONNECT: {
1276                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1277                    if (mPendingInstalls.size() > 0) {
1278                        if (mBound) {
1279                            disconnectService();
1280                        }
1281                        if (!connectToService()) {
1282                            Slog.e(TAG, "Failed to bind to media container service");
1283                            for (HandlerParams params : mPendingInstalls) {
1284                                // Indicate service bind error
1285                                params.serviceError();
1286                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1287                                        System.identityHashCode(params));
1288                            }
1289                            mPendingInstalls.clear();
1290                        }
1291                    }
1292                    break;
1293                }
1294                case MCS_UNBIND: {
1295                    // If there is no actual work left, then time to unbind.
1296                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1297
1298                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1299                        if (mBound) {
1300                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1301
1302                            disconnectService();
1303                        }
1304                    } else if (mPendingInstalls.size() > 0) {
1305                        // There are more pending requests in queue.
1306                        // Just post MCS_BOUND message to trigger processing
1307                        // of next pending install.
1308                        mHandler.sendEmptyMessage(MCS_BOUND);
1309                    }
1310
1311                    break;
1312                }
1313                case MCS_GIVE_UP: {
1314                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1315                    HandlerParams params = mPendingInstalls.remove(0);
1316                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                            System.identityHashCode(params));
1318                    break;
1319                }
1320                case SEND_PENDING_BROADCAST: {
1321                    String packages[];
1322                    ArrayList<String> components[];
1323                    int size = 0;
1324                    int uids[];
1325                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1326                    synchronized (mPackages) {
1327                        if (mPendingBroadcasts == null) {
1328                            return;
1329                        }
1330                        size = mPendingBroadcasts.size();
1331                        if (size <= 0) {
1332                            // Nothing to be done. Just return
1333                            return;
1334                        }
1335                        packages = new String[size];
1336                        components = new ArrayList[size];
1337                        uids = new int[size];
1338                        int i = 0;  // filling out the above arrays
1339
1340                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1341                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1342                            Iterator<Map.Entry<String, ArrayList<String>>> it
1343                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1344                                            .entrySet().iterator();
1345                            while (it.hasNext() && i < size) {
1346                                Map.Entry<String, ArrayList<String>> ent = it.next();
1347                                packages[i] = ent.getKey();
1348                                components[i] = ent.getValue();
1349                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1350                                uids[i] = (ps != null)
1351                                        ? UserHandle.getUid(packageUserId, ps.appId)
1352                                        : -1;
1353                                i++;
1354                            }
1355                        }
1356                        size = i;
1357                        mPendingBroadcasts.clear();
1358                    }
1359                    // Send broadcasts
1360                    for (int i = 0; i < size; i++) {
1361                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1362                    }
1363                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1364                    break;
1365                }
1366                case START_CLEANING_PACKAGE: {
1367                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1368                    final String packageName = (String)msg.obj;
1369                    final int userId = msg.arg1;
1370                    final boolean andCode = msg.arg2 != 0;
1371                    synchronized (mPackages) {
1372                        if (userId == UserHandle.USER_ALL) {
1373                            int[] users = sUserManager.getUserIds();
1374                            for (int user : users) {
1375                                mSettings.addPackageToCleanLPw(
1376                                        new PackageCleanItem(user, packageName, andCode));
1377                            }
1378                        } else {
1379                            mSettings.addPackageToCleanLPw(
1380                                    new PackageCleanItem(userId, packageName, andCode));
1381                        }
1382                    }
1383                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1384                    startCleaningPackages();
1385                } break;
1386                case POST_INSTALL: {
1387                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1388
1389                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1390                    final boolean didRestore = (msg.arg2 != 0);
1391                    mRunningInstalls.delete(msg.arg1);
1392
1393                    if (data != null) {
1394                        InstallArgs args = data.args;
1395                        PackageInstalledInfo parentRes = data.res;
1396
1397                        final boolean grantPermissions = (args.installFlags
1398                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1399                        final boolean killApp = (args.installFlags
1400                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1401                        final String[] grantedPermissions = args.installGrantPermissions;
1402
1403                        // Handle the parent package
1404                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1405                                grantedPermissions, didRestore, args.installerPackageName,
1406                                args.observer);
1407
1408                        // Handle the child packages
1409                        final int childCount = (parentRes.addedChildPackages != null)
1410                                ? parentRes.addedChildPackages.size() : 0;
1411                        for (int i = 0; i < childCount; i++) {
1412                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1413                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1414                                    grantedPermissions, false, args.installerPackageName,
1415                                    args.observer);
1416                        }
1417
1418                        // Log tracing if needed
1419                        if (args.traceMethod != null) {
1420                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1421                                    args.traceCookie);
1422                        }
1423                    } else {
1424                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1425                    }
1426
1427                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1428                } break;
1429                case UPDATED_MEDIA_STATUS: {
1430                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1431                    boolean reportStatus = msg.arg1 == 1;
1432                    boolean doGc = msg.arg2 == 1;
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1434                    if (doGc) {
1435                        // Force a gc to clear up stale containers.
1436                        Runtime.getRuntime().gc();
1437                    }
1438                    if (msg.obj != null) {
1439                        @SuppressWarnings("unchecked")
1440                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1441                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1442                        // Unload containers
1443                        unloadAllContainers(args);
1444                    }
1445                    if (reportStatus) {
1446                        try {
1447                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1448                            PackageHelper.getMountService().finishMediaUpdate();
1449                        } catch (RemoteException e) {
1450                            Log.e(TAG, "MountService not running?");
1451                        }
1452                    }
1453                } break;
1454                case WRITE_SETTINGS: {
1455                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1456                    synchronized (mPackages) {
1457                        removeMessages(WRITE_SETTINGS);
1458                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1459                        mSettings.writeLPr();
1460                        mDirtyUsers.clear();
1461                    }
1462                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1463                } break;
1464                case WRITE_PACKAGE_RESTRICTIONS: {
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1466                    synchronized (mPackages) {
1467                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1468                        for (int userId : mDirtyUsers) {
1469                            mSettings.writePackageRestrictionsLPr(userId);
1470                        }
1471                        mDirtyUsers.clear();
1472                    }
1473                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1474                } break;
1475                case WRITE_PACKAGE_LIST: {
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                    synchronized (mPackages) {
1478                        removeMessages(WRITE_PACKAGE_LIST);
1479                        mSettings.writePackageListLPr(msg.arg1);
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                } break;
1483                case CHECK_PENDING_VERIFICATION: {
1484                    final int verificationId = msg.arg1;
1485                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1486
1487                    if ((state != null) && !state.timeoutExtended()) {
1488                        final InstallArgs args = state.getInstallArgs();
1489                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1490
1491                        Slog.i(TAG, "Verification timed out for " + originUri);
1492                        mPendingVerification.remove(verificationId);
1493
1494                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1495
1496                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1497                            Slog.i(TAG, "Continuing with installation of " + originUri);
1498                            state.setVerifierResponse(Binder.getCallingUid(),
1499                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1500                            broadcastPackageVerified(verificationId, originUri,
1501                                    PackageManager.VERIFICATION_ALLOW,
1502                                    state.getInstallArgs().getUser());
1503                            try {
1504                                ret = args.copyApk(mContainerService, true);
1505                            } catch (RemoteException e) {
1506                                Slog.e(TAG, "Could not contact the ContainerService");
1507                            }
1508                        } else {
1509                            broadcastPackageVerified(verificationId, originUri,
1510                                    PackageManager.VERIFICATION_REJECT,
1511                                    state.getInstallArgs().getUser());
1512                        }
1513
1514                        Trace.asyncTraceEnd(
1515                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1516
1517                        processPendingInstall(args, ret);
1518                        mHandler.sendEmptyMessage(MCS_UNBIND);
1519                    }
1520                    break;
1521                }
1522                case PACKAGE_VERIFIED: {
1523                    final int verificationId = msg.arg1;
1524
1525                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1526                    if (state == null) {
1527                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1528                        break;
1529                    }
1530
1531                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1532
1533                    state.setVerifierResponse(response.callerUid, response.code);
1534
1535                    if (state.isVerificationComplete()) {
1536                        mPendingVerification.remove(verificationId);
1537
1538                        final InstallArgs args = state.getInstallArgs();
1539                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1540
1541                        int ret;
1542                        if (state.isInstallAllowed()) {
1543                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1544                            broadcastPackageVerified(verificationId, originUri,
1545                                    response.code, state.getInstallArgs().getUser());
1546                            try {
1547                                ret = args.copyApk(mContainerService, true);
1548                            } catch (RemoteException e) {
1549                                Slog.e(TAG, "Could not contact the ContainerService");
1550                            }
1551                        } else {
1552                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1553                        }
1554
1555                        Trace.asyncTraceEnd(
1556                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1557
1558                        processPendingInstall(args, ret);
1559                        mHandler.sendEmptyMessage(MCS_UNBIND);
1560                    }
1561
1562                    break;
1563                }
1564                case START_INTENT_FILTER_VERIFICATIONS: {
1565                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1566                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1567                            params.replacing, params.pkg);
1568                    break;
1569                }
1570                case INTENT_FILTER_VERIFIED: {
1571                    final int verificationId = msg.arg1;
1572
1573                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1574                            verificationId);
1575                    if (state == null) {
1576                        Slog.w(TAG, "Invalid IntentFilter verification token "
1577                                + verificationId + " received");
1578                        break;
1579                    }
1580
1581                    final int userId = state.getUserId();
1582
1583                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1584                            "Processing IntentFilter verification with token:"
1585                            + verificationId + " and userId:" + userId);
1586
1587                    final IntentFilterVerificationResponse response =
1588                            (IntentFilterVerificationResponse) msg.obj;
1589
1590                    state.setVerifierResponse(response.callerUid, response.code);
1591
1592                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1593                            "IntentFilter verification with token:" + verificationId
1594                            + " and userId:" + userId
1595                            + " is settings verifier response with response code:"
1596                            + response.code);
1597
1598                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1599                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1600                                + response.getFailedDomainsString());
1601                    }
1602
1603                    if (state.isVerificationComplete()) {
1604                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1605                    } else {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1607                                "IntentFilter verification with token:" + verificationId
1608                                + " was not said to be complete");
1609                    }
1610
1611                    break;
1612                }
1613            }
1614        }
1615    }
1616
1617    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1618            boolean killApp, String[] grantedPermissions,
1619            boolean launchedForRestore, String installerPackage,
1620            IPackageInstallObserver2 installObserver) {
1621        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1622            // Send the removed broadcasts
1623            if (res.removedInfo != null) {
1624                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1625            }
1626
1627            // Now that we successfully installed the package, grant runtime
1628            // permissions if requested before broadcasting the install.
1629            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1630                    >= Build.VERSION_CODES.M) {
1631                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1632            }
1633
1634            final boolean update = res.removedInfo != null
1635                    && res.removedInfo.removedPackage != null;
1636
1637            // If this is the first time we have child packages for a disabled privileged
1638            // app that had no children, we grant requested runtime permissions to the new
1639            // children if the parent on the system image had them already granted.
1640            if (res.pkg.parentPackage != null) {
1641                synchronized (mPackages) {
1642                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1643                }
1644            }
1645
1646            synchronized (mPackages) {
1647                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1648            }
1649
1650            final String packageName = res.pkg.applicationInfo.packageName;
1651            Bundle extras = new Bundle(1);
1652            extras.putInt(Intent.EXTRA_UID, res.uid);
1653
1654            // Determine the set of users who are adding this package for
1655            // the first time vs. those who are seeing an update.
1656            int[] firstUsers = EMPTY_INT_ARRAY;
1657            int[] updateUsers = EMPTY_INT_ARRAY;
1658            if (res.origUsers == null || res.origUsers.length == 0) {
1659                firstUsers = res.newUsers;
1660            } else {
1661                for (int newUser : res.newUsers) {
1662                    boolean isNew = true;
1663                    for (int origUser : res.origUsers) {
1664                        if (origUser == newUser) {
1665                            isNew = false;
1666                            break;
1667                        }
1668                    }
1669                    if (isNew) {
1670                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1671                    } else {
1672                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1673                    }
1674                }
1675            }
1676
1677            // Send installed broadcasts if the install/update is not ephemeral
1678            if (!isEphemeral(res.pkg)) {
1679                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1680
1681                // Send added for users that see the package for the first time
1682                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1683                        extras, 0 /*flags*/, null /*targetPackage*/,
1684                        null /*finishedReceiver*/, firstUsers);
1685
1686                // Send added for users that don't see the package for the first time
1687                if (update) {
1688                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1689                }
1690                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1691                        extras, 0 /*flags*/, null /*targetPackage*/,
1692                        null /*finishedReceiver*/, updateUsers);
1693
1694                // Send replaced for users that don't see the package for the first time
1695                if (update) {
1696                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1697                            packageName, extras, 0 /*flags*/,
1698                            null /*targetPackage*/, null /*finishedReceiver*/,
1699                            updateUsers);
1700                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1701                            null /*package*/, null /*extras*/, 0 /*flags*/,
1702                            packageName /*targetPackage*/,
1703                            null /*finishedReceiver*/, updateUsers);
1704                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1705                    // First-install and we did a restore, so we're responsible for the
1706                    // first-launch broadcast.
1707                    if (DEBUG_BACKUP) {
1708                        Slog.i(TAG, "Post-restore of " + packageName
1709                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1710                    }
1711                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1712                }
1713
1714                // Send broadcast package appeared if forward locked/external for all users
1715                // treat asec-hosted packages like removable media on upgrade
1716                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1717                    if (DEBUG_INSTALL) {
1718                        Slog.i(TAG, "upgrading pkg " + res.pkg
1719                                + " is ASEC-hosted -> AVAILABLE");
1720                    }
1721                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1722                    ArrayList<String> pkgList = new ArrayList<>(1);
1723                    pkgList.add(packageName);
1724                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1725                }
1726            }
1727
1728            // Work that needs to happen on first install within each user
1729            if (firstUsers != null && firstUsers.length > 0) {
1730                synchronized (mPackages) {
1731                    for (int userId : firstUsers) {
1732                        // If this app is a browser and it's newly-installed for some
1733                        // users, clear any default-browser state in those users. The
1734                        // app's nature doesn't depend on the user, so we can just check
1735                        // its browser nature in any user and generalize.
1736                        if (packageIsBrowser(packageName, userId)) {
1737                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1738                        }
1739
1740                        // We may also need to apply pending (restored) runtime
1741                        // permission grants within these users.
1742                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1743                    }
1744                }
1745            }
1746
1747            // Log current value of "unknown sources" setting
1748            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1749                    getUnknownSourcesSettings());
1750
1751            // Force a gc to clear up things
1752            Runtime.getRuntime().gc();
1753
1754            // Remove the replaced package's older resources safely now
1755            // We delete after a gc for applications  on sdcard.
1756            if (res.removedInfo != null && res.removedInfo.args != null) {
1757                synchronized (mInstallLock) {
1758                    res.removedInfo.args.doPostDeleteLI(true);
1759                }
1760            }
1761        }
1762
1763        // If someone is watching installs - notify them
1764        if (installObserver != null) {
1765            try {
1766                Bundle extras = extrasForInstallResult(res);
1767                installObserver.onPackageInstalled(res.name, res.returnCode,
1768                        res.returnMsg, extras);
1769            } catch (RemoteException e) {
1770                Slog.i(TAG, "Observer no longer exists.");
1771            }
1772        }
1773    }
1774
1775    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1776            PackageParser.Package pkg) {
1777        if (pkg.parentPackage == null) {
1778            return;
1779        }
1780        if (pkg.requestedPermissions == null) {
1781            return;
1782        }
1783        final PackageSetting disabledSysParentPs = mSettings
1784                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1785        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1786                || !disabledSysParentPs.isPrivileged()
1787                || (disabledSysParentPs.childPackageNames != null
1788                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1789            return;
1790        }
1791        final int[] allUserIds = sUserManager.getUserIds();
1792        final int permCount = pkg.requestedPermissions.size();
1793        for (int i = 0; i < permCount; i++) {
1794            String permission = pkg.requestedPermissions.get(i);
1795            BasePermission bp = mSettings.mPermissions.get(permission);
1796            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1797                continue;
1798            }
1799            for (int userId : allUserIds) {
1800                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1801                        permission, userId)) {
1802                    grantRuntimePermission(pkg.packageName, permission, userId);
1803                }
1804            }
1805        }
1806    }
1807
1808    private StorageEventListener mStorageListener = new StorageEventListener() {
1809        @Override
1810        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1811            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1812                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1813                    final String volumeUuid = vol.getFsUuid();
1814
1815                    // Clean up any users or apps that were removed or recreated
1816                    // while this volume was missing
1817                    reconcileUsers(volumeUuid);
1818                    reconcileApps(volumeUuid);
1819
1820                    // Clean up any install sessions that expired or were
1821                    // cancelled while this volume was missing
1822                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1823
1824                    loadPrivatePackages(vol);
1825
1826                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1827                    unloadPrivatePackages(vol);
1828                }
1829            }
1830
1831            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1832                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1833                    updateExternalMediaStatus(true, false);
1834                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1835                    updateExternalMediaStatus(false, false);
1836                }
1837            }
1838        }
1839
1840        @Override
1841        public void onVolumeForgotten(String fsUuid) {
1842            if (TextUtils.isEmpty(fsUuid)) {
1843                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1844                return;
1845            }
1846
1847            // Remove any apps installed on the forgotten volume
1848            synchronized (mPackages) {
1849                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1850                for (PackageSetting ps : packages) {
1851                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1852                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1853                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1854                }
1855
1856                mSettings.onVolumeForgotten(fsUuid);
1857                mSettings.writeLPr();
1858            }
1859        }
1860    };
1861
1862    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1863            String[] grantedPermissions) {
1864        for (int userId : userIds) {
1865            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1866        }
1867
1868        // We could have touched GID membership, so flush out packages.list
1869        synchronized (mPackages) {
1870            mSettings.writePackageListLPr();
1871        }
1872    }
1873
1874    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1875            String[] grantedPermissions) {
1876        SettingBase sb = (SettingBase) pkg.mExtras;
1877        if (sb == null) {
1878            return;
1879        }
1880
1881        PermissionsState permissionsState = sb.getPermissionsState();
1882
1883        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1884                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1885
1886        for (String permission : pkg.requestedPermissions) {
1887            final BasePermission bp;
1888            synchronized (mPackages) {
1889                bp = mSettings.mPermissions.get(permission);
1890            }
1891            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1892                    && (grantedPermissions == null
1893                           || ArrayUtils.contains(grantedPermissions, permission))) {
1894                final int flags = permissionsState.getPermissionFlags(permission, userId);
1895                // Installer cannot change immutable permissions.
1896                if ((flags & immutableFlags) == 0) {
1897                    grantRuntimePermission(pkg.packageName, permission, userId);
1898                }
1899            }
1900        }
1901    }
1902
1903    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1904        Bundle extras = null;
1905        switch (res.returnCode) {
1906            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1907                extras = new Bundle();
1908                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1909                        res.origPermission);
1910                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1911                        res.origPackage);
1912                break;
1913            }
1914            case PackageManager.INSTALL_SUCCEEDED: {
1915                extras = new Bundle();
1916                extras.putBoolean(Intent.EXTRA_REPLACING,
1917                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1918                break;
1919            }
1920        }
1921        return extras;
1922    }
1923
1924    void scheduleWriteSettingsLocked() {
1925        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1926            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1927        }
1928    }
1929
1930    void scheduleWritePackageListLocked(int userId) {
1931        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1932            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1933            msg.arg1 = userId;
1934            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1935        }
1936    }
1937
1938    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1939        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1940        scheduleWritePackageRestrictionsLocked(userId);
1941    }
1942
1943    void scheduleWritePackageRestrictionsLocked(int userId) {
1944        final int[] userIds = (userId == UserHandle.USER_ALL)
1945                ? sUserManager.getUserIds() : new int[]{userId};
1946        for (int nextUserId : userIds) {
1947            if (!sUserManager.exists(nextUserId)) return;
1948            mDirtyUsers.add(nextUserId);
1949            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1950                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1951            }
1952        }
1953    }
1954
1955    public static PackageManagerService main(Context context, Installer installer,
1956            boolean factoryTest, boolean onlyCore) {
1957        // Self-check for initial settings.
1958        PackageManagerServiceCompilerMapping.checkProperties();
1959
1960        PackageManagerService m = new PackageManagerService(context, installer,
1961                factoryTest, onlyCore);
1962        m.enableSystemUserPackages();
1963        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
1964        // disabled after already being started.
1965        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
1966                UserHandle.USER_SYSTEM);
1967        ServiceManager.addService("package", m);
1968        return m;
1969    }
1970
1971    private void enableSystemUserPackages() {
1972        if (!UserManager.isSplitSystemUser()) {
1973            return;
1974        }
1975        // For system user, enable apps based on the following conditions:
1976        // - app is whitelisted or belong to one of these groups:
1977        //   -- system app which has no launcher icons
1978        //   -- system app which has INTERACT_ACROSS_USERS permission
1979        //   -- system IME app
1980        // - app is not in the blacklist
1981        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1982        Set<String> enableApps = new ArraySet<>();
1983        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1984                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1985                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1986        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1987        enableApps.addAll(wlApps);
1988        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1989                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1990        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1991        enableApps.removeAll(blApps);
1992        Log.i(TAG, "Applications installed for system user: " + enableApps);
1993        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1994                UserHandle.SYSTEM);
1995        final int allAppsSize = allAps.size();
1996        synchronized (mPackages) {
1997            for (int i = 0; i < allAppsSize; i++) {
1998                String pName = allAps.get(i);
1999                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2000                // Should not happen, but we shouldn't be failing if it does
2001                if (pkgSetting == null) {
2002                    continue;
2003                }
2004                boolean install = enableApps.contains(pName);
2005                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2006                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2007                            + " for system user");
2008                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2009                }
2010            }
2011        }
2012    }
2013
2014    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2015        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2016                Context.DISPLAY_SERVICE);
2017        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2018    }
2019
2020    /**
2021     * Requests that files preopted on a secondary system partition be copied to the data partition
2022     * if possible.  Note that the actual copying of the files is accomplished by init for security
2023     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2024     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2025     */
2026    private static void requestCopyPreoptedFiles() {
2027        final int WAIT_TIME_MS = 100;
2028        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2029        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2030            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2031            // We will wait for up to 100 seconds.
2032            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2033            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2034                try {
2035                    Thread.sleep(WAIT_TIME_MS);
2036                } catch (InterruptedException e) {
2037                    // Do nothing
2038                }
2039                if (SystemClock.uptimeMillis() > timeEnd) {
2040                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2041                    Slog.wtf(TAG, "cppreopt did not finish!");
2042                    break;
2043                }
2044            }
2045        }
2046    }
2047
2048    public PackageManagerService(Context context, Installer installer,
2049            boolean factoryTest, boolean onlyCore) {
2050        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2051                SystemClock.uptimeMillis());
2052
2053        if (mSdkVersion <= 0) {
2054            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2055        }
2056
2057        mContext = context;
2058
2059        mPermissionReviewRequired = context.getResources().getBoolean(
2060                R.bool.config_permissionReviewRequired);
2061
2062        mFactoryTest = factoryTest;
2063        mOnlyCore = onlyCore;
2064        mMetrics = new DisplayMetrics();
2065        mSettings = new Settings(mPackages);
2066        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2075                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2076        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2077                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078
2079        String separateProcesses = SystemProperties.get("debug.separate_processes");
2080        if (separateProcesses != null && separateProcesses.length() > 0) {
2081            if ("*".equals(separateProcesses)) {
2082                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2083                mSeparateProcesses = null;
2084                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2085            } else {
2086                mDefParseFlags = 0;
2087                mSeparateProcesses = separateProcesses.split(",");
2088                Slog.w(TAG, "Running with debug.separate_processes: "
2089                        + separateProcesses);
2090            }
2091        } else {
2092            mDefParseFlags = 0;
2093            mSeparateProcesses = null;
2094        }
2095
2096        mInstaller = installer;
2097        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2098                "*dexopt*");
2099        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2100
2101        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2102                FgThread.get().getLooper());
2103
2104        getDefaultDisplayMetrics(context, mMetrics);
2105
2106        SystemConfig systemConfig = SystemConfig.getInstance();
2107        mGlobalGids = systemConfig.getGlobalGids();
2108        mSystemPermissions = systemConfig.getSystemPermissions();
2109        mAvailableFeatures = systemConfig.getAvailableFeatures();
2110
2111        synchronized (mInstallLock) {
2112        // writer
2113        synchronized (mPackages) {
2114            mHandlerThread = new ServiceThread(TAG,
2115                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2116            mHandlerThread.start();
2117            mHandler = new PackageHandler(mHandlerThread.getLooper());
2118            mProcessLoggingHandler = new ProcessLoggingHandler();
2119            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2120
2121            File dataDir = Environment.getDataDirectory();
2122            mAppInstallDir = new File(dataDir, "app");
2123            mAppLib32InstallDir = new File(dataDir, "app-lib");
2124            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2125            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2126            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2127
2128            sUserManager = new UserManagerService(context, this, mPackages);
2129
2130            // Propagate permission configuration in to package manager.
2131            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2132                    = systemConfig.getPermissions();
2133            for (int i=0; i<permConfig.size(); i++) {
2134                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2135                BasePermission bp = mSettings.mPermissions.get(perm.name);
2136                if (bp == null) {
2137                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2138                    mSettings.mPermissions.put(perm.name, bp);
2139                }
2140                if (perm.gids != null) {
2141                    bp.setGids(perm.gids, perm.perUser);
2142                }
2143            }
2144
2145            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2146            for (int i=0; i<libConfig.size(); i++) {
2147                mSharedLibraries.put(libConfig.keyAt(i),
2148                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2149            }
2150
2151            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2152
2153            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2154
2155            if (mFirstBoot) {
2156                requestCopyPreoptedFiles();
2157            }
2158
2159            String customResolverActivity = Resources.getSystem().getString(
2160                    R.string.config_customResolverActivity);
2161            if (TextUtils.isEmpty(customResolverActivity)) {
2162                customResolverActivity = null;
2163            } else {
2164                mCustomResolverComponentName = ComponentName.unflattenFromString(
2165                        customResolverActivity);
2166            }
2167
2168            long startTime = SystemClock.uptimeMillis();
2169
2170            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2171                    startTime);
2172
2173            // Set flag to monitor and not change apk file paths when
2174            // scanning install directories.
2175            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2176
2177            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2178            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2179
2180            if (bootClassPath == null) {
2181                Slog.w(TAG, "No BOOTCLASSPATH found!");
2182            }
2183
2184            if (systemServerClassPath == null) {
2185                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2186            }
2187
2188            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2189            final String[] dexCodeInstructionSets =
2190                    getDexCodeInstructionSets(
2191                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2192
2193            /**
2194             * Ensure all external libraries have had dexopt run on them.
2195             */
2196            if (mSharedLibraries.size() > 0) {
2197                // NOTE: For now, we're compiling these system "shared libraries"
2198                // (and framework jars) into all available architectures. It's possible
2199                // to compile them only when we come across an app that uses them (there's
2200                // already logic for that in scanPackageLI) but that adds some complexity.
2201                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2202                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2203                        final String lib = libEntry.path;
2204                        if (lib == null) {
2205                            continue;
2206                        }
2207
2208                        try {
2209                            // Shared libraries do not have profiles so we perform a full
2210                            // AOT compilation (if needed).
2211                            int dexoptNeeded = DexFile.getDexOptNeeded(
2212                                    lib, dexCodeInstructionSet,
2213                                    getCompilerFilterForReason(REASON_SHARED_APK),
2214                                    false /* newProfile */);
2215                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2216                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2217                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2218                                        getCompilerFilterForReason(REASON_SHARED_APK),
2219                                        StorageManager.UUID_PRIVATE_INTERNAL,
2220                                        SKIP_SHARED_LIBRARY_CHECK);
2221                            }
2222                        } catch (FileNotFoundException e) {
2223                            Slog.w(TAG, "Library not found: " + lib);
2224                        } catch (IOException | InstallerException e) {
2225                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2226                                    + e.getMessage());
2227                        }
2228                    }
2229                }
2230            }
2231
2232            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2233
2234            final VersionInfo ver = mSettings.getInternalVersion();
2235            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2236
2237            // when upgrading from pre-M, promote system app permissions from install to runtime
2238            mPromoteSystemApps =
2239                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2240
2241            // When upgrading from pre-N, we need to handle package extraction like first boot,
2242            // as there is no profiling data available.
2243            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2244
2245            // save off the names of pre-existing system packages prior to scanning; we don't
2246            // want to automatically grant runtime permissions for new system apps
2247            if (mPromoteSystemApps) {
2248                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2249                while (pkgSettingIter.hasNext()) {
2250                    PackageSetting ps = pkgSettingIter.next();
2251                    if (isSystemApp(ps)) {
2252                        mExistingSystemPackages.add(ps.name);
2253                    }
2254                }
2255            }
2256
2257            // Collect vendor overlay packages.
2258            // (Do this before scanning any apps.)
2259            // For security and version matching reason, only consider
2260            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2261            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2262            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2263                    | PackageParser.PARSE_IS_SYSTEM
2264                    | PackageParser.PARSE_IS_SYSTEM_DIR
2265                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2266
2267            // Find base frameworks (resource packages without code).
2268            scanDirTracedLI(frameworkDir, mDefParseFlags
2269                    | PackageParser.PARSE_IS_SYSTEM
2270                    | PackageParser.PARSE_IS_SYSTEM_DIR
2271                    | PackageParser.PARSE_IS_PRIVILEGED,
2272                    scanFlags | SCAN_NO_DEX, 0);
2273
2274            // Collected privileged system packages.
2275            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2276            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2277                    | PackageParser.PARSE_IS_SYSTEM
2278                    | PackageParser.PARSE_IS_SYSTEM_DIR
2279                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2280
2281            // Collect ordinary system packages.
2282            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2283            scanDirTracedLI(systemAppDir, mDefParseFlags
2284                    | PackageParser.PARSE_IS_SYSTEM
2285                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2286
2287            // Collect all vendor packages.
2288            File vendorAppDir = new File("/vendor/app");
2289            try {
2290                vendorAppDir = vendorAppDir.getCanonicalFile();
2291            } catch (IOException e) {
2292                // failed to look up canonical path, continue with original one
2293            }
2294            scanDirTracedLI(vendorAppDir, mDefParseFlags
2295                    | PackageParser.PARSE_IS_SYSTEM
2296                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2297
2298            // Collect all OEM packages.
2299            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2300            scanDirTracedLI(oemAppDir, mDefParseFlags
2301                    | PackageParser.PARSE_IS_SYSTEM
2302                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2303
2304            // Prune any system packages that no longer exist.
2305            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2306            if (!mOnlyCore) {
2307                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2308                while (psit.hasNext()) {
2309                    PackageSetting ps = psit.next();
2310
2311                    /*
2312                     * If this is not a system app, it can't be a
2313                     * disable system app.
2314                     */
2315                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2316                        continue;
2317                    }
2318
2319                    /*
2320                     * If the package is scanned, it's not erased.
2321                     */
2322                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2323                    if (scannedPkg != null) {
2324                        /*
2325                         * If the system app is both scanned and in the
2326                         * disabled packages list, then it must have been
2327                         * added via OTA. Remove it from the currently
2328                         * scanned package so the previously user-installed
2329                         * application can be scanned.
2330                         */
2331                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2332                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2333                                    + ps.name + "; removing system app.  Last known codePath="
2334                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2335                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2336                                    + scannedPkg.mVersionCode);
2337                            removePackageLI(scannedPkg, true);
2338                            mExpectingBetter.put(ps.name, ps.codePath);
2339                        }
2340
2341                        continue;
2342                    }
2343
2344                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2345                        psit.remove();
2346                        logCriticalInfo(Log.WARN, "System package " + ps.name
2347                                + " no longer exists; it's data will be wiped");
2348                        // Actual deletion of code and data will be handled by later
2349                        // reconciliation step
2350                    } else {
2351                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2352                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2353                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2354                        }
2355                    }
2356                }
2357            }
2358
2359            //look for any incomplete package installations
2360            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2361            for (int i = 0; i < deletePkgsList.size(); i++) {
2362                // Actual deletion of code and data will be handled by later
2363                // reconciliation step
2364                final String packageName = deletePkgsList.get(i).name;
2365                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2366                synchronized (mPackages) {
2367                    mSettings.removePackageLPw(packageName);
2368                }
2369            }
2370
2371            //delete tmp files
2372            deleteTempPackageFiles();
2373
2374            // Remove any shared userIDs that have no associated packages
2375            mSettings.pruneSharedUsersLPw();
2376
2377            if (!mOnlyCore) {
2378                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2379                        SystemClock.uptimeMillis());
2380                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2381
2382                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2383                        | PackageParser.PARSE_FORWARD_LOCK,
2384                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2385
2386                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2387                        | PackageParser.PARSE_IS_EPHEMERAL,
2388                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2389
2390                /**
2391                 * Remove disable package settings for any updated system
2392                 * apps that were removed via an OTA. If they're not a
2393                 * previously-updated app, remove them completely.
2394                 * Otherwise, just revoke their system-level permissions.
2395                 */
2396                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2397                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2398                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2399
2400                    String msg;
2401                    if (deletedPkg == null) {
2402                        msg = "Updated system package " + deletedAppName
2403                                + " no longer exists; it's data will be wiped";
2404                        // Actual deletion of code and data will be handled by later
2405                        // reconciliation step
2406                    } else {
2407                        msg = "Updated system app + " + deletedAppName
2408                                + " no longer present; removing system privileges for "
2409                                + deletedAppName;
2410
2411                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2412
2413                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2414                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2415                    }
2416                    logCriticalInfo(Log.WARN, msg);
2417                }
2418
2419                /**
2420                 * Make sure all system apps that we expected to appear on
2421                 * the userdata partition actually showed up. If they never
2422                 * appeared, crawl back and revive the system version.
2423                 */
2424                for (int i = 0; i < mExpectingBetter.size(); i++) {
2425                    final String packageName = mExpectingBetter.keyAt(i);
2426                    if (!mPackages.containsKey(packageName)) {
2427                        final File scanFile = mExpectingBetter.valueAt(i);
2428
2429                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2430                                + " but never showed up; reverting to system");
2431
2432                        int reparseFlags = mDefParseFlags;
2433                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2434                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2435                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2436                                    | PackageParser.PARSE_IS_PRIVILEGED;
2437                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2438                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2439                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2440                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2441                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2442                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2443                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2444                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2445                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2446                        } else {
2447                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2448                            continue;
2449                        }
2450
2451                        mSettings.enableSystemPackageLPw(packageName);
2452
2453                        try {
2454                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2455                        } catch (PackageManagerException e) {
2456                            Slog.e(TAG, "Failed to parse original system package: "
2457                                    + e.getMessage());
2458                        }
2459                    }
2460                }
2461            }
2462            mExpectingBetter.clear();
2463
2464            // Resolve protected action filters. Only the setup wizard is allowed to
2465            // have a high priority filter for these actions.
2466            mSetupWizardPackage = getSetupWizardPackageName();
2467            if (mProtectedFilters.size() > 0) {
2468                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2469                    Slog.i(TAG, "No setup wizard;"
2470                        + " All protected intents capped to priority 0");
2471                }
2472                for (ActivityIntentInfo filter : mProtectedFilters) {
2473                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2474                        if (DEBUG_FILTERS) {
2475                            Slog.i(TAG, "Found setup wizard;"
2476                                + " allow priority " + filter.getPriority() + ";"
2477                                + " package: " + filter.activity.info.packageName
2478                                + " activity: " + filter.activity.className
2479                                + " priority: " + filter.getPriority());
2480                        }
2481                        // skip setup wizard; allow it to keep the high priority filter
2482                        continue;
2483                    }
2484                    Slog.w(TAG, "Protected action; cap priority to 0;"
2485                            + " package: " + filter.activity.info.packageName
2486                            + " activity: " + filter.activity.className
2487                            + " origPrio: " + filter.getPriority());
2488                    filter.setPriority(0);
2489                }
2490            }
2491            mDeferProtectedFilters = false;
2492            mProtectedFilters.clear();
2493
2494            // Now that we know all of the shared libraries, update all clients to have
2495            // the correct library paths.
2496            updateAllSharedLibrariesLPw();
2497
2498            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2499                // NOTE: We ignore potential failures here during a system scan (like
2500                // the rest of the commands above) because there's precious little we
2501                // can do about it. A settings error is reported, though.
2502                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2503                        false /* boot complete */);
2504            }
2505
2506            // Now that we know all the packages we are keeping,
2507            // read and update their last usage times.
2508            mPackageUsage.read(mPackages);
2509            mCompilerStats.read();
2510
2511            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2512                    SystemClock.uptimeMillis());
2513            Slog.i(TAG, "Time to scan packages: "
2514                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2515                    + " seconds");
2516
2517            // If the platform SDK has changed since the last time we booted,
2518            // we need to re-grant app permission to catch any new ones that
2519            // appear.  This is really a hack, and means that apps can in some
2520            // cases get permissions that the user didn't initially explicitly
2521            // allow...  it would be nice to have some better way to handle
2522            // this situation.
2523            int updateFlags = UPDATE_PERMISSIONS_ALL;
2524            if (ver.sdkVersion != mSdkVersion) {
2525                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2526                        + mSdkVersion + "; regranting permissions for internal storage");
2527                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2528            }
2529            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2530            ver.sdkVersion = mSdkVersion;
2531
2532            // If this is the first boot or an update from pre-M, and it is a normal
2533            // boot, then we need to initialize the default preferred apps across
2534            // all defined users.
2535            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2536                for (UserInfo user : sUserManager.getUsers(true)) {
2537                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2538                    applyFactoryDefaultBrowserLPw(user.id);
2539                    primeDomainVerificationsLPw(user.id);
2540                }
2541            }
2542
2543            // Prepare storage for system user really early during boot,
2544            // since core system apps like SettingsProvider and SystemUI
2545            // can't wait for user to start
2546            final int storageFlags;
2547            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2548                storageFlags = StorageManager.FLAG_STORAGE_DE;
2549            } else {
2550                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2551            }
2552            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2553                    storageFlags);
2554
2555            // If this is first boot after an OTA, and a normal boot, then
2556            // we need to clear code cache directories.
2557            // Note that we do *not* clear the application profiles. These remain valid
2558            // across OTAs and are used to drive profile verification (post OTA) and
2559            // profile compilation (without waiting to collect a fresh set of profiles).
2560            if (mIsUpgrade && !onlyCore) {
2561                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2562                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2563                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2564                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2565                        // No apps are running this early, so no need to freeze
2566                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2567                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2568                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2569                    }
2570                }
2571                ver.fingerprint = Build.FINGERPRINT;
2572            }
2573
2574            checkDefaultBrowser();
2575
2576            // clear only after permissions and other defaults have been updated
2577            mExistingSystemPackages.clear();
2578            mPromoteSystemApps = false;
2579
2580            // All the changes are done during package scanning.
2581            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2582
2583            // can downgrade to reader
2584            mSettings.writeLPr();
2585
2586            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2587            // early on (before the package manager declares itself as early) because other
2588            // components in the system server might ask for package contexts for these apps.
2589            //
2590            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2591            // (i.e, that the data partition is unavailable).
2592            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2593                long start = System.nanoTime();
2594                List<PackageParser.Package> coreApps = new ArrayList<>();
2595                for (PackageParser.Package pkg : mPackages.values()) {
2596                    if (pkg.coreApp) {
2597                        coreApps.add(pkg);
2598                    }
2599                }
2600
2601                int[] stats = performDexOptUpgrade(coreApps, false,
2602                        getCompilerFilterForReason(REASON_CORE_APP));
2603
2604                final int elapsedTimeSeconds =
2605                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2606                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2607
2608                if (DEBUG_DEXOPT) {
2609                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2610                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2611                }
2612
2613
2614                // TODO: Should we log these stats to tron too ?
2615                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2616                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2617                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2618                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2619            }
2620
2621            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2622                    SystemClock.uptimeMillis());
2623
2624            if (!mOnlyCore) {
2625                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2626                mRequiredInstallerPackage = getRequiredInstallerLPr();
2627                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2628                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2629                        mIntentFilterVerifierComponent);
2630                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2631                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2632                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2633                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2634            } else {
2635                mRequiredVerifierPackage = null;
2636                mRequiredInstallerPackage = null;
2637                mIntentFilterVerifierComponent = null;
2638                mIntentFilterVerifier = null;
2639                mServicesSystemSharedLibraryPackageName = null;
2640                mSharedSystemSharedLibraryPackageName = null;
2641            }
2642
2643            mInstallerService = new PackageInstallerService(context, this);
2644
2645            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2646            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2647            // both the installer and resolver must be present to enable ephemeral
2648            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2649                if (DEBUG_EPHEMERAL) {
2650                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2651                            + " installer:" + ephemeralInstallerComponent);
2652                }
2653                mEphemeralResolverComponent = ephemeralResolverComponent;
2654                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2655                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2656                mEphemeralResolverConnection =
2657                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2658            } else {
2659                if (DEBUG_EPHEMERAL) {
2660                    final String missingComponent =
2661                            (ephemeralResolverComponent == null)
2662                            ? (ephemeralInstallerComponent == null)
2663                                    ? "resolver and installer"
2664                                    : "resolver"
2665                            : "installer";
2666                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2667                }
2668                mEphemeralResolverComponent = null;
2669                mEphemeralInstallerComponent = null;
2670                mEphemeralResolverConnection = null;
2671            }
2672
2673            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2674        } // synchronized (mPackages)
2675        } // synchronized (mInstallLock)
2676
2677        // Now after opening every single application zip, make sure they
2678        // are all flushed.  Not really needed, but keeps things nice and
2679        // tidy.
2680        Runtime.getRuntime().gc();
2681
2682        // The initial scanning above does many calls into installd while
2683        // holding the mPackages lock, but we're mostly interested in yelling
2684        // once we have a booted system.
2685        mInstaller.setWarnIfHeld(mPackages);
2686
2687        // Expose private service for system components to use.
2688        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2689    }
2690
2691    @Override
2692    public boolean isFirstBoot() {
2693        return mFirstBoot;
2694    }
2695
2696    @Override
2697    public boolean isOnlyCoreApps() {
2698        return mOnlyCore;
2699    }
2700
2701    @Override
2702    public boolean isUpgrade() {
2703        return mIsUpgrade;
2704    }
2705
2706    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2707        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2708
2709        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2710                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2711                UserHandle.USER_SYSTEM);
2712        if (matches.size() == 1) {
2713            return matches.get(0).getComponentInfo().packageName;
2714        } else {
2715            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2716            return null;
2717        }
2718    }
2719
2720    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2721        synchronized (mPackages) {
2722            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2723            if (libraryEntry == null) {
2724                throw new IllegalStateException("Missing required shared library:" + libraryName);
2725            }
2726            return libraryEntry.apk;
2727        }
2728    }
2729
2730    private @NonNull String getRequiredInstallerLPr() {
2731        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2732        intent.addCategory(Intent.CATEGORY_DEFAULT);
2733        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2734
2735        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2736                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2737                UserHandle.USER_SYSTEM);
2738        if (matches.size() == 1) {
2739            ResolveInfo resolveInfo = matches.get(0);
2740            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2741                throw new RuntimeException("The installer must be a privileged app");
2742            }
2743            return matches.get(0).getComponentInfo().packageName;
2744        } else {
2745            throw new RuntimeException("There must be exactly one installer; found " + matches);
2746        }
2747    }
2748
2749    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2750        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2751
2752        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2753                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2754                UserHandle.USER_SYSTEM);
2755        ResolveInfo best = null;
2756        final int N = matches.size();
2757        for (int i = 0; i < N; i++) {
2758            final ResolveInfo cur = matches.get(i);
2759            final String packageName = cur.getComponentInfo().packageName;
2760            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2761                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2762                continue;
2763            }
2764
2765            if (best == null || cur.priority > best.priority) {
2766                best = cur;
2767            }
2768        }
2769
2770        if (best != null) {
2771            return best.getComponentInfo().getComponentName();
2772        } else {
2773            throw new RuntimeException("There must be at least one intent filter verifier");
2774        }
2775    }
2776
2777    private @Nullable ComponentName getEphemeralResolverLPr() {
2778        final String[] packageArray =
2779                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2780        if (packageArray.length == 0) {
2781            if (DEBUG_EPHEMERAL) {
2782                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2783            }
2784            return null;
2785        }
2786
2787        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2788        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2789                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2790                UserHandle.USER_SYSTEM);
2791
2792        final int N = resolvers.size();
2793        if (N == 0) {
2794            if (DEBUG_EPHEMERAL) {
2795                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2796            }
2797            return null;
2798        }
2799
2800        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2801        for (int i = 0; i < N; i++) {
2802            final ResolveInfo info = resolvers.get(i);
2803
2804            if (info.serviceInfo == null) {
2805                continue;
2806            }
2807
2808            final String packageName = info.serviceInfo.packageName;
2809            if (!possiblePackages.contains(packageName)) {
2810                if (DEBUG_EPHEMERAL) {
2811                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2812                            + " pkg: " + packageName + ", info:" + info);
2813                }
2814                continue;
2815            }
2816
2817            if (DEBUG_EPHEMERAL) {
2818                Slog.v(TAG, "Ephemeral resolver found;"
2819                        + " pkg: " + packageName + ", info:" + info);
2820            }
2821            return new ComponentName(packageName, info.serviceInfo.name);
2822        }
2823        if (DEBUG_EPHEMERAL) {
2824            Slog.v(TAG, "Ephemeral resolver NOT found");
2825        }
2826        return null;
2827    }
2828
2829    private @Nullable ComponentName getEphemeralInstallerLPr() {
2830        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2831        intent.addCategory(Intent.CATEGORY_DEFAULT);
2832        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2833
2834        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2835                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2836                UserHandle.USER_SYSTEM);
2837        if (matches.size() == 0) {
2838            return null;
2839        } else if (matches.size() == 1) {
2840            return matches.get(0).getComponentInfo().getComponentName();
2841        } else {
2842            throw new RuntimeException(
2843                    "There must be at most one ephemeral installer; found " + matches);
2844        }
2845    }
2846
2847    private void primeDomainVerificationsLPw(int userId) {
2848        if (DEBUG_DOMAIN_VERIFICATION) {
2849            Slog.d(TAG, "Priming domain verifications in user " + userId);
2850        }
2851
2852        SystemConfig systemConfig = SystemConfig.getInstance();
2853        ArraySet<String> packages = systemConfig.getLinkedApps();
2854        ArraySet<String> domains = new ArraySet<String>();
2855
2856        for (String packageName : packages) {
2857            PackageParser.Package pkg = mPackages.get(packageName);
2858            if (pkg != null) {
2859                if (!pkg.isSystemApp()) {
2860                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2861                    continue;
2862                }
2863
2864                domains.clear();
2865                for (PackageParser.Activity a : pkg.activities) {
2866                    for (ActivityIntentInfo filter : a.intents) {
2867                        if (hasValidDomains(filter)) {
2868                            domains.addAll(filter.getHostsList());
2869                        }
2870                    }
2871                }
2872
2873                if (domains.size() > 0) {
2874                    if (DEBUG_DOMAIN_VERIFICATION) {
2875                        Slog.v(TAG, "      + " + packageName);
2876                    }
2877                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2878                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2879                    // and then 'always' in the per-user state actually used for intent resolution.
2880                    final IntentFilterVerificationInfo ivi;
2881                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2882                            new ArrayList<String>(domains));
2883                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2884                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2885                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2886                } else {
2887                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2888                            + "' does not handle web links");
2889                }
2890            } else {
2891                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2892            }
2893        }
2894
2895        scheduleWritePackageRestrictionsLocked(userId);
2896        scheduleWriteSettingsLocked();
2897    }
2898
2899    private void applyFactoryDefaultBrowserLPw(int userId) {
2900        // The default browser app's package name is stored in a string resource,
2901        // with a product-specific overlay used for vendor customization.
2902        String browserPkg = mContext.getResources().getString(
2903                com.android.internal.R.string.default_browser);
2904        if (!TextUtils.isEmpty(browserPkg)) {
2905            // non-empty string => required to be a known package
2906            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2907            if (ps == null) {
2908                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2909                browserPkg = null;
2910            } else {
2911                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2912            }
2913        }
2914
2915        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2916        // default.  If there's more than one, just leave everything alone.
2917        if (browserPkg == null) {
2918            calculateDefaultBrowserLPw(userId);
2919        }
2920    }
2921
2922    private void calculateDefaultBrowserLPw(int userId) {
2923        List<String> allBrowsers = resolveAllBrowserApps(userId);
2924        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2925        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2926    }
2927
2928    private List<String> resolveAllBrowserApps(int userId) {
2929        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2930        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2931                PackageManager.MATCH_ALL, userId);
2932
2933        final int count = list.size();
2934        List<String> result = new ArrayList<String>(count);
2935        for (int i=0; i<count; i++) {
2936            ResolveInfo info = list.get(i);
2937            if (info.activityInfo == null
2938                    || !info.handleAllWebDataURI
2939                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2940                    || result.contains(info.activityInfo.packageName)) {
2941                continue;
2942            }
2943            result.add(info.activityInfo.packageName);
2944        }
2945
2946        return result;
2947    }
2948
2949    private boolean packageIsBrowser(String packageName, int userId) {
2950        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2951                PackageManager.MATCH_ALL, userId);
2952        final int N = list.size();
2953        for (int i = 0; i < N; i++) {
2954            ResolveInfo info = list.get(i);
2955            if (packageName.equals(info.activityInfo.packageName)) {
2956                return true;
2957            }
2958        }
2959        return false;
2960    }
2961
2962    private void checkDefaultBrowser() {
2963        final int myUserId = UserHandle.myUserId();
2964        final String packageName = getDefaultBrowserPackageName(myUserId);
2965        if (packageName != null) {
2966            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2967            if (info == null) {
2968                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2969                synchronized (mPackages) {
2970                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2971                }
2972            }
2973        }
2974    }
2975
2976    @Override
2977    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2978            throws RemoteException {
2979        try {
2980            return super.onTransact(code, data, reply, flags);
2981        } catch (RuntimeException e) {
2982            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2983                Slog.wtf(TAG, "Package Manager Crash", e);
2984            }
2985            throw e;
2986        }
2987    }
2988
2989    static int[] appendInts(int[] cur, int[] add) {
2990        if (add == null) return cur;
2991        if (cur == null) return add;
2992        final int N = add.length;
2993        for (int i=0; i<N; i++) {
2994            cur = appendInt(cur, add[i]);
2995        }
2996        return cur;
2997    }
2998
2999    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3000        if (!sUserManager.exists(userId)) return null;
3001        if (ps == null) {
3002            return null;
3003        }
3004        final PackageParser.Package p = ps.pkg;
3005        if (p == null) {
3006            return null;
3007        }
3008
3009        final PermissionsState permissionsState = ps.getPermissionsState();
3010
3011        final int[] gids = permissionsState.computeGids(userId);
3012        final Set<String> permissions = permissionsState.getPermissions(userId);
3013        final PackageUserState state = ps.readUserState(userId);
3014
3015        return PackageParser.generatePackageInfo(p, gids, flags,
3016                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3017    }
3018
3019    @Override
3020    public void checkPackageStartable(String packageName, int userId) {
3021        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3022
3023        synchronized (mPackages) {
3024            final PackageSetting ps = mSettings.mPackages.get(packageName);
3025            if (ps == null) {
3026                throw new SecurityException("Package " + packageName + " was not found!");
3027            }
3028
3029            if (!ps.getInstalled(userId)) {
3030                throw new SecurityException(
3031                        "Package " + packageName + " was not installed for user " + userId + "!");
3032            }
3033
3034            if (mSafeMode && !ps.isSystem()) {
3035                throw new SecurityException("Package " + packageName + " not a system app!");
3036            }
3037
3038            if (mFrozenPackages.contains(packageName)) {
3039                throw new SecurityException("Package " + packageName + " is currently frozen!");
3040            }
3041
3042            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3043                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3044                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3045            }
3046        }
3047    }
3048
3049    @Override
3050    public boolean isPackageAvailable(String packageName, int userId) {
3051        if (!sUserManager.exists(userId)) return false;
3052        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3053                false /* requireFullPermission */, false /* checkShell */, "is package available");
3054        synchronized (mPackages) {
3055            PackageParser.Package p = mPackages.get(packageName);
3056            if (p != null) {
3057                final PackageSetting ps = (PackageSetting) p.mExtras;
3058                if (ps != null) {
3059                    final PackageUserState state = ps.readUserState(userId);
3060                    if (state != null) {
3061                        return PackageParser.isAvailable(state);
3062                    }
3063                }
3064            }
3065        }
3066        return false;
3067    }
3068
3069    @Override
3070    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        flags = updateFlagsForPackage(flags, userId, packageName);
3073        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3074                false /* requireFullPermission */, false /* checkShell */, "get package info");
3075        // reader
3076        synchronized (mPackages) {
3077            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3078            PackageParser.Package p = null;
3079            if (matchFactoryOnly) {
3080                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3081                if (ps != null) {
3082                    return generatePackageInfo(ps, flags, userId);
3083                }
3084            }
3085            if (p == null) {
3086                p = mPackages.get(packageName);
3087                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3088                    return null;
3089                }
3090            }
3091            if (DEBUG_PACKAGE_INFO)
3092                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3093            if (p != null) {
3094                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3095            }
3096            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3097                final PackageSetting ps = mSettings.mPackages.get(packageName);
3098                return generatePackageInfo(ps, flags, userId);
3099            }
3100        }
3101        return null;
3102    }
3103
3104    @Override
3105    public String[] currentToCanonicalPackageNames(String[] names) {
3106        String[] out = new String[names.length];
3107        // reader
3108        synchronized (mPackages) {
3109            for (int i=names.length-1; i>=0; i--) {
3110                PackageSetting ps = mSettings.mPackages.get(names[i]);
3111                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3112            }
3113        }
3114        return out;
3115    }
3116
3117    @Override
3118    public String[] canonicalToCurrentPackageNames(String[] names) {
3119        String[] out = new String[names.length];
3120        // reader
3121        synchronized (mPackages) {
3122            for (int i=names.length-1; i>=0; i--) {
3123                String cur = mSettings.mRenamedPackages.get(names[i]);
3124                out[i] = cur != null ? cur : names[i];
3125            }
3126        }
3127        return out;
3128    }
3129
3130    @Override
3131    public int getPackageUid(String packageName, int flags, int userId) {
3132        if (!sUserManager.exists(userId)) return -1;
3133        flags = updateFlagsForPackage(flags, userId, packageName);
3134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3135                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3136
3137        // reader
3138        synchronized (mPackages) {
3139            final PackageParser.Package p = mPackages.get(packageName);
3140            if (p != null && p.isMatch(flags)) {
3141                return UserHandle.getUid(userId, p.applicationInfo.uid);
3142            }
3143            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3144                final PackageSetting ps = mSettings.mPackages.get(packageName);
3145                if (ps != null && ps.isMatch(flags)) {
3146                    return UserHandle.getUid(userId, ps.appId);
3147                }
3148            }
3149        }
3150
3151        return -1;
3152    }
3153
3154    @Override
3155    public int[] getPackageGids(String packageName, int flags, int userId) {
3156        if (!sUserManager.exists(userId)) return null;
3157        flags = updateFlagsForPackage(flags, userId, packageName);
3158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3159                false /* requireFullPermission */, false /* checkShell */,
3160                "getPackageGids");
3161
3162        // reader
3163        synchronized (mPackages) {
3164            final PackageParser.Package p = mPackages.get(packageName);
3165            if (p != null && p.isMatch(flags)) {
3166                PackageSetting ps = (PackageSetting) p.mExtras;
3167                return ps.getPermissionsState().computeGids(userId);
3168            }
3169            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3170                final PackageSetting ps = mSettings.mPackages.get(packageName);
3171                if (ps != null && ps.isMatch(flags)) {
3172                    return ps.getPermissionsState().computeGids(userId);
3173                }
3174            }
3175        }
3176
3177        return null;
3178    }
3179
3180    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3181        if (bp.perm != null) {
3182            return PackageParser.generatePermissionInfo(bp.perm, flags);
3183        }
3184        PermissionInfo pi = new PermissionInfo();
3185        pi.name = bp.name;
3186        pi.packageName = bp.sourcePackage;
3187        pi.nonLocalizedLabel = bp.name;
3188        pi.protectionLevel = bp.protectionLevel;
3189        return pi;
3190    }
3191
3192    @Override
3193    public PermissionInfo getPermissionInfo(String name, int flags) {
3194        // reader
3195        synchronized (mPackages) {
3196            final BasePermission p = mSettings.mPermissions.get(name);
3197            if (p != null) {
3198                return generatePermissionInfo(p, flags);
3199            }
3200            return null;
3201        }
3202    }
3203
3204    @Override
3205    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3206            int flags) {
3207        // reader
3208        synchronized (mPackages) {
3209            if (group != null && !mPermissionGroups.containsKey(group)) {
3210                // This is thrown as NameNotFoundException
3211                return null;
3212            }
3213
3214            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3215            for (BasePermission p : mSettings.mPermissions.values()) {
3216                if (group == null) {
3217                    if (p.perm == null || p.perm.info.group == null) {
3218                        out.add(generatePermissionInfo(p, flags));
3219                    }
3220                } else {
3221                    if (p.perm != null && group.equals(p.perm.info.group)) {
3222                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3223                    }
3224                }
3225            }
3226            return new ParceledListSlice<>(out);
3227        }
3228    }
3229
3230    @Override
3231    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3232        // reader
3233        synchronized (mPackages) {
3234            return PackageParser.generatePermissionGroupInfo(
3235                    mPermissionGroups.get(name), flags);
3236        }
3237    }
3238
3239    @Override
3240    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3241        // reader
3242        synchronized (mPackages) {
3243            final int N = mPermissionGroups.size();
3244            ArrayList<PermissionGroupInfo> out
3245                    = new ArrayList<PermissionGroupInfo>(N);
3246            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3247                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3248            }
3249            return new ParceledListSlice<>(out);
3250        }
3251    }
3252
3253    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3254            int userId) {
3255        if (!sUserManager.exists(userId)) return null;
3256        PackageSetting ps = mSettings.mPackages.get(packageName);
3257        if (ps != null) {
3258            if (ps.pkg == null) {
3259                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3260                if (pInfo != null) {
3261                    return pInfo.applicationInfo;
3262                }
3263                return null;
3264            }
3265            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3266                    ps.readUserState(userId), userId);
3267        }
3268        return null;
3269    }
3270
3271    @Override
3272    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3273        if (!sUserManager.exists(userId)) return null;
3274        flags = updateFlagsForApplication(flags, userId, packageName);
3275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3276                false /* requireFullPermission */, false /* checkShell */, "get application info");
3277        // writer
3278        synchronized (mPackages) {
3279            PackageParser.Package p = mPackages.get(packageName);
3280            if (DEBUG_PACKAGE_INFO) Log.v(
3281                    TAG, "getApplicationInfo " + packageName
3282                    + ": " + p);
3283            if (p != null) {
3284                PackageSetting ps = mSettings.mPackages.get(packageName);
3285                if (ps == null) return null;
3286                // Note: isEnabledLP() does not apply here - always return info
3287                return PackageParser.generateApplicationInfo(
3288                        p, flags, ps.readUserState(userId), userId);
3289            }
3290            if ("android".equals(packageName)||"system".equals(packageName)) {
3291                return mAndroidApplication;
3292            }
3293            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3294                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3295            }
3296        }
3297        return null;
3298    }
3299
3300    @Override
3301    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3302            final IPackageDataObserver observer) {
3303        mContext.enforceCallingOrSelfPermission(
3304                android.Manifest.permission.CLEAR_APP_CACHE, null);
3305        // Queue up an async operation since clearing cache may take a little while.
3306        mHandler.post(new Runnable() {
3307            public void run() {
3308                mHandler.removeCallbacks(this);
3309                boolean success = true;
3310                synchronized (mInstallLock) {
3311                    try {
3312                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3313                    } catch (InstallerException e) {
3314                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3315                        success = false;
3316                    }
3317                }
3318                if (observer != null) {
3319                    try {
3320                        observer.onRemoveCompleted(null, success);
3321                    } catch (RemoteException e) {
3322                        Slog.w(TAG, "RemoveException when invoking call back");
3323                    }
3324                }
3325            }
3326        });
3327    }
3328
3329    @Override
3330    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3331            final IntentSender pi) {
3332        mContext.enforceCallingOrSelfPermission(
3333                android.Manifest.permission.CLEAR_APP_CACHE, null);
3334        // Queue up an async operation since clearing cache may take a little while.
3335        mHandler.post(new Runnable() {
3336            public void run() {
3337                mHandler.removeCallbacks(this);
3338                boolean success = true;
3339                synchronized (mInstallLock) {
3340                    try {
3341                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3342                    } catch (InstallerException e) {
3343                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3344                        success = false;
3345                    }
3346                }
3347                if(pi != null) {
3348                    try {
3349                        // Callback via pending intent
3350                        int code = success ? 1 : 0;
3351                        pi.sendIntent(null, code, null,
3352                                null, null);
3353                    } catch (SendIntentException e1) {
3354                        Slog.i(TAG, "Failed to send pending intent");
3355                    }
3356                }
3357            }
3358        });
3359    }
3360
3361    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3362        synchronized (mInstallLock) {
3363            try {
3364                mInstaller.freeCache(volumeUuid, freeStorageSize);
3365            } catch (InstallerException e) {
3366                throw new IOException("Failed to free enough space", e);
3367            }
3368        }
3369    }
3370
3371    /**
3372     * Update given flags based on encryption status of current user.
3373     */
3374    private int updateFlags(int flags, int userId) {
3375        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3376                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3377            // Caller expressed an explicit opinion about what encryption
3378            // aware/unaware components they want to see, so fall through and
3379            // give them what they want
3380        } else {
3381            // Caller expressed no opinion, so match based on user state
3382            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3384            } else {
3385                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3386            }
3387        }
3388        return flags;
3389    }
3390
3391    private UserManagerInternal getUserManagerInternal() {
3392        if (mUserManagerInternal == null) {
3393            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3394        }
3395        return mUserManagerInternal;
3396    }
3397
3398    /**
3399     * Update given flags when being used to request {@link PackageInfo}.
3400     */
3401    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3402        boolean triaged = true;
3403        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3404                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3405            // Caller is asking for component details, so they'd better be
3406            // asking for specific encryption matching behavior, or be triaged
3407            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3408                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3409                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3410                triaged = false;
3411            }
3412        }
3413        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3414                | PackageManager.MATCH_SYSTEM_ONLY
3415                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3416            triaged = false;
3417        }
3418        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3419            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3420                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3421        }
3422        return updateFlags(flags, userId);
3423    }
3424
3425    /**
3426     * Update given flags when being used to request {@link ApplicationInfo}.
3427     */
3428    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3429        return updateFlagsForPackage(flags, userId, cookie);
3430    }
3431
3432    /**
3433     * Update given flags when being used to request {@link ComponentInfo}.
3434     */
3435    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3436        if (cookie instanceof Intent) {
3437            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3438                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3439            }
3440        }
3441
3442        boolean triaged = true;
3443        // Caller is asking for component details, so they'd better be
3444        // asking for specific encryption matching behavior, or be triaged
3445        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3446                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3447                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3448            triaged = false;
3449        }
3450        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3451            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3452                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3453        }
3454
3455        return updateFlags(flags, userId);
3456    }
3457
3458    /**
3459     * Update given flags when being used to request {@link ResolveInfo}.
3460     */
3461    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3462        // Safe mode means we shouldn't match any third-party components
3463        if (mSafeMode) {
3464            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3465        }
3466
3467        return updateFlagsForComponent(flags, userId, cookie);
3468    }
3469
3470    @Override
3471    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3472        if (!sUserManager.exists(userId)) return null;
3473        flags = updateFlagsForComponent(flags, userId, component);
3474        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3475                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3476        synchronized (mPackages) {
3477            PackageParser.Activity a = mActivities.mActivities.get(component);
3478
3479            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3480            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3481                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3482                if (ps == null) return null;
3483                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3484                        userId);
3485            }
3486            if (mResolveComponentName.equals(component)) {
3487                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3488                        new PackageUserState(), userId);
3489            }
3490        }
3491        return null;
3492    }
3493
3494    @Override
3495    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3496            String resolvedType) {
3497        synchronized (mPackages) {
3498            if (component.equals(mResolveComponentName)) {
3499                // The resolver supports EVERYTHING!
3500                return true;
3501            }
3502            PackageParser.Activity a = mActivities.mActivities.get(component);
3503            if (a == null) {
3504                return false;
3505            }
3506            for (int i=0; i<a.intents.size(); i++) {
3507                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3508                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3509                    return true;
3510                }
3511            }
3512            return false;
3513        }
3514    }
3515
3516    @Override
3517    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3518        if (!sUserManager.exists(userId)) return null;
3519        flags = updateFlagsForComponent(flags, userId, component);
3520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3521                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3522        synchronized (mPackages) {
3523            PackageParser.Activity a = mReceivers.mActivities.get(component);
3524            if (DEBUG_PACKAGE_INFO) Log.v(
3525                TAG, "getReceiverInfo " + component + ": " + a);
3526            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3527                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3528                if (ps == null) return null;
3529                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3530                        userId);
3531            }
3532        }
3533        return null;
3534    }
3535
3536    @Override
3537    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3538        if (!sUserManager.exists(userId)) return null;
3539        flags = updateFlagsForComponent(flags, userId, component);
3540        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3541                false /* requireFullPermission */, false /* checkShell */, "get service info");
3542        synchronized (mPackages) {
3543            PackageParser.Service s = mServices.mServices.get(component);
3544            if (DEBUG_PACKAGE_INFO) Log.v(
3545                TAG, "getServiceInfo " + component + ": " + s);
3546            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3547                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3548                if (ps == null) return null;
3549                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3550                        userId);
3551            }
3552        }
3553        return null;
3554    }
3555
3556    @Override
3557    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3558        if (!sUserManager.exists(userId)) return null;
3559        flags = updateFlagsForComponent(flags, userId, component);
3560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3561                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3562        synchronized (mPackages) {
3563            PackageParser.Provider p = mProviders.mProviders.get(component);
3564            if (DEBUG_PACKAGE_INFO) Log.v(
3565                TAG, "getProviderInfo " + component + ": " + p);
3566            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3567                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3568                if (ps == null) return null;
3569                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3570                        userId);
3571            }
3572        }
3573        return null;
3574    }
3575
3576    @Override
3577    public String[] getSystemSharedLibraryNames() {
3578        Set<String> libSet;
3579        synchronized (mPackages) {
3580            libSet = mSharedLibraries.keySet();
3581            int size = libSet.size();
3582            if (size > 0) {
3583                String[] libs = new String[size];
3584                libSet.toArray(libs);
3585                return libs;
3586            }
3587        }
3588        return null;
3589    }
3590
3591    @Override
3592    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3593        synchronized (mPackages) {
3594            return mServicesSystemSharedLibraryPackageName;
3595        }
3596    }
3597
3598    @Override
3599    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3600        synchronized (mPackages) {
3601            return mSharedSystemSharedLibraryPackageName;
3602        }
3603    }
3604
3605    @Override
3606    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3607        synchronized (mPackages) {
3608            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3609
3610            final FeatureInfo fi = new FeatureInfo();
3611            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3612                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3613            res.add(fi);
3614
3615            return new ParceledListSlice<>(res);
3616        }
3617    }
3618
3619    @Override
3620    public boolean hasSystemFeature(String name, int version) {
3621        synchronized (mPackages) {
3622            final FeatureInfo feat = mAvailableFeatures.get(name);
3623            if (feat == null) {
3624                return false;
3625            } else {
3626                return feat.version >= version;
3627            }
3628        }
3629    }
3630
3631    @Override
3632    public int checkPermission(String permName, String pkgName, int userId) {
3633        if (!sUserManager.exists(userId)) {
3634            return PackageManager.PERMISSION_DENIED;
3635        }
3636
3637        synchronized (mPackages) {
3638            final PackageParser.Package p = mPackages.get(pkgName);
3639            if (p != null && p.mExtras != null) {
3640                final PackageSetting ps = (PackageSetting) p.mExtras;
3641                final PermissionsState permissionsState = ps.getPermissionsState();
3642                if (permissionsState.hasPermission(permName, userId)) {
3643                    return PackageManager.PERMISSION_GRANTED;
3644                }
3645                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3646                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3647                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3648                    return PackageManager.PERMISSION_GRANTED;
3649                }
3650            }
3651        }
3652
3653        return PackageManager.PERMISSION_DENIED;
3654    }
3655
3656    @Override
3657    public int checkUidPermission(String permName, int uid) {
3658        final int userId = UserHandle.getUserId(uid);
3659
3660        if (!sUserManager.exists(userId)) {
3661            return PackageManager.PERMISSION_DENIED;
3662        }
3663
3664        synchronized (mPackages) {
3665            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3666            if (obj != null) {
3667                final SettingBase ps = (SettingBase) obj;
3668                final PermissionsState permissionsState = ps.getPermissionsState();
3669                if (permissionsState.hasPermission(permName, userId)) {
3670                    return PackageManager.PERMISSION_GRANTED;
3671                }
3672                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3673                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3674                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3675                    return PackageManager.PERMISSION_GRANTED;
3676                }
3677            } else {
3678                ArraySet<String> perms = mSystemPermissions.get(uid);
3679                if (perms != null) {
3680                    if (perms.contains(permName)) {
3681                        return PackageManager.PERMISSION_GRANTED;
3682                    }
3683                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3684                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3685                        return PackageManager.PERMISSION_GRANTED;
3686                    }
3687                }
3688            }
3689        }
3690
3691        return PackageManager.PERMISSION_DENIED;
3692    }
3693
3694    @Override
3695    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3696        if (UserHandle.getCallingUserId() != userId) {
3697            mContext.enforceCallingPermission(
3698                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3699                    "isPermissionRevokedByPolicy for user " + userId);
3700        }
3701
3702        if (checkPermission(permission, packageName, userId)
3703                == PackageManager.PERMISSION_GRANTED) {
3704            return false;
3705        }
3706
3707        final long identity = Binder.clearCallingIdentity();
3708        try {
3709            final int flags = getPermissionFlags(permission, packageName, userId);
3710            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3711        } finally {
3712            Binder.restoreCallingIdentity(identity);
3713        }
3714    }
3715
3716    @Override
3717    public String getPermissionControllerPackageName() {
3718        synchronized (mPackages) {
3719            return mRequiredInstallerPackage;
3720        }
3721    }
3722
3723    /**
3724     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3725     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3726     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3727     * @param message the message to log on security exception
3728     */
3729    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3730            boolean checkShell, String message) {
3731        if (userId < 0) {
3732            throw new IllegalArgumentException("Invalid userId " + userId);
3733        }
3734        if (checkShell) {
3735            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3736        }
3737        if (userId == UserHandle.getUserId(callingUid)) return;
3738        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3739            if (requireFullPermission) {
3740                mContext.enforceCallingOrSelfPermission(
3741                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3742            } else {
3743                try {
3744                    mContext.enforceCallingOrSelfPermission(
3745                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3746                } catch (SecurityException se) {
3747                    mContext.enforceCallingOrSelfPermission(
3748                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3749                }
3750            }
3751        }
3752    }
3753
3754    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3755        if (callingUid == Process.SHELL_UID) {
3756            if (userHandle >= 0
3757                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3758                throw new SecurityException("Shell does not have permission to access user "
3759                        + userHandle);
3760            } else if (userHandle < 0) {
3761                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3762                        + Debug.getCallers(3));
3763            }
3764        }
3765    }
3766
3767    private BasePermission findPermissionTreeLP(String permName) {
3768        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3769            if (permName.startsWith(bp.name) &&
3770                    permName.length() > bp.name.length() &&
3771                    permName.charAt(bp.name.length()) == '.') {
3772                return bp;
3773            }
3774        }
3775        return null;
3776    }
3777
3778    private BasePermission checkPermissionTreeLP(String permName) {
3779        if (permName != null) {
3780            BasePermission bp = findPermissionTreeLP(permName);
3781            if (bp != null) {
3782                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3783                    return bp;
3784                }
3785                throw new SecurityException("Calling uid "
3786                        + Binder.getCallingUid()
3787                        + " is not allowed to add to permission tree "
3788                        + bp.name + " owned by uid " + bp.uid);
3789            }
3790        }
3791        throw new SecurityException("No permission tree found for " + permName);
3792    }
3793
3794    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3795        if (s1 == null) {
3796            return s2 == null;
3797        }
3798        if (s2 == null) {
3799            return false;
3800        }
3801        if (s1.getClass() != s2.getClass()) {
3802            return false;
3803        }
3804        return s1.equals(s2);
3805    }
3806
3807    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3808        if (pi1.icon != pi2.icon) return false;
3809        if (pi1.logo != pi2.logo) return false;
3810        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3811        if (!compareStrings(pi1.name, pi2.name)) return false;
3812        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3813        // We'll take care of setting this one.
3814        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3815        // These are not currently stored in settings.
3816        //if (!compareStrings(pi1.group, pi2.group)) return false;
3817        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3818        //if (pi1.labelRes != pi2.labelRes) return false;
3819        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3820        return true;
3821    }
3822
3823    int permissionInfoFootprint(PermissionInfo info) {
3824        int size = info.name.length();
3825        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3826        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3827        return size;
3828    }
3829
3830    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3831        int size = 0;
3832        for (BasePermission perm : mSettings.mPermissions.values()) {
3833            if (perm.uid == tree.uid) {
3834                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3835            }
3836        }
3837        return size;
3838    }
3839
3840    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3841        // We calculate the max size of permissions defined by this uid and throw
3842        // if that plus the size of 'info' would exceed our stated maximum.
3843        if (tree.uid != Process.SYSTEM_UID) {
3844            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3845            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3846                throw new SecurityException("Permission tree size cap exceeded");
3847            }
3848        }
3849    }
3850
3851    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3852        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3853            throw new SecurityException("Label must be specified in permission");
3854        }
3855        BasePermission tree = checkPermissionTreeLP(info.name);
3856        BasePermission bp = mSettings.mPermissions.get(info.name);
3857        boolean added = bp == null;
3858        boolean changed = true;
3859        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3860        if (added) {
3861            enforcePermissionCapLocked(info, tree);
3862            bp = new BasePermission(info.name, tree.sourcePackage,
3863                    BasePermission.TYPE_DYNAMIC);
3864        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3865            throw new SecurityException(
3866                    "Not allowed to modify non-dynamic permission "
3867                    + info.name);
3868        } else {
3869            if (bp.protectionLevel == fixedLevel
3870                    && bp.perm.owner.equals(tree.perm.owner)
3871                    && bp.uid == tree.uid
3872                    && comparePermissionInfos(bp.perm.info, info)) {
3873                changed = false;
3874            }
3875        }
3876        bp.protectionLevel = fixedLevel;
3877        info = new PermissionInfo(info);
3878        info.protectionLevel = fixedLevel;
3879        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3880        bp.perm.info.packageName = tree.perm.info.packageName;
3881        bp.uid = tree.uid;
3882        if (added) {
3883            mSettings.mPermissions.put(info.name, bp);
3884        }
3885        if (changed) {
3886            if (!async) {
3887                mSettings.writeLPr();
3888            } else {
3889                scheduleWriteSettingsLocked();
3890            }
3891        }
3892        return added;
3893    }
3894
3895    @Override
3896    public boolean addPermission(PermissionInfo info) {
3897        synchronized (mPackages) {
3898            return addPermissionLocked(info, false);
3899        }
3900    }
3901
3902    @Override
3903    public boolean addPermissionAsync(PermissionInfo info) {
3904        synchronized (mPackages) {
3905            return addPermissionLocked(info, true);
3906        }
3907    }
3908
3909    @Override
3910    public void removePermission(String name) {
3911        synchronized (mPackages) {
3912            checkPermissionTreeLP(name);
3913            BasePermission bp = mSettings.mPermissions.get(name);
3914            if (bp != null) {
3915                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3916                    throw new SecurityException(
3917                            "Not allowed to modify non-dynamic permission "
3918                            + name);
3919                }
3920                mSettings.mPermissions.remove(name);
3921                mSettings.writeLPr();
3922            }
3923        }
3924    }
3925
3926    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3927            BasePermission bp) {
3928        int index = pkg.requestedPermissions.indexOf(bp.name);
3929        if (index == -1) {
3930            throw new SecurityException("Package " + pkg.packageName
3931                    + " has not requested permission " + bp.name);
3932        }
3933        if (!bp.isRuntime() && !bp.isDevelopment()) {
3934            throw new SecurityException("Permission " + bp.name
3935                    + " is not a changeable permission type");
3936        }
3937    }
3938
3939    @Override
3940    public void grantRuntimePermission(String packageName, String name, final int userId) {
3941        if (!sUserManager.exists(userId)) {
3942            Log.e(TAG, "No such user:" + userId);
3943            return;
3944        }
3945
3946        mContext.enforceCallingOrSelfPermission(
3947                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3948                "grantRuntimePermission");
3949
3950        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3951                true /* requireFullPermission */, true /* checkShell */,
3952                "grantRuntimePermission");
3953
3954        final int uid;
3955        final SettingBase sb;
3956
3957        synchronized (mPackages) {
3958            final PackageParser.Package pkg = mPackages.get(packageName);
3959            if (pkg == null) {
3960                throw new IllegalArgumentException("Unknown package: " + packageName);
3961            }
3962
3963            final BasePermission bp = mSettings.mPermissions.get(name);
3964            if (bp == null) {
3965                throw new IllegalArgumentException("Unknown permission: " + name);
3966            }
3967
3968            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3969
3970            // If a permission review is required for legacy apps we represent
3971            // their permissions as always granted runtime ones since we need
3972            // to keep the review required permission flag per user while an
3973            // install permission's state is shared across all users.
3974            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
3975                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3976                    && bp.isRuntime()) {
3977                return;
3978            }
3979
3980            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3981            sb = (SettingBase) pkg.mExtras;
3982            if (sb == null) {
3983                throw new IllegalArgumentException("Unknown package: " + packageName);
3984            }
3985
3986            final PermissionsState permissionsState = sb.getPermissionsState();
3987
3988            final int flags = permissionsState.getPermissionFlags(name, userId);
3989            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3990                throw new SecurityException("Cannot grant system fixed permission "
3991                        + name + " for package " + packageName);
3992            }
3993
3994            if (bp.isDevelopment()) {
3995                // Development permissions must be handled specially, since they are not
3996                // normal runtime permissions.  For now they apply to all users.
3997                if (permissionsState.grantInstallPermission(bp) !=
3998                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3999                    scheduleWriteSettingsLocked();
4000                }
4001                return;
4002            }
4003
4004            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4005                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4006                return;
4007            }
4008
4009            final int result = permissionsState.grantRuntimePermission(bp, userId);
4010            switch (result) {
4011                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4012                    return;
4013                }
4014
4015                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4016                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4017                    mHandler.post(new Runnable() {
4018                        @Override
4019                        public void run() {
4020                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4021                        }
4022                    });
4023                }
4024                break;
4025            }
4026
4027            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4028
4029            // Not critical if that is lost - app has to request again.
4030            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4031        }
4032
4033        // Only need to do this if user is initialized. Otherwise it's a new user
4034        // and there are no processes running as the user yet and there's no need
4035        // to make an expensive call to remount processes for the changed permissions.
4036        if (READ_EXTERNAL_STORAGE.equals(name)
4037                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4038            final long token = Binder.clearCallingIdentity();
4039            try {
4040                if (sUserManager.isInitialized(userId)) {
4041                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4042                            MountServiceInternal.class);
4043                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4044                }
4045            } finally {
4046                Binder.restoreCallingIdentity(token);
4047            }
4048        }
4049    }
4050
4051    @Override
4052    public void revokeRuntimePermission(String packageName, String name, int userId) {
4053        if (!sUserManager.exists(userId)) {
4054            Log.e(TAG, "No such user:" + userId);
4055            return;
4056        }
4057
4058        mContext.enforceCallingOrSelfPermission(
4059                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4060                "revokeRuntimePermission");
4061
4062        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4063                true /* requireFullPermission */, true /* checkShell */,
4064                "revokeRuntimePermission");
4065
4066        final int appId;
4067
4068        synchronized (mPackages) {
4069            final PackageParser.Package pkg = mPackages.get(packageName);
4070            if (pkg == null) {
4071                throw new IllegalArgumentException("Unknown package: " + packageName);
4072            }
4073
4074            final BasePermission bp = mSettings.mPermissions.get(name);
4075            if (bp == null) {
4076                throw new IllegalArgumentException("Unknown permission: " + name);
4077            }
4078
4079            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4080
4081            // If a permission review is required for legacy apps we represent
4082            // their permissions as always granted runtime ones since we need
4083            // to keep the review required permission flag per user while an
4084            // install permission's state is shared across all users.
4085            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4086                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4087                    && bp.isRuntime()) {
4088                return;
4089            }
4090
4091            SettingBase sb = (SettingBase) pkg.mExtras;
4092            if (sb == null) {
4093                throw new IllegalArgumentException("Unknown package: " + packageName);
4094            }
4095
4096            final PermissionsState permissionsState = sb.getPermissionsState();
4097
4098            final int flags = permissionsState.getPermissionFlags(name, userId);
4099            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4100                throw new SecurityException("Cannot revoke system fixed permission "
4101                        + name + " for package " + packageName);
4102            }
4103
4104            if (bp.isDevelopment()) {
4105                // Development permissions must be handled specially, since they are not
4106                // normal runtime permissions.  For now they apply to all users.
4107                if (permissionsState.revokeInstallPermission(bp) !=
4108                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4109                    scheduleWriteSettingsLocked();
4110                }
4111                return;
4112            }
4113
4114            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4115                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4116                return;
4117            }
4118
4119            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4120
4121            // Critical, after this call app should never have the permission.
4122            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4123
4124            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4125        }
4126
4127        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4128    }
4129
4130    @Override
4131    public void resetRuntimePermissions() {
4132        mContext.enforceCallingOrSelfPermission(
4133                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4134                "revokeRuntimePermission");
4135
4136        int callingUid = Binder.getCallingUid();
4137        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4138            mContext.enforceCallingOrSelfPermission(
4139                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4140                    "resetRuntimePermissions");
4141        }
4142
4143        synchronized (mPackages) {
4144            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4145            for (int userId : UserManagerService.getInstance().getUserIds()) {
4146                final int packageCount = mPackages.size();
4147                for (int i = 0; i < packageCount; i++) {
4148                    PackageParser.Package pkg = mPackages.valueAt(i);
4149                    if (!(pkg.mExtras instanceof PackageSetting)) {
4150                        continue;
4151                    }
4152                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4153                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4154                }
4155            }
4156        }
4157    }
4158
4159    @Override
4160    public int getPermissionFlags(String name, String packageName, int userId) {
4161        if (!sUserManager.exists(userId)) {
4162            return 0;
4163        }
4164
4165        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4166
4167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4168                true /* requireFullPermission */, false /* checkShell */,
4169                "getPermissionFlags");
4170
4171        synchronized (mPackages) {
4172            final PackageParser.Package pkg = mPackages.get(packageName);
4173            if (pkg == null) {
4174                return 0;
4175            }
4176
4177            final BasePermission bp = mSettings.mPermissions.get(name);
4178            if (bp == null) {
4179                return 0;
4180            }
4181
4182            SettingBase sb = (SettingBase) pkg.mExtras;
4183            if (sb == null) {
4184                return 0;
4185            }
4186
4187            PermissionsState permissionsState = sb.getPermissionsState();
4188            return permissionsState.getPermissionFlags(name, userId);
4189        }
4190    }
4191
4192    @Override
4193    public void updatePermissionFlags(String name, String packageName, int flagMask,
4194            int flagValues, int userId) {
4195        if (!sUserManager.exists(userId)) {
4196            return;
4197        }
4198
4199        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4200
4201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4202                true /* requireFullPermission */, true /* checkShell */,
4203                "updatePermissionFlags");
4204
4205        // Only the system can change these flags and nothing else.
4206        if (getCallingUid() != Process.SYSTEM_UID) {
4207            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4208            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4209            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4210            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4211            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4212        }
4213
4214        synchronized (mPackages) {
4215            final PackageParser.Package pkg = mPackages.get(packageName);
4216            if (pkg == null) {
4217                throw new IllegalArgumentException("Unknown package: " + packageName);
4218            }
4219
4220            final BasePermission bp = mSettings.mPermissions.get(name);
4221            if (bp == null) {
4222                throw new IllegalArgumentException("Unknown permission: " + name);
4223            }
4224
4225            SettingBase sb = (SettingBase) pkg.mExtras;
4226            if (sb == null) {
4227                throw new IllegalArgumentException("Unknown package: " + packageName);
4228            }
4229
4230            PermissionsState permissionsState = sb.getPermissionsState();
4231
4232            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4233
4234            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4235                // Install and runtime permissions are stored in different places,
4236                // so figure out what permission changed and persist the change.
4237                if (permissionsState.getInstallPermissionState(name) != null) {
4238                    scheduleWriteSettingsLocked();
4239                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4240                        || hadState) {
4241                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4242                }
4243            }
4244        }
4245    }
4246
4247    /**
4248     * Update the permission flags for all packages and runtime permissions of a user in order
4249     * to allow device or profile owner to remove POLICY_FIXED.
4250     */
4251    @Override
4252    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4253        if (!sUserManager.exists(userId)) {
4254            return;
4255        }
4256
4257        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4258
4259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4260                true /* requireFullPermission */, true /* checkShell */,
4261                "updatePermissionFlagsForAllApps");
4262
4263        // Only the system can change system fixed flags.
4264        if (getCallingUid() != Process.SYSTEM_UID) {
4265            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4266            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4267        }
4268
4269        synchronized (mPackages) {
4270            boolean changed = false;
4271            final int packageCount = mPackages.size();
4272            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4273                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4274                SettingBase sb = (SettingBase) pkg.mExtras;
4275                if (sb == null) {
4276                    continue;
4277                }
4278                PermissionsState permissionsState = sb.getPermissionsState();
4279                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4280                        userId, flagMask, flagValues);
4281            }
4282            if (changed) {
4283                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4284            }
4285        }
4286    }
4287
4288    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4289        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4290                != PackageManager.PERMISSION_GRANTED
4291            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4292                != PackageManager.PERMISSION_GRANTED) {
4293            throw new SecurityException(message + " requires "
4294                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4295                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4296        }
4297    }
4298
4299    @Override
4300    public boolean shouldShowRequestPermissionRationale(String permissionName,
4301            String packageName, int userId) {
4302        if (UserHandle.getCallingUserId() != userId) {
4303            mContext.enforceCallingPermission(
4304                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4305                    "canShowRequestPermissionRationale for user " + userId);
4306        }
4307
4308        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4309        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4310            return false;
4311        }
4312
4313        if (checkPermission(permissionName, packageName, userId)
4314                == PackageManager.PERMISSION_GRANTED) {
4315            return false;
4316        }
4317
4318        final int flags;
4319
4320        final long identity = Binder.clearCallingIdentity();
4321        try {
4322            flags = getPermissionFlags(permissionName,
4323                    packageName, userId);
4324        } finally {
4325            Binder.restoreCallingIdentity(identity);
4326        }
4327
4328        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4329                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4330                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4331
4332        if ((flags & fixedFlags) != 0) {
4333            return false;
4334        }
4335
4336        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4337    }
4338
4339    @Override
4340    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4341        mContext.enforceCallingOrSelfPermission(
4342                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4343                "addOnPermissionsChangeListener");
4344
4345        synchronized (mPackages) {
4346            mOnPermissionChangeListeners.addListenerLocked(listener);
4347        }
4348    }
4349
4350    @Override
4351    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4352        synchronized (mPackages) {
4353            mOnPermissionChangeListeners.removeListenerLocked(listener);
4354        }
4355    }
4356
4357    @Override
4358    public boolean isProtectedBroadcast(String actionName) {
4359        synchronized (mPackages) {
4360            if (mProtectedBroadcasts.contains(actionName)) {
4361                return true;
4362            } else if (actionName != null) {
4363                // TODO: remove these terrible hacks
4364                if (actionName.startsWith("android.net.netmon.lingerExpired")
4365                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4366                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4367                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4368                    return true;
4369                }
4370            }
4371        }
4372        return false;
4373    }
4374
4375    @Override
4376    public int checkSignatures(String pkg1, String pkg2) {
4377        synchronized (mPackages) {
4378            final PackageParser.Package p1 = mPackages.get(pkg1);
4379            final PackageParser.Package p2 = mPackages.get(pkg2);
4380            if (p1 == null || p1.mExtras == null
4381                    || p2 == null || p2.mExtras == null) {
4382                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4383            }
4384            return compareSignatures(p1.mSignatures, p2.mSignatures);
4385        }
4386    }
4387
4388    @Override
4389    public int checkUidSignatures(int uid1, int uid2) {
4390        // Map to base uids.
4391        uid1 = UserHandle.getAppId(uid1);
4392        uid2 = UserHandle.getAppId(uid2);
4393        // reader
4394        synchronized (mPackages) {
4395            Signature[] s1;
4396            Signature[] s2;
4397            Object obj = mSettings.getUserIdLPr(uid1);
4398            if (obj != null) {
4399                if (obj instanceof SharedUserSetting) {
4400                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4401                } else if (obj instanceof PackageSetting) {
4402                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4403                } else {
4404                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4405                }
4406            } else {
4407                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4408            }
4409            obj = mSettings.getUserIdLPr(uid2);
4410            if (obj != null) {
4411                if (obj instanceof SharedUserSetting) {
4412                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4413                } else if (obj instanceof PackageSetting) {
4414                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4415                } else {
4416                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4417                }
4418            } else {
4419                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4420            }
4421            return compareSignatures(s1, s2);
4422        }
4423    }
4424
4425    /**
4426     * This method should typically only be used when granting or revoking
4427     * permissions, since the app may immediately restart after this call.
4428     * <p>
4429     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4430     * guard your work against the app being relaunched.
4431     */
4432    private void killUid(int appId, int userId, String reason) {
4433        final long identity = Binder.clearCallingIdentity();
4434        try {
4435            IActivityManager am = ActivityManagerNative.getDefault();
4436            if (am != null) {
4437                try {
4438                    am.killUid(appId, userId, reason);
4439                } catch (RemoteException e) {
4440                    /* ignore - same process */
4441                }
4442            }
4443        } finally {
4444            Binder.restoreCallingIdentity(identity);
4445        }
4446    }
4447
4448    /**
4449     * Compares two sets of signatures. Returns:
4450     * <br />
4451     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4452     * <br />
4453     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4454     * <br />
4455     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4456     * <br />
4457     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4458     * <br />
4459     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4460     */
4461    static int compareSignatures(Signature[] s1, Signature[] s2) {
4462        if (s1 == null) {
4463            return s2 == null
4464                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4465                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4466        }
4467
4468        if (s2 == null) {
4469            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4470        }
4471
4472        if (s1.length != s2.length) {
4473            return PackageManager.SIGNATURE_NO_MATCH;
4474        }
4475
4476        // Since both signature sets are of size 1, we can compare without HashSets.
4477        if (s1.length == 1) {
4478            return s1[0].equals(s2[0]) ?
4479                    PackageManager.SIGNATURE_MATCH :
4480                    PackageManager.SIGNATURE_NO_MATCH;
4481        }
4482
4483        ArraySet<Signature> set1 = new ArraySet<Signature>();
4484        for (Signature sig : s1) {
4485            set1.add(sig);
4486        }
4487        ArraySet<Signature> set2 = new ArraySet<Signature>();
4488        for (Signature sig : s2) {
4489            set2.add(sig);
4490        }
4491        // Make sure s2 contains all signatures in s1.
4492        if (set1.equals(set2)) {
4493            return PackageManager.SIGNATURE_MATCH;
4494        }
4495        return PackageManager.SIGNATURE_NO_MATCH;
4496    }
4497
4498    /**
4499     * If the database version for this type of package (internal storage or
4500     * external storage) is less than the version where package signatures
4501     * were updated, return true.
4502     */
4503    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4504        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4505        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4506    }
4507
4508    /**
4509     * Used for backward compatibility to make sure any packages with
4510     * certificate chains get upgraded to the new style. {@code existingSigs}
4511     * will be in the old format (since they were stored on disk from before the
4512     * system upgrade) and {@code scannedSigs} will be in the newer format.
4513     */
4514    private int compareSignaturesCompat(PackageSignatures existingSigs,
4515            PackageParser.Package scannedPkg) {
4516        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4517            return PackageManager.SIGNATURE_NO_MATCH;
4518        }
4519
4520        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4521        for (Signature sig : existingSigs.mSignatures) {
4522            existingSet.add(sig);
4523        }
4524        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4525        for (Signature sig : scannedPkg.mSignatures) {
4526            try {
4527                Signature[] chainSignatures = sig.getChainSignatures();
4528                for (Signature chainSig : chainSignatures) {
4529                    scannedCompatSet.add(chainSig);
4530                }
4531            } catch (CertificateEncodingException e) {
4532                scannedCompatSet.add(sig);
4533            }
4534        }
4535        /*
4536         * Make sure the expanded scanned set contains all signatures in the
4537         * existing one.
4538         */
4539        if (scannedCompatSet.equals(existingSet)) {
4540            // Migrate the old signatures to the new scheme.
4541            existingSigs.assignSignatures(scannedPkg.mSignatures);
4542            // The new KeySets will be re-added later in the scanning process.
4543            synchronized (mPackages) {
4544                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4545            }
4546            return PackageManager.SIGNATURE_MATCH;
4547        }
4548        return PackageManager.SIGNATURE_NO_MATCH;
4549    }
4550
4551    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4552        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4553        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4554    }
4555
4556    private int compareSignaturesRecover(PackageSignatures existingSigs,
4557            PackageParser.Package scannedPkg) {
4558        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4559            return PackageManager.SIGNATURE_NO_MATCH;
4560        }
4561
4562        String msg = null;
4563        try {
4564            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4565                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4566                        + scannedPkg.packageName);
4567                return PackageManager.SIGNATURE_MATCH;
4568            }
4569        } catch (CertificateException e) {
4570            msg = e.getMessage();
4571        }
4572
4573        logCriticalInfo(Log.INFO,
4574                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4575        return PackageManager.SIGNATURE_NO_MATCH;
4576    }
4577
4578    @Override
4579    public List<String> getAllPackages() {
4580        synchronized (mPackages) {
4581            return new ArrayList<String>(mPackages.keySet());
4582        }
4583    }
4584
4585    @Override
4586    public String[] getPackagesForUid(int uid) {
4587        final int userId = UserHandle.getUserId(uid);
4588        uid = UserHandle.getAppId(uid);
4589        // reader
4590        synchronized (mPackages) {
4591            Object obj = mSettings.getUserIdLPr(uid);
4592            if (obj instanceof SharedUserSetting) {
4593                final SharedUserSetting sus = (SharedUserSetting) obj;
4594                final int N = sus.packages.size();
4595                String[] res = new String[N];
4596                final Iterator<PackageSetting> it = sus.packages.iterator();
4597                int i = 0;
4598                while (it.hasNext()) {
4599                    PackageSetting ps = it.next();
4600                    if (ps.getInstalled(userId)) {
4601                        res[i++] = ps.name;
4602                    } else {
4603                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4604                    }
4605                }
4606                return res;
4607            } else if (obj instanceof PackageSetting) {
4608                final PackageSetting ps = (PackageSetting) obj;
4609                return new String[] { ps.name };
4610            }
4611        }
4612        return null;
4613    }
4614
4615    @Override
4616    public String getNameForUid(int uid) {
4617        // reader
4618        synchronized (mPackages) {
4619            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4620            if (obj instanceof SharedUserSetting) {
4621                final SharedUserSetting sus = (SharedUserSetting) obj;
4622                return sus.name + ":" + sus.userId;
4623            } else if (obj instanceof PackageSetting) {
4624                final PackageSetting ps = (PackageSetting) obj;
4625                return ps.name;
4626            }
4627        }
4628        return null;
4629    }
4630
4631    @Override
4632    public int getUidForSharedUser(String sharedUserName) {
4633        if(sharedUserName == null) {
4634            return -1;
4635        }
4636        // reader
4637        synchronized (mPackages) {
4638            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4639            if (suid == null) {
4640                return -1;
4641            }
4642            return suid.userId;
4643        }
4644    }
4645
4646    @Override
4647    public int getFlagsForUid(int uid) {
4648        synchronized (mPackages) {
4649            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4650            if (obj instanceof SharedUserSetting) {
4651                final SharedUserSetting sus = (SharedUserSetting) obj;
4652                return sus.pkgFlags;
4653            } else if (obj instanceof PackageSetting) {
4654                final PackageSetting ps = (PackageSetting) obj;
4655                return ps.pkgFlags;
4656            }
4657        }
4658        return 0;
4659    }
4660
4661    @Override
4662    public int getPrivateFlagsForUid(int uid) {
4663        synchronized (mPackages) {
4664            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4665            if (obj instanceof SharedUserSetting) {
4666                final SharedUserSetting sus = (SharedUserSetting) obj;
4667                return sus.pkgPrivateFlags;
4668            } else if (obj instanceof PackageSetting) {
4669                final PackageSetting ps = (PackageSetting) obj;
4670                return ps.pkgPrivateFlags;
4671            }
4672        }
4673        return 0;
4674    }
4675
4676    @Override
4677    public boolean isUidPrivileged(int uid) {
4678        uid = UserHandle.getAppId(uid);
4679        // reader
4680        synchronized (mPackages) {
4681            Object obj = mSettings.getUserIdLPr(uid);
4682            if (obj instanceof SharedUserSetting) {
4683                final SharedUserSetting sus = (SharedUserSetting) obj;
4684                final Iterator<PackageSetting> it = sus.packages.iterator();
4685                while (it.hasNext()) {
4686                    if (it.next().isPrivileged()) {
4687                        return true;
4688                    }
4689                }
4690            } else if (obj instanceof PackageSetting) {
4691                final PackageSetting ps = (PackageSetting) obj;
4692                return ps.isPrivileged();
4693            }
4694        }
4695        return false;
4696    }
4697
4698    @Override
4699    public String[] getAppOpPermissionPackages(String permissionName) {
4700        synchronized (mPackages) {
4701            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4702            if (pkgs == null) {
4703                return null;
4704            }
4705            return pkgs.toArray(new String[pkgs.size()]);
4706        }
4707    }
4708
4709    @Override
4710    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4711            int flags, int userId) {
4712        try {
4713            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4714
4715            if (!sUserManager.exists(userId)) return null;
4716            flags = updateFlagsForResolve(flags, userId, intent);
4717            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4718                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4719
4720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4721            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4722                    flags, userId);
4723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4724
4725            final ResolveInfo bestChoice =
4726                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4727
4728            if (isEphemeralAllowed(intent, query, userId)) {
4729                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4730                final EphemeralResolveInfo ai =
4731                        getEphemeralResolveInfo(intent, resolvedType, userId);
4732                if (ai != null) {
4733                    if (DEBUG_EPHEMERAL) {
4734                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4735                    }
4736                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4737                    bestChoice.ephemeralResolveInfo = ai;
4738                }
4739                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4740            }
4741            return bestChoice;
4742        } finally {
4743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4744        }
4745    }
4746
4747    @Override
4748    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4749            IntentFilter filter, int match, ComponentName activity) {
4750        final int userId = UserHandle.getCallingUserId();
4751        if (DEBUG_PREFERRED) {
4752            Log.v(TAG, "setLastChosenActivity intent=" + intent
4753                + " resolvedType=" + resolvedType
4754                + " flags=" + flags
4755                + " filter=" + filter
4756                + " match=" + match
4757                + " activity=" + activity);
4758            filter.dump(new PrintStreamPrinter(System.out), "    ");
4759        }
4760        intent.setComponent(null);
4761        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4762                userId);
4763        // Find any earlier preferred or last chosen entries and nuke them
4764        findPreferredActivity(intent, resolvedType,
4765                flags, query, 0, false, true, false, userId);
4766        // Add the new activity as the last chosen for this filter
4767        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4768                "Setting last chosen");
4769    }
4770
4771    @Override
4772    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4773        final int userId = UserHandle.getCallingUserId();
4774        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4775        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4776                userId);
4777        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4778                false, false, false, userId);
4779    }
4780
4781
4782    private boolean isEphemeralAllowed(
4783            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4784        // Short circuit and return early if possible.
4785        if (DISABLE_EPHEMERAL_APPS) {
4786            return false;
4787        }
4788        final int callingUser = UserHandle.getCallingUserId();
4789        if (callingUser != UserHandle.USER_SYSTEM) {
4790            return false;
4791        }
4792        if (mEphemeralResolverConnection == null) {
4793            return false;
4794        }
4795        if (intent.getComponent() != null) {
4796            return false;
4797        }
4798        if (intent.getPackage() != null) {
4799            return false;
4800        }
4801        final boolean isWebUri = hasWebURI(intent);
4802        if (!isWebUri) {
4803            return false;
4804        }
4805        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4806        synchronized (mPackages) {
4807            final int count = resolvedActivites.size();
4808            for (int n = 0; n < count; n++) {
4809                ResolveInfo info = resolvedActivites.get(n);
4810                String packageName = info.activityInfo.packageName;
4811                PackageSetting ps = mSettings.mPackages.get(packageName);
4812                if (ps != null) {
4813                    // Try to get the status from User settings first
4814                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4815                    int status = (int) (packedStatus >> 32);
4816                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4817                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4818                        if (DEBUG_EPHEMERAL) {
4819                            Slog.v(TAG, "DENY ephemeral apps;"
4820                                + " pkg: " + packageName + ", status: " + status);
4821                        }
4822                        return false;
4823                    }
4824                }
4825            }
4826        }
4827        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4828        return true;
4829    }
4830
4831    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4832            int userId) {
4833        MessageDigest digest = null;
4834        try {
4835            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4836        } catch (NoSuchAlgorithmException e) {
4837            // If we can't create a digest, ignore ephemeral apps.
4838            return null;
4839        }
4840
4841        final byte[] hostBytes = intent.getData().getHost().getBytes();
4842        final byte[] digestBytes = digest.digest(hostBytes);
4843        int shaPrefix =
4844                digestBytes[0] << 24
4845                | digestBytes[1] << 16
4846                | digestBytes[2] << 8
4847                | digestBytes[3] << 0;
4848        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4849                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4850        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4851            // No hash prefix match; there are no ephemeral apps for this domain.
4852            return null;
4853        }
4854        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4855            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4856            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4857                continue;
4858            }
4859            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4860            // No filters; this should never happen.
4861            if (filters.isEmpty()) {
4862                continue;
4863            }
4864            // We have a domain match; resolve the filters to see if anything matches.
4865            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4866            for (int j = filters.size() - 1; j >= 0; --j) {
4867                final EphemeralResolveIntentInfo intentInfo =
4868                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4869                ephemeralResolver.addFilter(intentInfo);
4870            }
4871            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4872                    intent, resolvedType, false /*defaultOnly*/, userId);
4873            if (!matchedResolveInfoList.isEmpty()) {
4874                return matchedResolveInfoList.get(0);
4875            }
4876        }
4877        // Hash or filter mis-match; no ephemeral apps for this domain.
4878        return null;
4879    }
4880
4881    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4882            int flags, List<ResolveInfo> query, int userId) {
4883        if (query != null) {
4884            final int N = query.size();
4885            if (N == 1) {
4886                return query.get(0);
4887            } else if (N > 1) {
4888                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4889                // If there is more than one activity with the same priority,
4890                // then let the user decide between them.
4891                ResolveInfo r0 = query.get(0);
4892                ResolveInfo r1 = query.get(1);
4893                if (DEBUG_INTENT_MATCHING || debug) {
4894                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4895                            + r1.activityInfo.name + "=" + r1.priority);
4896                }
4897                // If the first activity has a higher priority, or a different
4898                // default, then it is always desirable to pick it.
4899                if (r0.priority != r1.priority
4900                        || r0.preferredOrder != r1.preferredOrder
4901                        || r0.isDefault != r1.isDefault) {
4902                    return query.get(0);
4903                }
4904                // If we have saved a preference for a preferred activity for
4905                // this Intent, use that.
4906                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4907                        flags, query, r0.priority, true, false, debug, userId);
4908                if (ri != null) {
4909                    return ri;
4910                }
4911                ri = new ResolveInfo(mResolveInfo);
4912                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4913                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4914                // If all of the options come from the same package, show the application's
4915                // label and icon instead of the generic resolver's.
4916                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4917                // and then throw away the ResolveInfo itself, meaning that the caller loses
4918                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4919                // a fallback for this case; we only set the target package's resources on
4920                // the ResolveInfo, not the ActivityInfo.
4921                final String intentPackage = intent.getPackage();
4922                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4923                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4924                    ri.resolvePackageName = intentPackage;
4925                    if (userNeedsBadging(userId)) {
4926                        ri.noResourceId = true;
4927                    } else {
4928                        ri.icon = appi.icon;
4929                    }
4930                    ri.iconResourceId = appi.icon;
4931                    ri.labelRes = appi.labelRes;
4932                }
4933                ri.activityInfo.applicationInfo = new ApplicationInfo(
4934                        ri.activityInfo.applicationInfo);
4935                if (userId != 0) {
4936                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4937                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4938                }
4939                // Make sure that the resolver is displayable in car mode
4940                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4941                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4942                return ri;
4943            }
4944        }
4945        return null;
4946    }
4947
4948    /**
4949     * Return true if the given list is not empty and all of its contents have
4950     * an activityInfo with the given package name.
4951     */
4952    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4953        if (ArrayUtils.isEmpty(list)) {
4954            return false;
4955        }
4956        for (int i = 0, N = list.size(); i < N; i++) {
4957            final ResolveInfo ri = list.get(i);
4958            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4959            if (ai == null || !packageName.equals(ai.packageName)) {
4960                return false;
4961            }
4962        }
4963        return true;
4964    }
4965
4966    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4967            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4968        final int N = query.size();
4969        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4970                .get(userId);
4971        // Get the list of persistent preferred activities that handle the intent
4972        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4973        List<PersistentPreferredActivity> pprefs = ppir != null
4974                ? ppir.queryIntent(intent, resolvedType,
4975                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4976                : null;
4977        if (pprefs != null && pprefs.size() > 0) {
4978            final int M = pprefs.size();
4979            for (int i=0; i<M; i++) {
4980                final PersistentPreferredActivity ppa = pprefs.get(i);
4981                if (DEBUG_PREFERRED || debug) {
4982                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4983                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4984                            + "\n  component=" + ppa.mComponent);
4985                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4986                }
4987                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4988                        flags | MATCH_DISABLED_COMPONENTS, userId);
4989                if (DEBUG_PREFERRED || debug) {
4990                    Slog.v(TAG, "Found persistent preferred activity:");
4991                    if (ai != null) {
4992                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4993                    } else {
4994                        Slog.v(TAG, "  null");
4995                    }
4996                }
4997                if (ai == null) {
4998                    // This previously registered persistent preferred activity
4999                    // component is no longer known. Ignore it and do NOT remove it.
5000                    continue;
5001                }
5002                for (int j=0; j<N; j++) {
5003                    final ResolveInfo ri = query.get(j);
5004                    if (!ri.activityInfo.applicationInfo.packageName
5005                            .equals(ai.applicationInfo.packageName)) {
5006                        continue;
5007                    }
5008                    if (!ri.activityInfo.name.equals(ai.name)) {
5009                        continue;
5010                    }
5011                    //  Found a persistent preference that can handle the intent.
5012                    if (DEBUG_PREFERRED || debug) {
5013                        Slog.v(TAG, "Returning persistent preferred activity: " +
5014                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5015                    }
5016                    return ri;
5017                }
5018            }
5019        }
5020        return null;
5021    }
5022
5023    // TODO: handle preferred activities missing while user has amnesia
5024    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5025            List<ResolveInfo> query, int priority, boolean always,
5026            boolean removeMatches, boolean debug, int userId) {
5027        if (!sUserManager.exists(userId)) return null;
5028        flags = updateFlagsForResolve(flags, userId, intent);
5029        // writer
5030        synchronized (mPackages) {
5031            if (intent.getSelector() != null) {
5032                intent = intent.getSelector();
5033            }
5034            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5035
5036            // Try to find a matching persistent preferred activity.
5037            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5038                    debug, userId);
5039
5040            // If a persistent preferred activity matched, use it.
5041            if (pri != null) {
5042                return pri;
5043            }
5044
5045            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5046            // Get the list of preferred activities that handle the intent
5047            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5048            List<PreferredActivity> prefs = pir != null
5049                    ? pir.queryIntent(intent, resolvedType,
5050                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5051                    : null;
5052            if (prefs != null && prefs.size() > 0) {
5053                boolean changed = false;
5054                try {
5055                    // First figure out how good the original match set is.
5056                    // We will only allow preferred activities that came
5057                    // from the same match quality.
5058                    int match = 0;
5059
5060                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5061
5062                    final int N = query.size();
5063                    for (int j=0; j<N; j++) {
5064                        final ResolveInfo ri = query.get(j);
5065                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5066                                + ": 0x" + Integer.toHexString(match));
5067                        if (ri.match > match) {
5068                            match = ri.match;
5069                        }
5070                    }
5071
5072                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5073                            + Integer.toHexString(match));
5074
5075                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5076                    final int M = prefs.size();
5077                    for (int i=0; i<M; i++) {
5078                        final PreferredActivity pa = prefs.get(i);
5079                        if (DEBUG_PREFERRED || debug) {
5080                            Slog.v(TAG, "Checking PreferredActivity ds="
5081                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5082                                    + "\n  component=" + pa.mPref.mComponent);
5083                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5084                        }
5085                        if (pa.mPref.mMatch != match) {
5086                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5087                                    + Integer.toHexString(pa.mPref.mMatch));
5088                            continue;
5089                        }
5090                        // If it's not an "always" type preferred activity and that's what we're
5091                        // looking for, skip it.
5092                        if (always && !pa.mPref.mAlways) {
5093                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5094                            continue;
5095                        }
5096                        final ActivityInfo ai = getActivityInfo(
5097                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5098                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5099                                userId);
5100                        if (DEBUG_PREFERRED || debug) {
5101                            Slog.v(TAG, "Found preferred activity:");
5102                            if (ai != null) {
5103                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5104                            } else {
5105                                Slog.v(TAG, "  null");
5106                            }
5107                        }
5108                        if (ai == null) {
5109                            // This previously registered preferred activity
5110                            // component is no longer known.  Most likely an update
5111                            // to the app was installed and in the new version this
5112                            // component no longer exists.  Clean it up by removing
5113                            // it from the preferred activities list, and skip it.
5114                            Slog.w(TAG, "Removing dangling preferred activity: "
5115                                    + pa.mPref.mComponent);
5116                            pir.removeFilter(pa);
5117                            changed = true;
5118                            continue;
5119                        }
5120                        for (int j=0; j<N; j++) {
5121                            final ResolveInfo ri = query.get(j);
5122                            if (!ri.activityInfo.applicationInfo.packageName
5123                                    .equals(ai.applicationInfo.packageName)) {
5124                                continue;
5125                            }
5126                            if (!ri.activityInfo.name.equals(ai.name)) {
5127                                continue;
5128                            }
5129
5130                            if (removeMatches) {
5131                                pir.removeFilter(pa);
5132                                changed = true;
5133                                if (DEBUG_PREFERRED) {
5134                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5135                                }
5136                                break;
5137                            }
5138
5139                            // Okay we found a previously set preferred or last chosen app.
5140                            // If the result set is different from when this
5141                            // was created, we need to clear it and re-ask the
5142                            // user their preference, if we're looking for an "always" type entry.
5143                            if (always && !pa.mPref.sameSet(query)) {
5144                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5145                                        + intent + " type " + resolvedType);
5146                                if (DEBUG_PREFERRED) {
5147                                    Slog.v(TAG, "Removing preferred activity since set changed "
5148                                            + pa.mPref.mComponent);
5149                                }
5150                                pir.removeFilter(pa);
5151                                // Re-add the filter as a "last chosen" entry (!always)
5152                                PreferredActivity lastChosen = new PreferredActivity(
5153                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5154                                pir.addFilter(lastChosen);
5155                                changed = true;
5156                                return null;
5157                            }
5158
5159                            // Yay! Either the set matched or we're looking for the last chosen
5160                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5161                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5162                            return ri;
5163                        }
5164                    }
5165                } finally {
5166                    if (changed) {
5167                        if (DEBUG_PREFERRED) {
5168                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5169                        }
5170                        scheduleWritePackageRestrictionsLocked(userId);
5171                    }
5172                }
5173            }
5174        }
5175        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5176        return null;
5177    }
5178
5179    /*
5180     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5181     */
5182    @Override
5183    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5184            int targetUserId) {
5185        mContext.enforceCallingOrSelfPermission(
5186                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5187        List<CrossProfileIntentFilter> matches =
5188                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5189        if (matches != null) {
5190            int size = matches.size();
5191            for (int i = 0; i < size; i++) {
5192                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5193            }
5194        }
5195        if (hasWebURI(intent)) {
5196            // cross-profile app linking works only towards the parent.
5197            final UserInfo parent = getProfileParent(sourceUserId);
5198            synchronized(mPackages) {
5199                int flags = updateFlagsForResolve(0, parent.id, intent);
5200                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5201                        intent, resolvedType, flags, sourceUserId, parent.id);
5202                return xpDomainInfo != null;
5203            }
5204        }
5205        return false;
5206    }
5207
5208    private UserInfo getProfileParent(int userId) {
5209        final long identity = Binder.clearCallingIdentity();
5210        try {
5211            return sUserManager.getProfileParent(userId);
5212        } finally {
5213            Binder.restoreCallingIdentity(identity);
5214        }
5215    }
5216
5217    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5218            String resolvedType, int userId) {
5219        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5220        if (resolver != null) {
5221            return resolver.queryIntent(intent, resolvedType, false, userId);
5222        }
5223        return null;
5224    }
5225
5226    @Override
5227    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5228            String resolvedType, int flags, int userId) {
5229        try {
5230            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5231
5232            return new ParceledListSlice<>(
5233                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5234        } finally {
5235            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5236        }
5237    }
5238
5239    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5240            String resolvedType, int flags, int userId) {
5241        if (!sUserManager.exists(userId)) return Collections.emptyList();
5242        flags = updateFlagsForResolve(flags, userId, intent);
5243        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5244                false /* requireFullPermission */, false /* checkShell */,
5245                "query intent activities");
5246        ComponentName comp = intent.getComponent();
5247        if (comp == null) {
5248            if (intent.getSelector() != null) {
5249                intent = intent.getSelector();
5250                comp = intent.getComponent();
5251            }
5252        }
5253
5254        if (comp != null) {
5255            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5256            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5257            if (ai != null) {
5258                final ResolveInfo ri = new ResolveInfo();
5259                ri.activityInfo = ai;
5260                list.add(ri);
5261            }
5262            return list;
5263        }
5264
5265        // reader
5266        synchronized (mPackages) {
5267            final String pkgName = intent.getPackage();
5268            if (pkgName == null) {
5269                List<CrossProfileIntentFilter> matchingFilters =
5270                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5271                // Check for results that need to skip the current profile.
5272                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5273                        resolvedType, flags, userId);
5274                if (xpResolveInfo != null) {
5275                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5276                    result.add(xpResolveInfo);
5277                    return filterIfNotSystemUser(result, userId);
5278                }
5279
5280                // Check for results in the current profile.
5281                List<ResolveInfo> result = mActivities.queryIntent(
5282                        intent, resolvedType, flags, userId);
5283                result = filterIfNotSystemUser(result, userId);
5284
5285                // Check for cross profile results.
5286                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5287                xpResolveInfo = queryCrossProfileIntents(
5288                        matchingFilters, intent, resolvedType, flags, userId,
5289                        hasNonNegativePriorityResult);
5290                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5291                    boolean isVisibleToUser = filterIfNotSystemUser(
5292                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5293                    if (isVisibleToUser) {
5294                        result.add(xpResolveInfo);
5295                        Collections.sort(result, mResolvePrioritySorter);
5296                    }
5297                }
5298                if (hasWebURI(intent)) {
5299                    CrossProfileDomainInfo xpDomainInfo = null;
5300                    final UserInfo parent = getProfileParent(userId);
5301                    if (parent != null) {
5302                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5303                                flags, userId, parent.id);
5304                    }
5305                    if (xpDomainInfo != null) {
5306                        if (xpResolveInfo != null) {
5307                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5308                            // in the result.
5309                            result.remove(xpResolveInfo);
5310                        }
5311                        if (result.size() == 0) {
5312                            result.add(xpDomainInfo.resolveInfo);
5313                            return result;
5314                        }
5315                    } else if (result.size() <= 1) {
5316                        return result;
5317                    }
5318                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5319                            xpDomainInfo, userId);
5320                    Collections.sort(result, mResolvePrioritySorter);
5321                }
5322                return result;
5323            }
5324            final PackageParser.Package pkg = mPackages.get(pkgName);
5325            if (pkg != null) {
5326                return filterIfNotSystemUser(
5327                        mActivities.queryIntentForPackage(
5328                                intent, resolvedType, flags, pkg.activities, userId),
5329                        userId);
5330            }
5331            return new ArrayList<ResolveInfo>();
5332        }
5333    }
5334
5335    private static class CrossProfileDomainInfo {
5336        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5337        ResolveInfo resolveInfo;
5338        /* Best domain verification status of the activities found in the other profile */
5339        int bestDomainVerificationStatus;
5340    }
5341
5342    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5343            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5344        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5345                sourceUserId)) {
5346            return null;
5347        }
5348        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5349                resolvedType, flags, parentUserId);
5350
5351        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5352            return null;
5353        }
5354        CrossProfileDomainInfo result = null;
5355        int size = resultTargetUser.size();
5356        for (int i = 0; i < size; i++) {
5357            ResolveInfo riTargetUser = resultTargetUser.get(i);
5358            // Intent filter verification is only for filters that specify a host. So don't return
5359            // those that handle all web uris.
5360            if (riTargetUser.handleAllWebDataURI) {
5361                continue;
5362            }
5363            String packageName = riTargetUser.activityInfo.packageName;
5364            PackageSetting ps = mSettings.mPackages.get(packageName);
5365            if (ps == null) {
5366                continue;
5367            }
5368            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5369            int status = (int)(verificationState >> 32);
5370            if (result == null) {
5371                result = new CrossProfileDomainInfo();
5372                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5373                        sourceUserId, parentUserId);
5374                result.bestDomainVerificationStatus = status;
5375            } else {
5376                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5377                        result.bestDomainVerificationStatus);
5378            }
5379        }
5380        // Don't consider matches with status NEVER across profiles.
5381        if (result != null && result.bestDomainVerificationStatus
5382                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5383            return null;
5384        }
5385        return result;
5386    }
5387
5388    /**
5389     * Verification statuses are ordered from the worse to the best, except for
5390     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5391     */
5392    private int bestDomainVerificationStatus(int status1, int status2) {
5393        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5394            return status2;
5395        }
5396        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5397            return status1;
5398        }
5399        return (int) MathUtils.max(status1, status2);
5400    }
5401
5402    private boolean isUserEnabled(int userId) {
5403        long callingId = Binder.clearCallingIdentity();
5404        try {
5405            UserInfo userInfo = sUserManager.getUserInfo(userId);
5406            return userInfo != null && userInfo.isEnabled();
5407        } finally {
5408            Binder.restoreCallingIdentity(callingId);
5409        }
5410    }
5411
5412    /**
5413     * Filter out activities with systemUserOnly flag set, when current user is not System.
5414     *
5415     * @return filtered list
5416     */
5417    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5418        if (userId == UserHandle.USER_SYSTEM) {
5419            return resolveInfos;
5420        }
5421        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5422            ResolveInfo info = resolveInfos.get(i);
5423            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5424                resolveInfos.remove(i);
5425            }
5426        }
5427        return resolveInfos;
5428    }
5429
5430    /**
5431     * @param resolveInfos list of resolve infos in descending priority order
5432     * @return if the list contains a resolve info with non-negative priority
5433     */
5434    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5435        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5436    }
5437
5438    private static boolean hasWebURI(Intent intent) {
5439        if (intent.getData() == null) {
5440            return false;
5441        }
5442        final String scheme = intent.getScheme();
5443        if (TextUtils.isEmpty(scheme)) {
5444            return false;
5445        }
5446        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5447    }
5448
5449    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5450            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5451            int userId) {
5452        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5453
5454        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5455            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5456                    candidates.size());
5457        }
5458
5459        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5460        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5461        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5462        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5463        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5464        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5465
5466        synchronized (mPackages) {
5467            final int count = candidates.size();
5468            // First, try to use linked apps. Partition the candidates into four lists:
5469            // one for the final results, one for the "do not use ever", one for "undefined status"
5470            // and finally one for "browser app type".
5471            for (int n=0; n<count; n++) {
5472                ResolveInfo info = candidates.get(n);
5473                String packageName = info.activityInfo.packageName;
5474                PackageSetting ps = mSettings.mPackages.get(packageName);
5475                if (ps != null) {
5476                    // Add to the special match all list (Browser use case)
5477                    if (info.handleAllWebDataURI) {
5478                        matchAllList.add(info);
5479                        continue;
5480                    }
5481                    // Try to get the status from User settings first
5482                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5483                    int status = (int)(packedStatus >> 32);
5484                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5485                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5486                        if (DEBUG_DOMAIN_VERIFICATION) {
5487                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5488                                    + " : linkgen=" + linkGeneration);
5489                        }
5490                        // Use link-enabled generation as preferredOrder, i.e.
5491                        // prefer newly-enabled over earlier-enabled.
5492                        info.preferredOrder = linkGeneration;
5493                        alwaysList.add(info);
5494                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5495                        if (DEBUG_DOMAIN_VERIFICATION) {
5496                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5497                        }
5498                        neverList.add(info);
5499                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5500                        if (DEBUG_DOMAIN_VERIFICATION) {
5501                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5502                        }
5503                        alwaysAskList.add(info);
5504                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5505                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5506                        if (DEBUG_DOMAIN_VERIFICATION) {
5507                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5508                        }
5509                        undefinedList.add(info);
5510                    }
5511                }
5512            }
5513
5514            // We'll want to include browser possibilities in a few cases
5515            boolean includeBrowser = false;
5516
5517            // First try to add the "always" resolution(s) for the current user, if any
5518            if (alwaysList.size() > 0) {
5519                result.addAll(alwaysList);
5520            } else {
5521                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5522                result.addAll(undefinedList);
5523                // Maybe add one for the other profile.
5524                if (xpDomainInfo != null && (
5525                        xpDomainInfo.bestDomainVerificationStatus
5526                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5527                    result.add(xpDomainInfo.resolveInfo);
5528                }
5529                includeBrowser = true;
5530            }
5531
5532            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5533            // If there were 'always' entries their preferred order has been set, so we also
5534            // back that off to make the alternatives equivalent
5535            if (alwaysAskList.size() > 0) {
5536                for (ResolveInfo i : result) {
5537                    i.preferredOrder = 0;
5538                }
5539                result.addAll(alwaysAskList);
5540                includeBrowser = true;
5541            }
5542
5543            if (includeBrowser) {
5544                // Also add browsers (all of them or only the default one)
5545                if (DEBUG_DOMAIN_VERIFICATION) {
5546                    Slog.v(TAG, "   ...including browsers in candidate set");
5547                }
5548                if ((matchFlags & MATCH_ALL) != 0) {
5549                    result.addAll(matchAllList);
5550                } else {
5551                    // Browser/generic handling case.  If there's a default browser, go straight
5552                    // to that (but only if there is no other higher-priority match).
5553                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5554                    int maxMatchPrio = 0;
5555                    ResolveInfo defaultBrowserMatch = null;
5556                    final int numCandidates = matchAllList.size();
5557                    for (int n = 0; n < numCandidates; n++) {
5558                        ResolveInfo info = matchAllList.get(n);
5559                        // track the highest overall match priority...
5560                        if (info.priority > maxMatchPrio) {
5561                            maxMatchPrio = info.priority;
5562                        }
5563                        // ...and the highest-priority default browser match
5564                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5565                            if (defaultBrowserMatch == null
5566                                    || (defaultBrowserMatch.priority < info.priority)) {
5567                                if (debug) {
5568                                    Slog.v(TAG, "Considering default browser match " + info);
5569                                }
5570                                defaultBrowserMatch = info;
5571                            }
5572                        }
5573                    }
5574                    if (defaultBrowserMatch != null
5575                            && defaultBrowserMatch.priority >= maxMatchPrio
5576                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5577                    {
5578                        if (debug) {
5579                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5580                        }
5581                        result.add(defaultBrowserMatch);
5582                    } else {
5583                        result.addAll(matchAllList);
5584                    }
5585                }
5586
5587                // If there is nothing selected, add all candidates and remove the ones that the user
5588                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5589                if (result.size() == 0) {
5590                    result.addAll(candidates);
5591                    result.removeAll(neverList);
5592                }
5593            }
5594        }
5595        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5596            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5597                    result.size());
5598            for (ResolveInfo info : result) {
5599                Slog.v(TAG, "  + " + info.activityInfo);
5600            }
5601        }
5602        return result;
5603    }
5604
5605    // Returns a packed value as a long:
5606    //
5607    // high 'int'-sized word: link status: undefined/ask/never/always.
5608    // low 'int'-sized word: relative priority among 'always' results.
5609    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5610        long result = ps.getDomainVerificationStatusForUser(userId);
5611        // if none available, get the master status
5612        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5613            if (ps.getIntentFilterVerificationInfo() != null) {
5614                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5615            }
5616        }
5617        return result;
5618    }
5619
5620    private ResolveInfo querySkipCurrentProfileIntents(
5621            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5622            int flags, int sourceUserId) {
5623        if (matchingFilters != null) {
5624            int size = matchingFilters.size();
5625            for (int i = 0; i < size; i ++) {
5626                CrossProfileIntentFilter filter = matchingFilters.get(i);
5627                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5628                    // Checking if there are activities in the target user that can handle the
5629                    // intent.
5630                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5631                            resolvedType, flags, sourceUserId);
5632                    if (resolveInfo != null) {
5633                        return resolveInfo;
5634                    }
5635                }
5636            }
5637        }
5638        return null;
5639    }
5640
5641    // Return matching ResolveInfo in target user if any.
5642    private ResolveInfo queryCrossProfileIntents(
5643            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5644            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5645        if (matchingFilters != null) {
5646            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5647            // match the same intent. For performance reasons, it is better not to
5648            // run queryIntent twice for the same userId
5649            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5650            int size = matchingFilters.size();
5651            for (int i = 0; i < size; i++) {
5652                CrossProfileIntentFilter filter = matchingFilters.get(i);
5653                int targetUserId = filter.getTargetUserId();
5654                boolean skipCurrentProfile =
5655                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5656                boolean skipCurrentProfileIfNoMatchFound =
5657                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5658                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5659                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5660                    // Checking if there are activities in the target user that can handle the
5661                    // intent.
5662                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5663                            resolvedType, flags, sourceUserId);
5664                    if (resolveInfo != null) return resolveInfo;
5665                    alreadyTriedUserIds.put(targetUserId, true);
5666                }
5667            }
5668        }
5669        return null;
5670    }
5671
5672    /**
5673     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5674     * will forward the intent to the filter's target user.
5675     * Otherwise, returns null.
5676     */
5677    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5678            String resolvedType, int flags, int sourceUserId) {
5679        int targetUserId = filter.getTargetUserId();
5680        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5681                resolvedType, flags, targetUserId);
5682        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5683            // If all the matches in the target profile are suspended, return null.
5684            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5685                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5686                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5687                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5688                            targetUserId);
5689                }
5690            }
5691        }
5692        return null;
5693    }
5694
5695    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5696            int sourceUserId, int targetUserId) {
5697        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5698        long ident = Binder.clearCallingIdentity();
5699        boolean targetIsProfile;
5700        try {
5701            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5702        } finally {
5703            Binder.restoreCallingIdentity(ident);
5704        }
5705        String className;
5706        if (targetIsProfile) {
5707            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5708        } else {
5709            className = FORWARD_INTENT_TO_PARENT;
5710        }
5711        ComponentName forwardingActivityComponentName = new ComponentName(
5712                mAndroidApplication.packageName, className);
5713        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5714                sourceUserId);
5715        if (!targetIsProfile) {
5716            forwardingActivityInfo.showUserIcon = targetUserId;
5717            forwardingResolveInfo.noResourceId = true;
5718        }
5719        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5720        forwardingResolveInfo.priority = 0;
5721        forwardingResolveInfo.preferredOrder = 0;
5722        forwardingResolveInfo.match = 0;
5723        forwardingResolveInfo.isDefault = true;
5724        forwardingResolveInfo.filter = filter;
5725        forwardingResolveInfo.targetUserId = targetUserId;
5726        return forwardingResolveInfo;
5727    }
5728
5729    @Override
5730    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5731            Intent[] specifics, String[] specificTypes, Intent intent,
5732            String resolvedType, int flags, int userId) {
5733        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5734                specificTypes, intent, resolvedType, flags, userId));
5735    }
5736
5737    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5738            Intent[] specifics, String[] specificTypes, Intent intent,
5739            String resolvedType, int flags, int userId) {
5740        if (!sUserManager.exists(userId)) return Collections.emptyList();
5741        flags = updateFlagsForResolve(flags, userId, intent);
5742        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5743                false /* requireFullPermission */, false /* checkShell */,
5744                "query intent activity options");
5745        final String resultsAction = intent.getAction();
5746
5747        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5748                | PackageManager.GET_RESOLVED_FILTER, userId);
5749
5750        if (DEBUG_INTENT_MATCHING) {
5751            Log.v(TAG, "Query " + intent + ": " + results);
5752        }
5753
5754        int specificsPos = 0;
5755        int N;
5756
5757        // todo: note that the algorithm used here is O(N^2).  This
5758        // isn't a problem in our current environment, but if we start running
5759        // into situations where we have more than 5 or 10 matches then this
5760        // should probably be changed to something smarter...
5761
5762        // First we go through and resolve each of the specific items
5763        // that were supplied, taking care of removing any corresponding
5764        // duplicate items in the generic resolve list.
5765        if (specifics != null) {
5766            for (int i=0; i<specifics.length; i++) {
5767                final Intent sintent = specifics[i];
5768                if (sintent == null) {
5769                    continue;
5770                }
5771
5772                if (DEBUG_INTENT_MATCHING) {
5773                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5774                }
5775
5776                String action = sintent.getAction();
5777                if (resultsAction != null && resultsAction.equals(action)) {
5778                    // If this action was explicitly requested, then don't
5779                    // remove things that have it.
5780                    action = null;
5781                }
5782
5783                ResolveInfo ri = null;
5784                ActivityInfo ai = null;
5785
5786                ComponentName comp = sintent.getComponent();
5787                if (comp == null) {
5788                    ri = resolveIntent(
5789                        sintent,
5790                        specificTypes != null ? specificTypes[i] : null,
5791                            flags, userId);
5792                    if (ri == null) {
5793                        continue;
5794                    }
5795                    if (ri == mResolveInfo) {
5796                        // ACK!  Must do something better with this.
5797                    }
5798                    ai = ri.activityInfo;
5799                    comp = new ComponentName(ai.applicationInfo.packageName,
5800                            ai.name);
5801                } else {
5802                    ai = getActivityInfo(comp, flags, userId);
5803                    if (ai == null) {
5804                        continue;
5805                    }
5806                }
5807
5808                // Look for any generic query activities that are duplicates
5809                // of this specific one, and remove them from the results.
5810                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5811                N = results.size();
5812                int j;
5813                for (j=specificsPos; j<N; j++) {
5814                    ResolveInfo sri = results.get(j);
5815                    if ((sri.activityInfo.name.equals(comp.getClassName())
5816                            && sri.activityInfo.applicationInfo.packageName.equals(
5817                                    comp.getPackageName()))
5818                        || (action != null && sri.filter.matchAction(action))) {
5819                        results.remove(j);
5820                        if (DEBUG_INTENT_MATCHING) Log.v(
5821                            TAG, "Removing duplicate item from " + j
5822                            + " due to specific " + specificsPos);
5823                        if (ri == null) {
5824                            ri = sri;
5825                        }
5826                        j--;
5827                        N--;
5828                    }
5829                }
5830
5831                // Add this specific item to its proper place.
5832                if (ri == null) {
5833                    ri = new ResolveInfo();
5834                    ri.activityInfo = ai;
5835                }
5836                results.add(specificsPos, ri);
5837                ri.specificIndex = i;
5838                specificsPos++;
5839            }
5840        }
5841
5842        // Now we go through the remaining generic results and remove any
5843        // duplicate actions that are found here.
5844        N = results.size();
5845        for (int i=specificsPos; i<N-1; i++) {
5846            final ResolveInfo rii = results.get(i);
5847            if (rii.filter == null) {
5848                continue;
5849            }
5850
5851            // Iterate over all of the actions of this result's intent
5852            // filter...  typically this should be just one.
5853            final Iterator<String> it = rii.filter.actionsIterator();
5854            if (it == null) {
5855                continue;
5856            }
5857            while (it.hasNext()) {
5858                final String action = it.next();
5859                if (resultsAction != null && resultsAction.equals(action)) {
5860                    // If this action was explicitly requested, then don't
5861                    // remove things that have it.
5862                    continue;
5863                }
5864                for (int j=i+1; j<N; j++) {
5865                    final ResolveInfo rij = results.get(j);
5866                    if (rij.filter != null && rij.filter.hasAction(action)) {
5867                        results.remove(j);
5868                        if (DEBUG_INTENT_MATCHING) Log.v(
5869                            TAG, "Removing duplicate item from " + j
5870                            + " due to action " + action + " at " + i);
5871                        j--;
5872                        N--;
5873                    }
5874                }
5875            }
5876
5877            // If the caller didn't request filter information, drop it now
5878            // so we don't have to marshall/unmarshall it.
5879            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5880                rii.filter = null;
5881            }
5882        }
5883
5884        // Filter out the caller activity if so requested.
5885        if (caller != null) {
5886            N = results.size();
5887            for (int i=0; i<N; i++) {
5888                ActivityInfo ainfo = results.get(i).activityInfo;
5889                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5890                        && caller.getClassName().equals(ainfo.name)) {
5891                    results.remove(i);
5892                    break;
5893                }
5894            }
5895        }
5896
5897        // If the caller didn't request filter information,
5898        // drop them now so we don't have to
5899        // marshall/unmarshall it.
5900        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5901            N = results.size();
5902            for (int i=0; i<N; i++) {
5903                results.get(i).filter = null;
5904            }
5905        }
5906
5907        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5908        return results;
5909    }
5910
5911    @Override
5912    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5913            String resolvedType, int flags, int userId) {
5914        return new ParceledListSlice<>(
5915                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5916    }
5917
5918    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5919            String resolvedType, int flags, int userId) {
5920        if (!sUserManager.exists(userId)) return Collections.emptyList();
5921        flags = updateFlagsForResolve(flags, userId, intent);
5922        ComponentName comp = intent.getComponent();
5923        if (comp == null) {
5924            if (intent.getSelector() != null) {
5925                intent = intent.getSelector();
5926                comp = intent.getComponent();
5927            }
5928        }
5929        if (comp != null) {
5930            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5931            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5932            if (ai != null) {
5933                ResolveInfo ri = new ResolveInfo();
5934                ri.activityInfo = ai;
5935                list.add(ri);
5936            }
5937            return list;
5938        }
5939
5940        // reader
5941        synchronized (mPackages) {
5942            String pkgName = intent.getPackage();
5943            if (pkgName == null) {
5944                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5945            }
5946            final PackageParser.Package pkg = mPackages.get(pkgName);
5947            if (pkg != null) {
5948                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5949                        userId);
5950            }
5951            return Collections.emptyList();
5952        }
5953    }
5954
5955    @Override
5956    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5957        if (!sUserManager.exists(userId)) return null;
5958        flags = updateFlagsForResolve(flags, userId, intent);
5959        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5960        if (query != null) {
5961            if (query.size() >= 1) {
5962                // If there is more than one service with the same priority,
5963                // just arbitrarily pick the first one.
5964                return query.get(0);
5965            }
5966        }
5967        return null;
5968    }
5969
5970    @Override
5971    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5972            String resolvedType, int flags, int userId) {
5973        return new ParceledListSlice<>(
5974                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5975    }
5976
5977    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5978            String resolvedType, int flags, int userId) {
5979        if (!sUserManager.exists(userId)) return Collections.emptyList();
5980        flags = updateFlagsForResolve(flags, userId, intent);
5981        ComponentName comp = intent.getComponent();
5982        if (comp == null) {
5983            if (intent.getSelector() != null) {
5984                intent = intent.getSelector();
5985                comp = intent.getComponent();
5986            }
5987        }
5988        if (comp != null) {
5989            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5990            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5991            if (si != null) {
5992                final ResolveInfo ri = new ResolveInfo();
5993                ri.serviceInfo = si;
5994                list.add(ri);
5995            }
5996            return list;
5997        }
5998
5999        // reader
6000        synchronized (mPackages) {
6001            String pkgName = intent.getPackage();
6002            if (pkgName == null) {
6003                return mServices.queryIntent(intent, resolvedType, flags, userId);
6004            }
6005            final PackageParser.Package pkg = mPackages.get(pkgName);
6006            if (pkg != null) {
6007                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6008                        userId);
6009            }
6010            return Collections.emptyList();
6011        }
6012    }
6013
6014    @Override
6015    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6016            String resolvedType, int flags, int userId) {
6017        return new ParceledListSlice<>(
6018                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6019    }
6020
6021    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6022            Intent intent, String resolvedType, int flags, int userId) {
6023        if (!sUserManager.exists(userId)) return Collections.emptyList();
6024        flags = updateFlagsForResolve(flags, userId, intent);
6025        ComponentName comp = intent.getComponent();
6026        if (comp == null) {
6027            if (intent.getSelector() != null) {
6028                intent = intent.getSelector();
6029                comp = intent.getComponent();
6030            }
6031        }
6032        if (comp != null) {
6033            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6034            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6035            if (pi != null) {
6036                final ResolveInfo ri = new ResolveInfo();
6037                ri.providerInfo = pi;
6038                list.add(ri);
6039            }
6040            return list;
6041        }
6042
6043        // reader
6044        synchronized (mPackages) {
6045            String pkgName = intent.getPackage();
6046            if (pkgName == null) {
6047                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6048            }
6049            final PackageParser.Package pkg = mPackages.get(pkgName);
6050            if (pkg != null) {
6051                return mProviders.queryIntentForPackage(
6052                        intent, resolvedType, flags, pkg.providers, userId);
6053            }
6054            return Collections.emptyList();
6055        }
6056    }
6057
6058    @Override
6059    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6060        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6061        flags = updateFlagsForPackage(flags, userId, null);
6062        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6063        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6064                true /* requireFullPermission */, false /* checkShell */,
6065                "get installed packages");
6066
6067        // writer
6068        synchronized (mPackages) {
6069            ArrayList<PackageInfo> list;
6070            if (listUninstalled) {
6071                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6072                for (PackageSetting ps : mSettings.mPackages.values()) {
6073                    final PackageInfo pi;
6074                    if (ps.pkg != null) {
6075                        pi = generatePackageInfo(ps, flags, userId);
6076                    } else {
6077                        pi = generatePackageInfo(ps, flags, userId);
6078                    }
6079                    if (pi != null) {
6080                        list.add(pi);
6081                    }
6082                }
6083            } else {
6084                list = new ArrayList<PackageInfo>(mPackages.size());
6085                for (PackageParser.Package p : mPackages.values()) {
6086                    final PackageInfo pi =
6087                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6088                    if (pi != null) {
6089                        list.add(pi);
6090                    }
6091                }
6092            }
6093
6094            return new ParceledListSlice<PackageInfo>(list);
6095        }
6096    }
6097
6098    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6099            String[] permissions, boolean[] tmp, int flags, int userId) {
6100        int numMatch = 0;
6101        final PermissionsState permissionsState = ps.getPermissionsState();
6102        for (int i=0; i<permissions.length; i++) {
6103            final String permission = permissions[i];
6104            if (permissionsState.hasPermission(permission, userId)) {
6105                tmp[i] = true;
6106                numMatch++;
6107            } else {
6108                tmp[i] = false;
6109            }
6110        }
6111        if (numMatch == 0) {
6112            return;
6113        }
6114        final PackageInfo pi;
6115        if (ps.pkg != null) {
6116            pi = generatePackageInfo(ps, flags, userId);
6117        } else {
6118            pi = generatePackageInfo(ps, flags, userId);
6119        }
6120        // The above might return null in cases of uninstalled apps or install-state
6121        // skew across users/profiles.
6122        if (pi != null) {
6123            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6124                if (numMatch == permissions.length) {
6125                    pi.requestedPermissions = permissions;
6126                } else {
6127                    pi.requestedPermissions = new String[numMatch];
6128                    numMatch = 0;
6129                    for (int i=0; i<permissions.length; i++) {
6130                        if (tmp[i]) {
6131                            pi.requestedPermissions[numMatch] = permissions[i];
6132                            numMatch++;
6133                        }
6134                    }
6135                }
6136            }
6137            list.add(pi);
6138        }
6139    }
6140
6141    @Override
6142    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6143            String[] permissions, int flags, int userId) {
6144        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6145        flags = updateFlagsForPackage(flags, userId, permissions);
6146        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6147
6148        // writer
6149        synchronized (mPackages) {
6150            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6151            boolean[] tmpBools = new boolean[permissions.length];
6152            if (listUninstalled) {
6153                for (PackageSetting ps : mSettings.mPackages.values()) {
6154                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6155                }
6156            } else {
6157                for (PackageParser.Package pkg : mPackages.values()) {
6158                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6159                    if (ps != null) {
6160                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6161                                userId);
6162                    }
6163                }
6164            }
6165
6166            return new ParceledListSlice<PackageInfo>(list);
6167        }
6168    }
6169
6170    @Override
6171    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6172        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6173        flags = updateFlagsForApplication(flags, userId, null);
6174        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6175
6176        // writer
6177        synchronized (mPackages) {
6178            ArrayList<ApplicationInfo> list;
6179            if (listUninstalled) {
6180                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6181                for (PackageSetting ps : mSettings.mPackages.values()) {
6182                    ApplicationInfo ai;
6183                    if (ps.pkg != null) {
6184                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6185                                ps.readUserState(userId), userId);
6186                    } else {
6187                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6188                    }
6189                    if (ai != null) {
6190                        list.add(ai);
6191                    }
6192                }
6193            } else {
6194                list = new ArrayList<ApplicationInfo>(mPackages.size());
6195                for (PackageParser.Package p : mPackages.values()) {
6196                    if (p.mExtras != null) {
6197                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6198                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6199                        if (ai != null) {
6200                            list.add(ai);
6201                        }
6202                    }
6203                }
6204            }
6205
6206            return new ParceledListSlice<ApplicationInfo>(list);
6207        }
6208    }
6209
6210    @Override
6211    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6212        if (DISABLE_EPHEMERAL_APPS) {
6213            return null;
6214        }
6215
6216        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6217                "getEphemeralApplications");
6218        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6219                true /* requireFullPermission */, false /* checkShell */,
6220                "getEphemeralApplications");
6221        synchronized (mPackages) {
6222            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6223                    .getEphemeralApplicationsLPw(userId);
6224            if (ephemeralApps != null) {
6225                return new ParceledListSlice<>(ephemeralApps);
6226            }
6227        }
6228        return null;
6229    }
6230
6231    @Override
6232    public boolean isEphemeralApplication(String packageName, int userId) {
6233        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6234                true /* requireFullPermission */, false /* checkShell */,
6235                "isEphemeral");
6236        if (DISABLE_EPHEMERAL_APPS) {
6237            return false;
6238        }
6239
6240        if (!isCallerSameApp(packageName)) {
6241            return false;
6242        }
6243        synchronized (mPackages) {
6244            PackageParser.Package pkg = mPackages.get(packageName);
6245            if (pkg != null) {
6246                return pkg.applicationInfo.isEphemeralApp();
6247            }
6248        }
6249        return false;
6250    }
6251
6252    @Override
6253    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6254        if (DISABLE_EPHEMERAL_APPS) {
6255            return null;
6256        }
6257
6258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6259                true /* requireFullPermission */, false /* checkShell */,
6260                "getCookie");
6261        if (!isCallerSameApp(packageName)) {
6262            return null;
6263        }
6264        synchronized (mPackages) {
6265            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6266                    packageName, userId);
6267        }
6268    }
6269
6270    @Override
6271    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6272        if (DISABLE_EPHEMERAL_APPS) {
6273            return true;
6274        }
6275
6276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6277                true /* requireFullPermission */, true /* checkShell */,
6278                "setCookie");
6279        if (!isCallerSameApp(packageName)) {
6280            return false;
6281        }
6282        synchronized (mPackages) {
6283            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6284                    packageName, cookie, userId);
6285        }
6286    }
6287
6288    @Override
6289    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6290        if (DISABLE_EPHEMERAL_APPS) {
6291            return null;
6292        }
6293
6294        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6295                "getEphemeralApplicationIcon");
6296        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6297                true /* requireFullPermission */, false /* checkShell */,
6298                "getEphemeralApplicationIcon");
6299        synchronized (mPackages) {
6300            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6301                    packageName, userId);
6302        }
6303    }
6304
6305    private boolean isCallerSameApp(String packageName) {
6306        PackageParser.Package pkg = mPackages.get(packageName);
6307        return pkg != null
6308                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6309    }
6310
6311    @Override
6312    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6313        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6314    }
6315
6316    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6317        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6318
6319        // reader
6320        synchronized (mPackages) {
6321            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6322            final int userId = UserHandle.getCallingUserId();
6323            while (i.hasNext()) {
6324                final PackageParser.Package p = i.next();
6325                if (p.applicationInfo == null) continue;
6326
6327                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6328                        && !p.applicationInfo.isDirectBootAware();
6329                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6330                        && p.applicationInfo.isDirectBootAware();
6331
6332                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6333                        && (!mSafeMode || isSystemApp(p))
6334                        && (matchesUnaware || matchesAware)) {
6335                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6336                    if (ps != null) {
6337                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6338                                ps.readUserState(userId), userId);
6339                        if (ai != null) {
6340                            finalList.add(ai);
6341                        }
6342                    }
6343                }
6344            }
6345        }
6346
6347        return finalList;
6348    }
6349
6350    @Override
6351    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6352        if (!sUserManager.exists(userId)) return null;
6353        flags = updateFlagsForComponent(flags, userId, name);
6354        // reader
6355        synchronized (mPackages) {
6356            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6357            PackageSetting ps = provider != null
6358                    ? mSettings.mPackages.get(provider.owner.packageName)
6359                    : null;
6360            return ps != null
6361                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6362                    ? PackageParser.generateProviderInfo(provider, flags,
6363                            ps.readUserState(userId), userId)
6364                    : null;
6365        }
6366    }
6367
6368    /**
6369     * @deprecated
6370     */
6371    @Deprecated
6372    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6373        // reader
6374        synchronized (mPackages) {
6375            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6376                    .entrySet().iterator();
6377            final int userId = UserHandle.getCallingUserId();
6378            while (i.hasNext()) {
6379                Map.Entry<String, PackageParser.Provider> entry = i.next();
6380                PackageParser.Provider p = entry.getValue();
6381                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6382
6383                if (ps != null && p.syncable
6384                        && (!mSafeMode || (p.info.applicationInfo.flags
6385                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6386                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6387                            ps.readUserState(userId), userId);
6388                    if (info != null) {
6389                        outNames.add(entry.getKey());
6390                        outInfo.add(info);
6391                    }
6392                }
6393            }
6394        }
6395    }
6396
6397    @Override
6398    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6399            int uid, int flags) {
6400        final int userId = processName != null ? UserHandle.getUserId(uid)
6401                : UserHandle.getCallingUserId();
6402        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6403        flags = updateFlagsForComponent(flags, userId, processName);
6404
6405        ArrayList<ProviderInfo> finalList = null;
6406        // reader
6407        synchronized (mPackages) {
6408            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6409            while (i.hasNext()) {
6410                final PackageParser.Provider p = i.next();
6411                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6412                if (ps != null && p.info.authority != null
6413                        && (processName == null
6414                                || (p.info.processName.equals(processName)
6415                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6416                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6417                    if (finalList == null) {
6418                        finalList = new ArrayList<ProviderInfo>(3);
6419                    }
6420                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6421                            ps.readUserState(userId), userId);
6422                    if (info != null) {
6423                        finalList.add(info);
6424                    }
6425                }
6426            }
6427        }
6428
6429        if (finalList != null) {
6430            Collections.sort(finalList, mProviderInitOrderSorter);
6431            return new ParceledListSlice<ProviderInfo>(finalList);
6432        }
6433
6434        return ParceledListSlice.emptyList();
6435    }
6436
6437    @Override
6438    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6439        // reader
6440        synchronized (mPackages) {
6441            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6442            return PackageParser.generateInstrumentationInfo(i, flags);
6443        }
6444    }
6445
6446    @Override
6447    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6448            String targetPackage, int flags) {
6449        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6450    }
6451
6452    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6453            int flags) {
6454        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6455
6456        // reader
6457        synchronized (mPackages) {
6458            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6459            while (i.hasNext()) {
6460                final PackageParser.Instrumentation p = i.next();
6461                if (targetPackage == null
6462                        || targetPackage.equals(p.info.targetPackage)) {
6463                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6464                            flags);
6465                    if (ii != null) {
6466                        finalList.add(ii);
6467                    }
6468                }
6469            }
6470        }
6471
6472        return finalList;
6473    }
6474
6475    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6476        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6477        if (overlays == null) {
6478            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6479            return;
6480        }
6481        for (PackageParser.Package opkg : overlays.values()) {
6482            // Not much to do if idmap fails: we already logged the error
6483            // and we certainly don't want to abort installation of pkg simply
6484            // because an overlay didn't fit properly. For these reasons,
6485            // ignore the return value of createIdmapForPackagePairLI.
6486            createIdmapForPackagePairLI(pkg, opkg);
6487        }
6488    }
6489
6490    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6491            PackageParser.Package opkg) {
6492        if (!opkg.mTrustedOverlay) {
6493            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6494                    opkg.baseCodePath + ": overlay not trusted");
6495            return false;
6496        }
6497        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6498        if (overlaySet == null) {
6499            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6500                    opkg.baseCodePath + " but target package has no known overlays");
6501            return false;
6502        }
6503        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6504        // TODO: generate idmap for split APKs
6505        try {
6506            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6507        } catch (InstallerException e) {
6508            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6509                    + opkg.baseCodePath);
6510            return false;
6511        }
6512        PackageParser.Package[] overlayArray =
6513            overlaySet.values().toArray(new PackageParser.Package[0]);
6514        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6515            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6516                return p1.mOverlayPriority - p2.mOverlayPriority;
6517            }
6518        };
6519        Arrays.sort(overlayArray, cmp);
6520
6521        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6522        int i = 0;
6523        for (PackageParser.Package p : overlayArray) {
6524            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6525        }
6526        return true;
6527    }
6528
6529    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6530        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6531        try {
6532            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6533        } finally {
6534            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6535        }
6536    }
6537
6538    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6539        final File[] files = dir.listFiles();
6540        if (ArrayUtils.isEmpty(files)) {
6541            Log.d(TAG, "No files in app dir " + dir);
6542            return;
6543        }
6544
6545        if (DEBUG_PACKAGE_SCANNING) {
6546            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6547                    + " flags=0x" + Integer.toHexString(parseFlags));
6548        }
6549
6550        for (File file : files) {
6551            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6552                    && !PackageInstallerService.isStageName(file.getName());
6553            if (!isPackage) {
6554                // Ignore entries which are not packages
6555                continue;
6556            }
6557            try {
6558                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6559                        scanFlags, currentTime, null);
6560            } catch (PackageManagerException e) {
6561                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6562
6563                // Delete invalid userdata apps
6564                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6565                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6566                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6567                    removeCodePathLI(file);
6568                }
6569            }
6570        }
6571    }
6572
6573    private static File getSettingsProblemFile() {
6574        File dataDir = Environment.getDataDirectory();
6575        File systemDir = new File(dataDir, "system");
6576        File fname = new File(systemDir, "uiderrors.txt");
6577        return fname;
6578    }
6579
6580    static void reportSettingsProblem(int priority, String msg) {
6581        logCriticalInfo(priority, msg);
6582    }
6583
6584    static void logCriticalInfo(int priority, String msg) {
6585        Slog.println(priority, TAG, msg);
6586        EventLogTags.writePmCriticalInfo(msg);
6587        try {
6588            File fname = getSettingsProblemFile();
6589            FileOutputStream out = new FileOutputStream(fname, true);
6590            PrintWriter pw = new FastPrintWriter(out);
6591            SimpleDateFormat formatter = new SimpleDateFormat();
6592            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6593            pw.println(dateString + ": " + msg);
6594            pw.close();
6595            FileUtils.setPermissions(
6596                    fname.toString(),
6597                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6598                    -1, -1);
6599        } catch (java.io.IOException e) {
6600        }
6601    }
6602
6603    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6604            final int policyFlags) throws PackageManagerException {
6605        if (ps != null
6606                && ps.codePath.equals(srcFile)
6607                && ps.timeStamp == srcFile.lastModified()
6608                && !isCompatSignatureUpdateNeeded(pkg)
6609                && !isRecoverSignatureUpdateNeeded(pkg)) {
6610            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6611            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6612            ArraySet<PublicKey> signingKs;
6613            synchronized (mPackages) {
6614                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6615            }
6616            if (ps.signatures.mSignatures != null
6617                    && ps.signatures.mSignatures.length != 0
6618                    && signingKs != null) {
6619                // Optimization: reuse the existing cached certificates
6620                // if the package appears to be unchanged.
6621                pkg.mSignatures = ps.signatures.mSignatures;
6622                pkg.mSigningKeys = signingKs;
6623                return;
6624            }
6625
6626            Slog.w(TAG, "PackageSetting for " + ps.name
6627                    + " is missing signatures.  Collecting certs again to recover them.");
6628        } else {
6629            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6630        }
6631
6632        try {
6633            PackageParser.collectCertificates(pkg, policyFlags);
6634        } catch (PackageParserException e) {
6635            throw PackageManagerException.from(e);
6636        }
6637    }
6638
6639    /**
6640     *  Traces a package scan.
6641     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6642     */
6643    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6644            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6645        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6646        try {
6647            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6648        } finally {
6649            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6650        }
6651    }
6652
6653    /**
6654     *  Scans a package and returns the newly parsed package.
6655     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6656     */
6657    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6658            long currentTime, UserHandle user) throws PackageManagerException {
6659        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6660        PackageParser pp = new PackageParser();
6661        pp.setSeparateProcesses(mSeparateProcesses);
6662        pp.setOnlyCoreApps(mOnlyCore);
6663        pp.setDisplayMetrics(mMetrics);
6664
6665        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6666            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6667        }
6668
6669        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6670        final PackageParser.Package pkg;
6671        try {
6672            pkg = pp.parsePackage(scanFile, parseFlags);
6673        } catch (PackageParserException e) {
6674            throw PackageManagerException.from(e);
6675        } finally {
6676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6677        }
6678
6679        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6680    }
6681
6682    /**
6683     *  Scans a package and returns the newly parsed package.
6684     *  @throws PackageManagerException on a parse error.
6685     */
6686    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6687            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6688            throws PackageManagerException {
6689        // If the package has children and this is the first dive in the function
6690        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6691        // packages (parent and children) would be successfully scanned before the
6692        // actual scan since scanning mutates internal state and we want to atomically
6693        // install the package and its children.
6694        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6695            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6696                scanFlags |= SCAN_CHECK_ONLY;
6697            }
6698        } else {
6699            scanFlags &= ~SCAN_CHECK_ONLY;
6700        }
6701
6702        // Scan the parent
6703        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6704                scanFlags, currentTime, user);
6705
6706        // Scan the children
6707        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6708        for (int i = 0; i < childCount; i++) {
6709            PackageParser.Package childPackage = pkg.childPackages.get(i);
6710            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6711                    currentTime, user);
6712        }
6713
6714
6715        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6716            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6717        }
6718
6719        return scannedPkg;
6720    }
6721
6722    /**
6723     *  Scans a package and returns the newly parsed package.
6724     *  @throws PackageManagerException on a parse error.
6725     */
6726    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6727            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6728            throws PackageManagerException {
6729        PackageSetting ps = null;
6730        PackageSetting updatedPkg;
6731        // reader
6732        synchronized (mPackages) {
6733            // Look to see if we already know about this package.
6734            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6735            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6736                // This package has been renamed to its original name.  Let's
6737                // use that.
6738                ps = mSettings.peekPackageLPr(oldName);
6739            }
6740            // If there was no original package, see one for the real package name.
6741            if (ps == null) {
6742                ps = mSettings.peekPackageLPr(pkg.packageName);
6743            }
6744            // Check to see if this package could be hiding/updating a system
6745            // package.  Must look for it either under the original or real
6746            // package name depending on our state.
6747            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6748            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6749
6750            // If this is a package we don't know about on the system partition, we
6751            // may need to remove disabled child packages on the system partition
6752            // or may need to not add child packages if the parent apk is updated
6753            // on the data partition and no longer defines this child package.
6754            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6755                // If this is a parent package for an updated system app and this system
6756                // app got an OTA update which no longer defines some of the child packages
6757                // we have to prune them from the disabled system packages.
6758                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6759                if (disabledPs != null) {
6760                    final int scannedChildCount = (pkg.childPackages != null)
6761                            ? pkg.childPackages.size() : 0;
6762                    final int disabledChildCount = disabledPs.childPackageNames != null
6763                            ? disabledPs.childPackageNames.size() : 0;
6764                    for (int i = 0; i < disabledChildCount; i++) {
6765                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6766                        boolean disabledPackageAvailable = false;
6767                        for (int j = 0; j < scannedChildCount; j++) {
6768                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6769                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6770                                disabledPackageAvailable = true;
6771                                break;
6772                            }
6773                         }
6774                         if (!disabledPackageAvailable) {
6775                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6776                         }
6777                    }
6778                }
6779            }
6780        }
6781
6782        boolean updatedPkgBetter = false;
6783        // First check if this is a system package that may involve an update
6784        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6785            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6786            // it needs to drop FLAG_PRIVILEGED.
6787            if (locationIsPrivileged(scanFile)) {
6788                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6789            } else {
6790                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6791            }
6792
6793            if (ps != null && !ps.codePath.equals(scanFile)) {
6794                // The path has changed from what was last scanned...  check the
6795                // version of the new path against what we have stored to determine
6796                // what to do.
6797                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6798                if (pkg.mVersionCode <= ps.versionCode) {
6799                    // The system package has been updated and the code path does not match
6800                    // Ignore entry. Skip it.
6801                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6802                            + " ignored: updated version " + ps.versionCode
6803                            + " better than this " + pkg.mVersionCode);
6804                    if (!updatedPkg.codePath.equals(scanFile)) {
6805                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6806                                + ps.name + " changing from " + updatedPkg.codePathString
6807                                + " to " + scanFile);
6808                        updatedPkg.codePath = scanFile;
6809                        updatedPkg.codePathString = scanFile.toString();
6810                        updatedPkg.resourcePath = scanFile;
6811                        updatedPkg.resourcePathString = scanFile.toString();
6812                    }
6813                    updatedPkg.pkg = pkg;
6814                    updatedPkg.versionCode = pkg.mVersionCode;
6815
6816                    // Update the disabled system child packages to point to the package too.
6817                    final int childCount = updatedPkg.childPackageNames != null
6818                            ? updatedPkg.childPackageNames.size() : 0;
6819                    for (int i = 0; i < childCount; i++) {
6820                        String childPackageName = updatedPkg.childPackageNames.get(i);
6821                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6822                                childPackageName);
6823                        if (updatedChildPkg != null) {
6824                            updatedChildPkg.pkg = pkg;
6825                            updatedChildPkg.versionCode = pkg.mVersionCode;
6826                        }
6827                    }
6828
6829                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6830                            + scanFile + " ignored: updated version " + ps.versionCode
6831                            + " better than this " + pkg.mVersionCode);
6832                } else {
6833                    // The current app on the system partition is better than
6834                    // what we have updated to on the data partition; switch
6835                    // back to the system partition version.
6836                    // At this point, its safely assumed that package installation for
6837                    // apps in system partition will go through. If not there won't be a working
6838                    // version of the app
6839                    // writer
6840                    synchronized (mPackages) {
6841                        // Just remove the loaded entries from package lists.
6842                        mPackages.remove(ps.name);
6843                    }
6844
6845                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6846                            + " reverting from " + ps.codePathString
6847                            + ": new version " + pkg.mVersionCode
6848                            + " better than installed " + ps.versionCode);
6849
6850                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6851                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6852                    synchronized (mInstallLock) {
6853                        args.cleanUpResourcesLI();
6854                    }
6855                    synchronized (mPackages) {
6856                        mSettings.enableSystemPackageLPw(ps.name);
6857                    }
6858                    updatedPkgBetter = true;
6859                }
6860            }
6861        }
6862
6863        if (updatedPkg != null) {
6864            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6865            // initially
6866            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6867
6868            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6869            // flag set initially
6870            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6871                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6872            }
6873        }
6874
6875        // Verify certificates against what was last scanned
6876        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6877
6878        /*
6879         * A new system app appeared, but we already had a non-system one of the
6880         * same name installed earlier.
6881         */
6882        boolean shouldHideSystemApp = false;
6883        if (updatedPkg == null && ps != null
6884                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6885            /*
6886             * Check to make sure the signatures match first. If they don't,
6887             * wipe the installed application and its data.
6888             */
6889            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6890                    != PackageManager.SIGNATURE_MATCH) {
6891                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6892                        + " signatures don't match existing userdata copy; removing");
6893                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6894                        "scanPackageInternalLI")) {
6895                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6896                }
6897                ps = null;
6898            } else {
6899                /*
6900                 * If the newly-added system app is an older version than the
6901                 * already installed version, hide it. It will be scanned later
6902                 * and re-added like an update.
6903                 */
6904                if (pkg.mVersionCode <= ps.versionCode) {
6905                    shouldHideSystemApp = true;
6906                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6907                            + " but new version " + pkg.mVersionCode + " better than installed "
6908                            + ps.versionCode + "; hiding system");
6909                } else {
6910                    /*
6911                     * The newly found system app is a newer version that the
6912                     * one previously installed. Simply remove the
6913                     * already-installed application and replace it with our own
6914                     * while keeping the application data.
6915                     */
6916                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6917                            + " reverting from " + ps.codePathString + ": new version "
6918                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6919                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6920                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6921                    synchronized (mInstallLock) {
6922                        args.cleanUpResourcesLI();
6923                    }
6924                }
6925            }
6926        }
6927
6928        // The apk is forward locked (not public) if its code and resources
6929        // are kept in different files. (except for app in either system or
6930        // vendor path).
6931        // TODO grab this value from PackageSettings
6932        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6933            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6934                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6935            }
6936        }
6937
6938        // TODO: extend to support forward-locked splits
6939        String resourcePath = null;
6940        String baseResourcePath = null;
6941        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6942            if (ps != null && ps.resourcePathString != null) {
6943                resourcePath = ps.resourcePathString;
6944                baseResourcePath = ps.resourcePathString;
6945            } else {
6946                // Should not happen at all. Just log an error.
6947                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6948            }
6949        } else {
6950            resourcePath = pkg.codePath;
6951            baseResourcePath = pkg.baseCodePath;
6952        }
6953
6954        // Set application objects path explicitly.
6955        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6956        pkg.setApplicationInfoCodePath(pkg.codePath);
6957        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6958        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6959        pkg.setApplicationInfoResourcePath(resourcePath);
6960        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6961        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6962
6963        // Note that we invoke the following method only if we are about to unpack an application
6964        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6965                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6966
6967        /*
6968         * If the system app should be overridden by a previously installed
6969         * data, hide the system app now and let the /data/app scan pick it up
6970         * again.
6971         */
6972        if (shouldHideSystemApp) {
6973            synchronized (mPackages) {
6974                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6975            }
6976        }
6977
6978        return scannedPkg;
6979    }
6980
6981    private static String fixProcessName(String defProcessName,
6982            String processName, int uid) {
6983        if (processName == null) {
6984            return defProcessName;
6985        }
6986        return processName;
6987    }
6988
6989    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6990            throws PackageManagerException {
6991        if (pkgSetting.signatures.mSignatures != null) {
6992            // Already existing package. Make sure signatures match
6993            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6994                    == PackageManager.SIGNATURE_MATCH;
6995            if (!match) {
6996                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6997                        == PackageManager.SIGNATURE_MATCH;
6998            }
6999            if (!match) {
7000                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7001                        == PackageManager.SIGNATURE_MATCH;
7002            }
7003            if (!match) {
7004                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7005                        + pkg.packageName + " signatures do not match the "
7006                        + "previously installed version; ignoring!");
7007            }
7008        }
7009
7010        // Check for shared user signatures
7011        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7012            // Already existing package. Make sure signatures match
7013            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7014                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7015            if (!match) {
7016                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7017                        == PackageManager.SIGNATURE_MATCH;
7018            }
7019            if (!match) {
7020                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7021                        == PackageManager.SIGNATURE_MATCH;
7022            }
7023            if (!match) {
7024                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7025                        "Package " + pkg.packageName
7026                        + " has no signatures that match those in shared user "
7027                        + pkgSetting.sharedUser.name + "; ignoring!");
7028            }
7029        }
7030    }
7031
7032    /**
7033     * Enforces that only the system UID or root's UID can call a method exposed
7034     * via Binder.
7035     *
7036     * @param message used as message if SecurityException is thrown
7037     * @throws SecurityException if the caller is not system or root
7038     */
7039    private static final void enforceSystemOrRoot(String message) {
7040        final int uid = Binder.getCallingUid();
7041        if (uid != Process.SYSTEM_UID && uid != 0) {
7042            throw new SecurityException(message);
7043        }
7044    }
7045
7046    @Override
7047    public void performFstrimIfNeeded() {
7048        enforceSystemOrRoot("Only the system can request fstrim");
7049
7050        // Before everything else, see whether we need to fstrim.
7051        try {
7052            IMountService ms = PackageHelper.getMountService();
7053            if (ms != null) {
7054                final boolean isUpgrade = isUpgrade();
7055                boolean doTrim = isUpgrade;
7056                if (doTrim) {
7057                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7058                } else {
7059                    final long interval = android.provider.Settings.Global.getLong(
7060                            mContext.getContentResolver(),
7061                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7062                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7063                    if (interval > 0) {
7064                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7065                        if (timeSinceLast > interval) {
7066                            doTrim = true;
7067                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7068                                    + "; running immediately");
7069                        }
7070                    }
7071                }
7072                if (doTrim) {
7073                    if (!isFirstBoot()) {
7074                        try {
7075                            ActivityManagerNative.getDefault().showBootMessage(
7076                                    mContext.getResources().getString(
7077                                            R.string.android_upgrading_fstrim), true);
7078                        } catch (RemoteException e) {
7079                        }
7080                    }
7081                    ms.runMaintenance();
7082                }
7083            } else {
7084                Slog.e(TAG, "Mount service unavailable!");
7085            }
7086        } catch (RemoteException e) {
7087            // Can't happen; MountService is local
7088        }
7089    }
7090
7091    @Override
7092    public void updatePackagesIfNeeded() {
7093        enforceSystemOrRoot("Only the system can request package update");
7094
7095        // We need to re-extract after an OTA.
7096        boolean causeUpgrade = isUpgrade();
7097
7098        // First boot or factory reset.
7099        // Note: we also handle devices that are upgrading to N right now as if it is their
7100        //       first boot, as they do not have profile data.
7101        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7102
7103        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7104        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7105
7106        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7107            return;
7108        }
7109
7110        List<PackageParser.Package> pkgs;
7111        synchronized (mPackages) {
7112            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7113        }
7114
7115        final long startTime = System.nanoTime();
7116        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7117                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7118
7119        final int elapsedTimeSeconds =
7120                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7121
7122        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7123        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7124        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7125        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7126        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7127    }
7128
7129    /**
7130     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7131     * containing statistics about the invocation. The array consists of three elements,
7132     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7133     * and {@code numberOfPackagesFailed}.
7134     */
7135    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7136            String compilerFilter) {
7137
7138        int numberOfPackagesVisited = 0;
7139        int numberOfPackagesOptimized = 0;
7140        int numberOfPackagesSkipped = 0;
7141        int numberOfPackagesFailed = 0;
7142        final int numberOfPackagesToDexopt = pkgs.size();
7143
7144        for (PackageParser.Package pkg : pkgs) {
7145            numberOfPackagesVisited++;
7146
7147            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7148                if (DEBUG_DEXOPT) {
7149                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7150                }
7151                numberOfPackagesSkipped++;
7152                continue;
7153            }
7154
7155            if (DEBUG_DEXOPT) {
7156                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7157                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7158            }
7159
7160            if (showDialog) {
7161                try {
7162                    ActivityManagerNative.getDefault().showBootMessage(
7163                            mContext.getResources().getString(R.string.android_upgrading_apk,
7164                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7165                } catch (RemoteException e) {
7166                }
7167            }
7168
7169            // If the OTA updates a system app which was previously preopted to a non-preopted state
7170            // the app might end up being verified at runtime. That's because by default the apps
7171            // are verify-profile but for preopted apps there's no profile.
7172            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7173            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7174            // filter (by default interpret-only).
7175            // Note that at this stage unused apps are already filtered.
7176            if (isSystemApp(pkg) &&
7177                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7178                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7179                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7180            }
7181
7182            // checkProfiles is false to avoid merging profiles during boot which
7183            // might interfere with background compilation (b/28612421).
7184            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7185            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7186            // trade-off worth doing to save boot time work.
7187            int dexOptStatus = performDexOptTraced(pkg.packageName,
7188                    false /* checkProfiles */,
7189                    compilerFilter,
7190                    false /* force */);
7191            switch (dexOptStatus) {
7192                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7193                    numberOfPackagesOptimized++;
7194                    break;
7195                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7196                    numberOfPackagesSkipped++;
7197                    break;
7198                case PackageDexOptimizer.DEX_OPT_FAILED:
7199                    numberOfPackagesFailed++;
7200                    break;
7201                default:
7202                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7203                    break;
7204            }
7205        }
7206
7207        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7208                numberOfPackagesFailed };
7209    }
7210
7211    @Override
7212    public void notifyPackageUse(String packageName, int reason) {
7213        synchronized (mPackages) {
7214            PackageParser.Package p = mPackages.get(packageName);
7215            if (p == null) {
7216                return;
7217            }
7218            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7219        }
7220    }
7221
7222    // TODO: this is not used nor needed. Delete it.
7223    @Override
7224    public boolean performDexOptIfNeeded(String packageName) {
7225        int dexOptStatus = performDexOptTraced(packageName,
7226                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7227        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7228    }
7229
7230    @Override
7231    public boolean performDexOpt(String packageName,
7232            boolean checkProfiles, int compileReason, boolean force) {
7233        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7234                getCompilerFilterForReason(compileReason), force);
7235        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7236    }
7237
7238    @Override
7239    public boolean performDexOptMode(String packageName,
7240            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7241        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7242                targetCompilerFilter, force);
7243        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7244    }
7245
7246    private int performDexOptTraced(String packageName,
7247                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7248        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7249        try {
7250            return performDexOptInternal(packageName, checkProfiles,
7251                    targetCompilerFilter, force);
7252        } finally {
7253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7254        }
7255    }
7256
7257    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7258    // if the package can now be considered up to date for the given filter.
7259    private int performDexOptInternal(String packageName,
7260                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7261        PackageParser.Package p;
7262        synchronized (mPackages) {
7263            p = mPackages.get(packageName);
7264            if (p == null) {
7265                // Package could not be found. Report failure.
7266                return PackageDexOptimizer.DEX_OPT_FAILED;
7267            }
7268            mPackageUsage.maybeWriteAsync(mPackages);
7269            mCompilerStats.maybeWriteAsync();
7270        }
7271        long callingId = Binder.clearCallingIdentity();
7272        try {
7273            synchronized (mInstallLock) {
7274                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7275                        targetCompilerFilter, force);
7276            }
7277        } finally {
7278            Binder.restoreCallingIdentity(callingId);
7279        }
7280    }
7281
7282    public ArraySet<String> getOptimizablePackages() {
7283        ArraySet<String> pkgs = new ArraySet<String>();
7284        synchronized (mPackages) {
7285            for (PackageParser.Package p : mPackages.values()) {
7286                if (PackageDexOptimizer.canOptimizePackage(p)) {
7287                    pkgs.add(p.packageName);
7288                }
7289            }
7290        }
7291        return pkgs;
7292    }
7293
7294    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7295            boolean checkProfiles, String targetCompilerFilter,
7296            boolean force) {
7297        // Select the dex optimizer based on the force parameter.
7298        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7299        //       allocate an object here.
7300        PackageDexOptimizer pdo = force
7301                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7302                : mPackageDexOptimizer;
7303
7304        // Optimize all dependencies first. Note: we ignore the return value and march on
7305        // on errors.
7306        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7307        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7308        if (!deps.isEmpty()) {
7309            for (PackageParser.Package depPackage : deps) {
7310                // TODO: Analyze and investigate if we (should) profile libraries.
7311                // Currently this will do a full compilation of the library by default.
7312                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7313                        false /* checkProfiles */,
7314                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7315                        getOrCreateCompilerPackageStats(depPackage));
7316            }
7317        }
7318        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7319                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7320    }
7321
7322    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7323        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7324            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7325            Set<String> collectedNames = new HashSet<>();
7326            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7327
7328            retValue.remove(p);
7329
7330            return retValue;
7331        } else {
7332            return Collections.emptyList();
7333        }
7334    }
7335
7336    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7337            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7338        if (!collectedNames.contains(p.packageName)) {
7339            collectedNames.add(p.packageName);
7340            collected.add(p);
7341
7342            if (p.usesLibraries != null) {
7343                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7344            }
7345            if (p.usesOptionalLibraries != null) {
7346                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7347                        collectedNames);
7348            }
7349        }
7350    }
7351
7352    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7353            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7354        for (String libName : libs) {
7355            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7356            if (libPkg != null) {
7357                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7358            }
7359        }
7360    }
7361
7362    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7363        synchronized (mPackages) {
7364            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7365            if (lib != null && lib.apk != null) {
7366                return mPackages.get(lib.apk);
7367            }
7368        }
7369        return null;
7370    }
7371
7372    public void shutdown() {
7373        mPackageUsage.writeNow(mPackages);
7374        mCompilerStats.writeNow();
7375    }
7376
7377    @Override
7378    public void dumpProfiles(String packageName) {
7379        PackageParser.Package pkg;
7380        synchronized (mPackages) {
7381            pkg = mPackages.get(packageName);
7382            if (pkg == null) {
7383                throw new IllegalArgumentException("Unknown package: " + packageName);
7384            }
7385        }
7386        /* Only the shell, root, or the app user should be able to dump profiles. */
7387        int callingUid = Binder.getCallingUid();
7388        if (callingUid != Process.SHELL_UID &&
7389            callingUid != Process.ROOT_UID &&
7390            callingUid != pkg.applicationInfo.uid) {
7391            throw new SecurityException("dumpProfiles");
7392        }
7393
7394        synchronized (mInstallLock) {
7395            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7396            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7397            try {
7398                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7399                String gid = Integer.toString(sharedGid);
7400                String codePaths = TextUtils.join(";", allCodePaths);
7401                mInstaller.dumpProfiles(gid, packageName, codePaths);
7402            } catch (InstallerException e) {
7403                Slog.w(TAG, "Failed to dump profiles", e);
7404            }
7405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7406        }
7407    }
7408
7409    @Override
7410    public void forceDexOpt(String packageName) {
7411        enforceSystemOrRoot("forceDexOpt");
7412
7413        PackageParser.Package pkg;
7414        synchronized (mPackages) {
7415            pkg = mPackages.get(packageName);
7416            if (pkg == null) {
7417                throw new IllegalArgumentException("Unknown package: " + packageName);
7418            }
7419        }
7420
7421        synchronized (mInstallLock) {
7422            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7423
7424            // Whoever is calling forceDexOpt wants a fully compiled package.
7425            // Don't use profiles since that may cause compilation to be skipped.
7426            final int res = performDexOptInternalWithDependenciesLI(pkg,
7427                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7428                    true /* force */);
7429
7430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7431            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7432                throw new IllegalStateException("Failed to dexopt: " + res);
7433            }
7434        }
7435    }
7436
7437    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7438        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7439            Slog.w(TAG, "Unable to update from " + oldPkg.name
7440                    + " to " + newPkg.packageName
7441                    + ": old package not in system partition");
7442            return false;
7443        } else if (mPackages.get(oldPkg.name) != null) {
7444            Slog.w(TAG, "Unable to update from " + oldPkg.name
7445                    + " to " + newPkg.packageName
7446                    + ": old package still exists");
7447            return false;
7448        }
7449        return true;
7450    }
7451
7452    void removeCodePathLI(File codePath) {
7453        if (codePath.isDirectory()) {
7454            try {
7455                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7456            } catch (InstallerException e) {
7457                Slog.w(TAG, "Failed to remove code path", e);
7458            }
7459        } else {
7460            codePath.delete();
7461        }
7462    }
7463
7464    private int[] resolveUserIds(int userId) {
7465        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7466    }
7467
7468    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7469        if (pkg == null) {
7470            Slog.wtf(TAG, "Package was null!", new Throwable());
7471            return;
7472        }
7473        clearAppDataLeafLIF(pkg, userId, flags);
7474        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7475        for (int i = 0; i < childCount; i++) {
7476            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7477        }
7478    }
7479
7480    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7481        final PackageSetting ps;
7482        synchronized (mPackages) {
7483            ps = mSettings.mPackages.get(pkg.packageName);
7484        }
7485        for (int realUserId : resolveUserIds(userId)) {
7486            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7487            try {
7488                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7489                        ceDataInode);
7490            } catch (InstallerException e) {
7491                Slog.w(TAG, String.valueOf(e));
7492            }
7493        }
7494    }
7495
7496    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7497        if (pkg == null) {
7498            Slog.wtf(TAG, "Package was null!", new Throwable());
7499            return;
7500        }
7501        destroyAppDataLeafLIF(pkg, userId, flags);
7502        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7503        for (int i = 0; i < childCount; i++) {
7504            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7505        }
7506    }
7507
7508    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7509        final PackageSetting ps;
7510        synchronized (mPackages) {
7511            ps = mSettings.mPackages.get(pkg.packageName);
7512        }
7513        for (int realUserId : resolveUserIds(userId)) {
7514            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7515            try {
7516                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7517                        ceDataInode);
7518            } catch (InstallerException e) {
7519                Slog.w(TAG, String.valueOf(e));
7520            }
7521        }
7522    }
7523
7524    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7525        if (pkg == null) {
7526            Slog.wtf(TAG, "Package was null!", new Throwable());
7527            return;
7528        }
7529        destroyAppProfilesLeafLIF(pkg);
7530        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7531        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7532        for (int i = 0; i < childCount; i++) {
7533            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7534            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7535                    true /* removeBaseMarker */);
7536        }
7537    }
7538
7539    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7540            boolean removeBaseMarker) {
7541        if (pkg.isForwardLocked()) {
7542            return;
7543        }
7544
7545        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7546            try {
7547                path = PackageManagerServiceUtils.realpath(new File(path));
7548            } catch (IOException e) {
7549                // TODO: Should we return early here ?
7550                Slog.w(TAG, "Failed to get canonical path", e);
7551                continue;
7552            }
7553
7554            final String useMarker = path.replace('/', '@');
7555            for (int realUserId : resolveUserIds(userId)) {
7556                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7557                if (removeBaseMarker) {
7558                    File foreignUseMark = new File(profileDir, useMarker);
7559                    if (foreignUseMark.exists()) {
7560                        if (!foreignUseMark.delete()) {
7561                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7562                                    + pkg.packageName);
7563                        }
7564                    }
7565                }
7566
7567                File[] markers = profileDir.listFiles();
7568                if (markers != null) {
7569                    final String searchString = "@" + pkg.packageName + "@";
7570                    // We also delete all markers that contain the package name we're
7571                    // uninstalling. These are associated with secondary dex-files belonging
7572                    // to the package. Reconstructing the path of these dex files is messy
7573                    // in general.
7574                    for (File marker : markers) {
7575                        if (marker.getName().indexOf(searchString) > 0) {
7576                            if (!marker.delete()) {
7577                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7578                                    + pkg.packageName);
7579                            }
7580                        }
7581                    }
7582                }
7583            }
7584        }
7585    }
7586
7587    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7588        try {
7589            mInstaller.destroyAppProfiles(pkg.packageName);
7590        } catch (InstallerException e) {
7591            Slog.w(TAG, String.valueOf(e));
7592        }
7593    }
7594
7595    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7596        if (pkg == null) {
7597            Slog.wtf(TAG, "Package was null!", new Throwable());
7598            return;
7599        }
7600        clearAppProfilesLeafLIF(pkg);
7601        // We don't remove the base foreign use marker when clearing profiles because
7602        // we will rename it when the app is updated. Unlike the actual profile contents,
7603        // the foreign use marker is good across installs.
7604        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7606        for (int i = 0; i < childCount; i++) {
7607            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7608        }
7609    }
7610
7611    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7612        try {
7613            mInstaller.clearAppProfiles(pkg.packageName);
7614        } catch (InstallerException e) {
7615            Slog.w(TAG, String.valueOf(e));
7616        }
7617    }
7618
7619    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7620            long lastUpdateTime) {
7621        // Set parent install/update time
7622        PackageSetting ps = (PackageSetting) pkg.mExtras;
7623        if (ps != null) {
7624            ps.firstInstallTime = firstInstallTime;
7625            ps.lastUpdateTime = lastUpdateTime;
7626        }
7627        // Set children install/update time
7628        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7629        for (int i = 0; i < childCount; i++) {
7630            PackageParser.Package childPkg = pkg.childPackages.get(i);
7631            ps = (PackageSetting) childPkg.mExtras;
7632            if (ps != null) {
7633                ps.firstInstallTime = firstInstallTime;
7634                ps.lastUpdateTime = lastUpdateTime;
7635            }
7636        }
7637    }
7638
7639    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7640            PackageParser.Package changingLib) {
7641        if (file.path != null) {
7642            usesLibraryFiles.add(file.path);
7643            return;
7644        }
7645        PackageParser.Package p = mPackages.get(file.apk);
7646        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7647            // If we are doing this while in the middle of updating a library apk,
7648            // then we need to make sure to use that new apk for determining the
7649            // dependencies here.  (We haven't yet finished committing the new apk
7650            // to the package manager state.)
7651            if (p == null || p.packageName.equals(changingLib.packageName)) {
7652                p = changingLib;
7653            }
7654        }
7655        if (p != null) {
7656            usesLibraryFiles.addAll(p.getAllCodePaths());
7657        }
7658    }
7659
7660    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7661            PackageParser.Package changingLib) throws PackageManagerException {
7662        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7663            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7664            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7665            for (int i=0; i<N; i++) {
7666                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7667                if (file == null) {
7668                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7669                            "Package " + pkg.packageName + " requires unavailable shared library "
7670                            + pkg.usesLibraries.get(i) + "; failing!");
7671                }
7672                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7673            }
7674            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7675            for (int i=0; i<N; i++) {
7676                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7677                if (file == null) {
7678                    Slog.w(TAG, "Package " + pkg.packageName
7679                            + " desires unavailable shared library "
7680                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7681                } else {
7682                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7683                }
7684            }
7685            N = usesLibraryFiles.size();
7686            if (N > 0) {
7687                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7688            } else {
7689                pkg.usesLibraryFiles = null;
7690            }
7691        }
7692    }
7693
7694    private static boolean hasString(List<String> list, List<String> which) {
7695        if (list == null) {
7696            return false;
7697        }
7698        for (int i=list.size()-1; i>=0; i--) {
7699            for (int j=which.size()-1; j>=0; j--) {
7700                if (which.get(j).equals(list.get(i))) {
7701                    return true;
7702                }
7703            }
7704        }
7705        return false;
7706    }
7707
7708    private void updateAllSharedLibrariesLPw() {
7709        for (PackageParser.Package pkg : mPackages.values()) {
7710            try {
7711                updateSharedLibrariesLPw(pkg, null);
7712            } catch (PackageManagerException e) {
7713                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7714            }
7715        }
7716    }
7717
7718    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7719            PackageParser.Package changingPkg) {
7720        ArrayList<PackageParser.Package> res = null;
7721        for (PackageParser.Package pkg : mPackages.values()) {
7722            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7723                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7724                if (res == null) {
7725                    res = new ArrayList<PackageParser.Package>();
7726                }
7727                res.add(pkg);
7728                try {
7729                    updateSharedLibrariesLPw(pkg, changingPkg);
7730                } catch (PackageManagerException e) {
7731                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7732                }
7733            }
7734        }
7735        return res;
7736    }
7737
7738    /**
7739     * Derive the value of the {@code cpuAbiOverride} based on the provided
7740     * value and an optional stored value from the package settings.
7741     */
7742    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7743        String cpuAbiOverride = null;
7744
7745        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7746            cpuAbiOverride = null;
7747        } else if (abiOverride != null) {
7748            cpuAbiOverride = abiOverride;
7749        } else if (settings != null) {
7750            cpuAbiOverride = settings.cpuAbiOverrideString;
7751        }
7752
7753        return cpuAbiOverride;
7754    }
7755
7756    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7757            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7758                    throws PackageManagerException {
7759        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7760        // If the package has children and this is the first dive in the function
7761        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7762        // whether all packages (parent and children) would be successfully scanned
7763        // before the actual scan since scanning mutates internal state and we want
7764        // to atomically install the package and its children.
7765        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7766            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7767                scanFlags |= SCAN_CHECK_ONLY;
7768            }
7769        } else {
7770            scanFlags &= ~SCAN_CHECK_ONLY;
7771        }
7772
7773        final PackageParser.Package scannedPkg;
7774        try {
7775            // Scan the parent
7776            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7777            // Scan the children
7778            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7779            for (int i = 0; i < childCount; i++) {
7780                PackageParser.Package childPkg = pkg.childPackages.get(i);
7781                scanPackageLI(childPkg, policyFlags,
7782                        scanFlags, currentTime, user);
7783            }
7784        } finally {
7785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7786        }
7787
7788        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7789            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7790        }
7791
7792        return scannedPkg;
7793    }
7794
7795    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7796            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7797        boolean success = false;
7798        try {
7799            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7800                    currentTime, user);
7801            success = true;
7802            return res;
7803        } finally {
7804            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7805                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7806                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7807                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7808                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7809            }
7810        }
7811    }
7812
7813    /**
7814     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7815     */
7816    private static boolean apkHasCode(String fileName) {
7817        StrictJarFile jarFile = null;
7818        try {
7819            jarFile = new StrictJarFile(fileName,
7820                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7821            return jarFile.findEntry("classes.dex") != null;
7822        } catch (IOException ignore) {
7823        } finally {
7824            try {
7825                jarFile.close();
7826            } catch (IOException ignore) {}
7827        }
7828        return false;
7829    }
7830
7831    /**
7832     * Enforces code policy for the package. This ensures that if an APK has
7833     * declared hasCode="true" in its manifest that the APK actually contains
7834     * code.
7835     *
7836     * @throws PackageManagerException If bytecode could not be found when it should exist
7837     */
7838    private static void enforceCodePolicy(PackageParser.Package pkg)
7839            throws PackageManagerException {
7840        final boolean shouldHaveCode =
7841                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7842        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7843            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7844                    "Package " + pkg.baseCodePath + " code is missing");
7845        }
7846
7847        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7848            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7849                final boolean splitShouldHaveCode =
7850                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7851                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7852                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7853                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7854                }
7855            }
7856        }
7857    }
7858
7859    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7860            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7861            throws PackageManagerException {
7862        final File scanFile = new File(pkg.codePath);
7863        if (pkg.applicationInfo.getCodePath() == null ||
7864                pkg.applicationInfo.getResourcePath() == null) {
7865            // Bail out. The resource and code paths haven't been set.
7866            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7867                    "Code and resource paths haven't been set correctly");
7868        }
7869
7870        // Apply policy
7871        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7872            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7873            if (pkg.applicationInfo.isDirectBootAware()) {
7874                // we're direct boot aware; set for all components
7875                for (PackageParser.Service s : pkg.services) {
7876                    s.info.encryptionAware = s.info.directBootAware = true;
7877                }
7878                for (PackageParser.Provider p : pkg.providers) {
7879                    p.info.encryptionAware = p.info.directBootAware = true;
7880                }
7881                for (PackageParser.Activity a : pkg.activities) {
7882                    a.info.encryptionAware = a.info.directBootAware = true;
7883                }
7884                for (PackageParser.Activity r : pkg.receivers) {
7885                    r.info.encryptionAware = r.info.directBootAware = true;
7886                }
7887            }
7888        } else {
7889            // Only allow system apps to be flagged as core apps.
7890            pkg.coreApp = false;
7891            // clear flags not applicable to regular apps
7892            pkg.applicationInfo.privateFlags &=
7893                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7894            pkg.applicationInfo.privateFlags &=
7895                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7896        }
7897        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7898
7899        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7900            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7901        }
7902
7903        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7904            enforceCodePolicy(pkg);
7905        }
7906
7907        if (mCustomResolverComponentName != null &&
7908                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7909            setUpCustomResolverActivity(pkg);
7910        }
7911
7912        if (pkg.packageName.equals("android")) {
7913            synchronized (mPackages) {
7914                if (mAndroidApplication != null) {
7915                    Slog.w(TAG, "*************************************************");
7916                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7917                    Slog.w(TAG, " file=" + scanFile);
7918                    Slog.w(TAG, "*************************************************");
7919                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7920                            "Core android package being redefined.  Skipping.");
7921                }
7922
7923                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7924                    // Set up information for our fall-back user intent resolution activity.
7925                    mPlatformPackage = pkg;
7926                    pkg.mVersionCode = mSdkVersion;
7927                    mAndroidApplication = pkg.applicationInfo;
7928
7929                    if (!mResolverReplaced) {
7930                        mResolveActivity.applicationInfo = mAndroidApplication;
7931                        mResolveActivity.name = ResolverActivity.class.getName();
7932                        mResolveActivity.packageName = mAndroidApplication.packageName;
7933                        mResolveActivity.processName = "system:ui";
7934                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7935                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7936                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7937                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7938                        mResolveActivity.exported = true;
7939                        mResolveActivity.enabled = true;
7940                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7941                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7942                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7943                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7944                                | ActivityInfo.CONFIG_ORIENTATION
7945                                | ActivityInfo.CONFIG_KEYBOARD
7946                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7947                        mResolveInfo.activityInfo = mResolveActivity;
7948                        mResolveInfo.priority = 0;
7949                        mResolveInfo.preferredOrder = 0;
7950                        mResolveInfo.match = 0;
7951                        mResolveComponentName = new ComponentName(
7952                                mAndroidApplication.packageName, mResolveActivity.name);
7953                    }
7954                }
7955            }
7956        }
7957
7958        if (DEBUG_PACKAGE_SCANNING) {
7959            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7960                Log.d(TAG, "Scanning package " + pkg.packageName);
7961        }
7962
7963        synchronized (mPackages) {
7964            if (mPackages.containsKey(pkg.packageName)
7965                    || mSharedLibraries.containsKey(pkg.packageName)) {
7966                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7967                        "Application package " + pkg.packageName
7968                                + " already installed.  Skipping duplicate.");
7969            }
7970
7971            // If we're only installing presumed-existing packages, require that the
7972            // scanned APK is both already known and at the path previously established
7973            // for it.  Previously unknown packages we pick up normally, but if we have an
7974            // a priori expectation about this package's install presence, enforce it.
7975            // With a singular exception for new system packages. When an OTA contains
7976            // a new system package, we allow the codepath to change from a system location
7977            // to the user-installed location. If we don't allow this change, any newer,
7978            // user-installed version of the application will be ignored.
7979            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7980                if (mExpectingBetter.containsKey(pkg.packageName)) {
7981                    logCriticalInfo(Log.WARN,
7982                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7983                } else {
7984                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7985                    if (known != null) {
7986                        if (DEBUG_PACKAGE_SCANNING) {
7987                            Log.d(TAG, "Examining " + pkg.codePath
7988                                    + " and requiring known paths " + known.codePathString
7989                                    + " & " + known.resourcePathString);
7990                        }
7991                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7992                                || !pkg.applicationInfo.getResourcePath().equals(
7993                                known.resourcePathString)) {
7994                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7995                                    "Application package " + pkg.packageName
7996                                            + " found at " + pkg.applicationInfo.getCodePath()
7997                                            + " but expected at " + known.codePathString
7998                                            + "; ignoring.");
7999                        }
8000                    }
8001                }
8002            }
8003        }
8004
8005        // Initialize package source and resource directories
8006        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8007        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8008
8009        SharedUserSetting suid = null;
8010        PackageSetting pkgSetting = null;
8011
8012        if (!isSystemApp(pkg)) {
8013            // Only system apps can use these features.
8014            pkg.mOriginalPackages = null;
8015            pkg.mRealPackage = null;
8016            pkg.mAdoptPermissions = null;
8017        }
8018
8019        // Getting the package setting may have a side-effect, so if we
8020        // are only checking if scan would succeed, stash a copy of the
8021        // old setting to restore at the end.
8022        PackageSetting nonMutatedPs = null;
8023
8024        // writer
8025        synchronized (mPackages) {
8026            if (pkg.mSharedUserId != null) {
8027                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8028                if (suid == null) {
8029                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8030                            "Creating application package " + pkg.packageName
8031                            + " for shared user failed");
8032                }
8033                if (DEBUG_PACKAGE_SCANNING) {
8034                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8035                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8036                                + "): packages=" + suid.packages);
8037                }
8038            }
8039
8040            // Check if we are renaming from an original package name.
8041            PackageSetting origPackage = null;
8042            String realName = null;
8043            if (pkg.mOriginalPackages != null) {
8044                // This package may need to be renamed to a previously
8045                // installed name.  Let's check on that...
8046                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8047                if (pkg.mOriginalPackages.contains(renamed)) {
8048                    // This package had originally been installed as the
8049                    // original name, and we have already taken care of
8050                    // transitioning to the new one.  Just update the new
8051                    // one to continue using the old name.
8052                    realName = pkg.mRealPackage;
8053                    if (!pkg.packageName.equals(renamed)) {
8054                        // Callers into this function may have already taken
8055                        // care of renaming the package; only do it here if
8056                        // it is not already done.
8057                        pkg.setPackageName(renamed);
8058                    }
8059
8060                } else {
8061                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8062                        if ((origPackage = mSettings.peekPackageLPr(
8063                                pkg.mOriginalPackages.get(i))) != null) {
8064                            // We do have the package already installed under its
8065                            // original name...  should we use it?
8066                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8067                                // New package is not compatible with original.
8068                                origPackage = null;
8069                                continue;
8070                            } else if (origPackage.sharedUser != null) {
8071                                // Make sure uid is compatible between packages.
8072                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8073                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8074                                            + " to " + pkg.packageName + ": old uid "
8075                                            + origPackage.sharedUser.name
8076                                            + " differs from " + pkg.mSharedUserId);
8077                                    origPackage = null;
8078                                    continue;
8079                                }
8080                                // TODO: Add case when shared user id is added [b/28144775]
8081                            } else {
8082                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8083                                        + pkg.packageName + " to old name " + origPackage.name);
8084                            }
8085                            break;
8086                        }
8087                    }
8088                }
8089            }
8090
8091            if (mTransferedPackages.contains(pkg.packageName)) {
8092                Slog.w(TAG, "Package " + pkg.packageName
8093                        + " was transferred to another, but its .apk remains");
8094            }
8095
8096            // See comments in nonMutatedPs declaration
8097            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8098                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8099                if (foundPs != null) {
8100                    nonMutatedPs = new PackageSetting(foundPs);
8101                }
8102            }
8103
8104            // Just create the setting, don't add it yet. For already existing packages
8105            // the PkgSetting exists already and doesn't have to be created.
8106            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8107                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8108                    pkg.applicationInfo.primaryCpuAbi,
8109                    pkg.applicationInfo.secondaryCpuAbi,
8110                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8111                    user, false);
8112            if (pkgSetting == null) {
8113                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8114                        "Creating application package " + pkg.packageName + " failed");
8115            }
8116
8117            if (pkgSetting.origPackage != null) {
8118                // If we are first transitioning from an original package,
8119                // fix up the new package's name now.  We need to do this after
8120                // looking up the package under its new name, so getPackageLP
8121                // can take care of fiddling things correctly.
8122                pkg.setPackageName(origPackage.name);
8123
8124                // File a report about this.
8125                String msg = "New package " + pkgSetting.realName
8126                        + " renamed to replace old package " + pkgSetting.name;
8127                reportSettingsProblem(Log.WARN, msg);
8128
8129                // Make a note of it.
8130                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8131                    mTransferedPackages.add(origPackage.name);
8132                }
8133
8134                // No longer need to retain this.
8135                pkgSetting.origPackage = null;
8136            }
8137
8138            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8139                // Make a note of it.
8140                mTransferedPackages.add(pkg.packageName);
8141            }
8142
8143            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8144                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8145            }
8146
8147            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8148                // Check all shared libraries and map to their actual file path.
8149                // We only do this here for apps not on a system dir, because those
8150                // are the only ones that can fail an install due to this.  We
8151                // will take care of the system apps by updating all of their
8152                // library paths after the scan is done.
8153                updateSharedLibrariesLPw(pkg, null);
8154            }
8155
8156            if (mFoundPolicyFile) {
8157                SELinuxMMAC.assignSeinfoValue(pkg);
8158            }
8159
8160            pkg.applicationInfo.uid = pkgSetting.appId;
8161            pkg.mExtras = pkgSetting;
8162            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8163                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8164                    // We just determined the app is signed correctly, so bring
8165                    // over the latest parsed certs.
8166                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8167                } else {
8168                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8169                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8170                                "Package " + pkg.packageName + " upgrade keys do not match the "
8171                                + "previously installed version");
8172                    } else {
8173                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8174                        String msg = "System package " + pkg.packageName
8175                            + " signature changed; retaining data.";
8176                        reportSettingsProblem(Log.WARN, msg);
8177                    }
8178                }
8179            } else {
8180                try {
8181                    verifySignaturesLP(pkgSetting, pkg);
8182                    // We just determined the app is signed correctly, so bring
8183                    // over the latest parsed certs.
8184                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8185                } catch (PackageManagerException e) {
8186                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8187                        throw e;
8188                    }
8189                    // The signature has changed, but this package is in the system
8190                    // image...  let's recover!
8191                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8192                    // However...  if this package is part of a shared user, but it
8193                    // doesn't match the signature of the shared user, let's fail.
8194                    // What this means is that you can't change the signatures
8195                    // associated with an overall shared user, which doesn't seem all
8196                    // that unreasonable.
8197                    if (pkgSetting.sharedUser != null) {
8198                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8199                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8200                            throw new PackageManagerException(
8201                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8202                                            "Signature mismatch for shared user: "
8203                                            + pkgSetting.sharedUser);
8204                        }
8205                    }
8206                    // File a report about this.
8207                    String msg = "System package " + pkg.packageName
8208                        + " signature changed; retaining data.";
8209                    reportSettingsProblem(Log.WARN, msg);
8210                }
8211            }
8212            // Verify that this new package doesn't have any content providers
8213            // that conflict with existing packages.  Only do this if the
8214            // package isn't already installed, since we don't want to break
8215            // things that are installed.
8216            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8217                final int N = pkg.providers.size();
8218                int i;
8219                for (i=0; i<N; i++) {
8220                    PackageParser.Provider p = pkg.providers.get(i);
8221                    if (p.info.authority != null) {
8222                        String names[] = p.info.authority.split(";");
8223                        for (int j = 0; j < names.length; j++) {
8224                            if (mProvidersByAuthority.containsKey(names[j])) {
8225                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8226                                final String otherPackageName =
8227                                        ((other != null && other.getComponentName() != null) ?
8228                                                other.getComponentName().getPackageName() : "?");
8229                                throw new PackageManagerException(
8230                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8231                                                "Can't install because provider name " + names[j]
8232                                                + " (in package " + pkg.applicationInfo.packageName
8233                                                + ") is already used by " + otherPackageName);
8234                            }
8235                        }
8236                    }
8237                }
8238            }
8239
8240            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8241                // This package wants to adopt ownership of permissions from
8242                // another package.
8243                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8244                    final String origName = pkg.mAdoptPermissions.get(i);
8245                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8246                    if (orig != null) {
8247                        if (verifyPackageUpdateLPr(orig, pkg)) {
8248                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8249                                    + pkg.packageName);
8250                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8251                        }
8252                    }
8253                }
8254            }
8255        }
8256
8257        final String pkgName = pkg.packageName;
8258
8259        final long scanFileTime = scanFile.lastModified();
8260        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8261        pkg.applicationInfo.processName = fixProcessName(
8262                pkg.applicationInfo.packageName,
8263                pkg.applicationInfo.processName,
8264                pkg.applicationInfo.uid);
8265
8266        if (pkg != mPlatformPackage) {
8267            // Get all of our default paths setup
8268            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8269        }
8270
8271        final String path = scanFile.getPath();
8272        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8273
8274        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8275            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8276
8277            // Some system apps still use directory structure for native libraries
8278            // in which case we might end up not detecting abi solely based on apk
8279            // structure. Try to detect abi based on directory structure.
8280            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8281                    pkg.applicationInfo.primaryCpuAbi == null) {
8282                setBundledAppAbisAndRoots(pkg, pkgSetting);
8283                setNativeLibraryPaths(pkg);
8284            }
8285
8286        } else {
8287            if ((scanFlags & SCAN_MOVE) != 0) {
8288                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8289                // but we already have this packages package info in the PackageSetting. We just
8290                // use that and derive the native library path based on the new codepath.
8291                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8292                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8293            }
8294
8295            // Set native library paths again. For moves, the path will be updated based on the
8296            // ABIs we've determined above. For non-moves, the path will be updated based on the
8297            // ABIs we determined during compilation, but the path will depend on the final
8298            // package path (after the rename away from the stage path).
8299            setNativeLibraryPaths(pkg);
8300        }
8301
8302        // This is a special case for the "system" package, where the ABI is
8303        // dictated by the zygote configuration (and init.rc). We should keep track
8304        // of this ABI so that we can deal with "normal" applications that run under
8305        // the same UID correctly.
8306        if (mPlatformPackage == pkg) {
8307            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8308                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8309        }
8310
8311        // If there's a mismatch between the abi-override in the package setting
8312        // and the abiOverride specified for the install. Warn about this because we
8313        // would've already compiled the app without taking the package setting into
8314        // account.
8315        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8316            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8317                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8318                        " for package " + pkg.packageName);
8319            }
8320        }
8321
8322        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8323        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8324        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8325
8326        // Copy the derived override back to the parsed package, so that we can
8327        // update the package settings accordingly.
8328        pkg.cpuAbiOverride = cpuAbiOverride;
8329
8330        if (DEBUG_ABI_SELECTION) {
8331            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8332                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8333                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8334        }
8335
8336        // Push the derived path down into PackageSettings so we know what to
8337        // clean up at uninstall time.
8338        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8339
8340        if (DEBUG_ABI_SELECTION) {
8341            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8342                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8343                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8344        }
8345
8346        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8347            // We don't do this here during boot because we can do it all
8348            // at once after scanning all existing packages.
8349            //
8350            // We also do this *before* we perform dexopt on this package, so that
8351            // we can avoid redundant dexopts, and also to make sure we've got the
8352            // code and package path correct.
8353            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8354                    pkg, true /* boot complete */);
8355        }
8356
8357        if (mFactoryTest && pkg.requestedPermissions.contains(
8358                android.Manifest.permission.FACTORY_TEST)) {
8359            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8360        }
8361
8362        ArrayList<PackageParser.Package> clientLibPkgs = null;
8363
8364        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8365            if (nonMutatedPs != null) {
8366                synchronized (mPackages) {
8367                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8368                }
8369            }
8370            return pkg;
8371        }
8372
8373        // Only privileged apps and updated privileged apps can add child packages.
8374        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8375            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8376                throw new PackageManagerException("Only privileged apps and updated "
8377                        + "privileged apps can add child packages. Ignoring package "
8378                        + pkg.packageName);
8379            }
8380            final int childCount = pkg.childPackages.size();
8381            for (int i = 0; i < childCount; i++) {
8382                PackageParser.Package childPkg = pkg.childPackages.get(i);
8383                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8384                        childPkg.packageName)) {
8385                    throw new PackageManagerException("Cannot override a child package of "
8386                            + "another disabled system app. Ignoring package " + pkg.packageName);
8387                }
8388            }
8389        }
8390
8391        // writer
8392        synchronized (mPackages) {
8393            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8394                // Only system apps can add new shared libraries.
8395                if (pkg.libraryNames != null) {
8396                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8397                        String name = pkg.libraryNames.get(i);
8398                        boolean allowed = false;
8399                        if (pkg.isUpdatedSystemApp()) {
8400                            // New library entries can only be added through the
8401                            // system image.  This is important to get rid of a lot
8402                            // of nasty edge cases: for example if we allowed a non-
8403                            // system update of the app to add a library, then uninstalling
8404                            // the update would make the library go away, and assumptions
8405                            // we made such as through app install filtering would now
8406                            // have allowed apps on the device which aren't compatible
8407                            // with it.  Better to just have the restriction here, be
8408                            // conservative, and create many fewer cases that can negatively
8409                            // impact the user experience.
8410                            final PackageSetting sysPs = mSettings
8411                                    .getDisabledSystemPkgLPr(pkg.packageName);
8412                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8413                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8414                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8415                                        allowed = true;
8416                                        break;
8417                                    }
8418                                }
8419                            }
8420                        } else {
8421                            allowed = true;
8422                        }
8423                        if (allowed) {
8424                            if (!mSharedLibraries.containsKey(name)) {
8425                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8426                            } else if (!name.equals(pkg.packageName)) {
8427                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8428                                        + name + " already exists; skipping");
8429                            }
8430                        } else {
8431                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8432                                    + name + " that is not declared on system image; skipping");
8433                        }
8434                    }
8435                    if ((scanFlags & SCAN_BOOTING) == 0) {
8436                        // If we are not booting, we need to update any applications
8437                        // that are clients of our shared library.  If we are booting,
8438                        // this will all be done once the scan is complete.
8439                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8440                    }
8441                }
8442            }
8443        }
8444
8445        if ((scanFlags & SCAN_BOOTING) != 0) {
8446            // No apps can run during boot scan, so they don't need to be frozen
8447        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8448            // Caller asked to not kill app, so it's probably not frozen
8449        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8450            // Caller asked us to ignore frozen check for some reason; they
8451            // probably didn't know the package name
8452        } else {
8453            // We're doing major surgery on this package, so it better be frozen
8454            // right now to keep it from launching
8455            checkPackageFrozen(pkgName);
8456        }
8457
8458        // Also need to kill any apps that are dependent on the library.
8459        if (clientLibPkgs != null) {
8460            for (int i=0; i<clientLibPkgs.size(); i++) {
8461                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8462                killApplication(clientPkg.applicationInfo.packageName,
8463                        clientPkg.applicationInfo.uid, "update lib");
8464            }
8465        }
8466
8467        // Make sure we're not adding any bogus keyset info
8468        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8469        ksms.assertScannedPackageValid(pkg);
8470
8471        // writer
8472        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8473
8474        boolean createIdmapFailed = false;
8475        synchronized (mPackages) {
8476            // We don't expect installation to fail beyond this point
8477
8478            if (pkgSetting.pkg != null) {
8479                // Note that |user| might be null during the initial boot scan. If a codePath
8480                // for an app has changed during a boot scan, it's due to an app update that's
8481                // part of the system partition and marker changes must be applied to all users.
8482                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8483                    (user != null) ? user : UserHandle.ALL);
8484            }
8485
8486            // Add the new setting to mSettings
8487            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8488            // Add the new setting to mPackages
8489            mPackages.put(pkg.applicationInfo.packageName, pkg);
8490            // Make sure we don't accidentally delete its data.
8491            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8492            while (iter.hasNext()) {
8493                PackageCleanItem item = iter.next();
8494                if (pkgName.equals(item.packageName)) {
8495                    iter.remove();
8496                }
8497            }
8498
8499            // Take care of first install / last update times.
8500            if (currentTime != 0) {
8501                if (pkgSetting.firstInstallTime == 0) {
8502                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8503                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8504                    pkgSetting.lastUpdateTime = currentTime;
8505                }
8506            } else if (pkgSetting.firstInstallTime == 0) {
8507                // We need *something*.  Take time time stamp of the file.
8508                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8509            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8510                if (scanFileTime != pkgSetting.timeStamp) {
8511                    // A package on the system image has changed; consider this
8512                    // to be an update.
8513                    pkgSetting.lastUpdateTime = scanFileTime;
8514                }
8515            }
8516
8517            // Add the package's KeySets to the global KeySetManagerService
8518            ksms.addScannedPackageLPw(pkg);
8519
8520            int N = pkg.providers.size();
8521            StringBuilder r = null;
8522            int i;
8523            for (i=0; i<N; i++) {
8524                PackageParser.Provider p = pkg.providers.get(i);
8525                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8526                        p.info.processName, pkg.applicationInfo.uid);
8527                mProviders.addProvider(p);
8528                p.syncable = p.info.isSyncable;
8529                if (p.info.authority != null) {
8530                    String names[] = p.info.authority.split(";");
8531                    p.info.authority = null;
8532                    for (int j = 0; j < names.length; j++) {
8533                        if (j == 1 && p.syncable) {
8534                            // We only want the first authority for a provider to possibly be
8535                            // syncable, so if we already added this provider using a different
8536                            // authority clear the syncable flag. We copy the provider before
8537                            // changing it because the mProviders object contains a reference
8538                            // to a provider that we don't want to change.
8539                            // Only do this for the second authority since the resulting provider
8540                            // object can be the same for all future authorities for this provider.
8541                            p = new PackageParser.Provider(p);
8542                            p.syncable = false;
8543                        }
8544                        if (!mProvidersByAuthority.containsKey(names[j])) {
8545                            mProvidersByAuthority.put(names[j], p);
8546                            if (p.info.authority == null) {
8547                                p.info.authority = names[j];
8548                            } else {
8549                                p.info.authority = p.info.authority + ";" + names[j];
8550                            }
8551                            if (DEBUG_PACKAGE_SCANNING) {
8552                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8553                                    Log.d(TAG, "Registered content provider: " + names[j]
8554                                            + ", className = " + p.info.name + ", isSyncable = "
8555                                            + p.info.isSyncable);
8556                            }
8557                        } else {
8558                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8559                            Slog.w(TAG, "Skipping provider name " + names[j] +
8560                                    " (in package " + pkg.applicationInfo.packageName +
8561                                    "): name already used by "
8562                                    + ((other != null && other.getComponentName() != null)
8563                                            ? other.getComponentName().getPackageName() : "?"));
8564                        }
8565                    }
8566                }
8567                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8568                    if (r == null) {
8569                        r = new StringBuilder(256);
8570                    } else {
8571                        r.append(' ');
8572                    }
8573                    r.append(p.info.name);
8574                }
8575            }
8576            if (r != null) {
8577                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8578            }
8579
8580            N = pkg.services.size();
8581            r = null;
8582            for (i=0; i<N; i++) {
8583                PackageParser.Service s = pkg.services.get(i);
8584                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8585                        s.info.processName, pkg.applicationInfo.uid);
8586                mServices.addService(s);
8587                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8588                    if (r == null) {
8589                        r = new StringBuilder(256);
8590                    } else {
8591                        r.append(' ');
8592                    }
8593                    r.append(s.info.name);
8594                }
8595            }
8596            if (r != null) {
8597                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8598            }
8599
8600            N = pkg.receivers.size();
8601            r = null;
8602            for (i=0; i<N; i++) {
8603                PackageParser.Activity a = pkg.receivers.get(i);
8604                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8605                        a.info.processName, pkg.applicationInfo.uid);
8606                mReceivers.addActivity(a, "receiver");
8607                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8608                    if (r == null) {
8609                        r = new StringBuilder(256);
8610                    } else {
8611                        r.append(' ');
8612                    }
8613                    r.append(a.info.name);
8614                }
8615            }
8616            if (r != null) {
8617                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8618            }
8619
8620            N = pkg.activities.size();
8621            r = null;
8622            for (i=0; i<N; i++) {
8623                PackageParser.Activity a = pkg.activities.get(i);
8624                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8625                        a.info.processName, pkg.applicationInfo.uid);
8626                mActivities.addActivity(a, "activity");
8627                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8628                    if (r == null) {
8629                        r = new StringBuilder(256);
8630                    } else {
8631                        r.append(' ');
8632                    }
8633                    r.append(a.info.name);
8634                }
8635            }
8636            if (r != null) {
8637                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8638            }
8639
8640            N = pkg.permissionGroups.size();
8641            r = null;
8642            for (i=0; i<N; i++) {
8643                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8644                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8645                if (cur == null) {
8646                    mPermissionGroups.put(pg.info.name, pg);
8647                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8648                        if (r == null) {
8649                            r = new StringBuilder(256);
8650                        } else {
8651                            r.append(' ');
8652                        }
8653                        r.append(pg.info.name);
8654                    }
8655                } else {
8656                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8657                            + pg.info.packageName + " ignored: original from "
8658                            + cur.info.packageName);
8659                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8660                        if (r == null) {
8661                            r = new StringBuilder(256);
8662                        } else {
8663                            r.append(' ');
8664                        }
8665                        r.append("DUP:");
8666                        r.append(pg.info.name);
8667                    }
8668                }
8669            }
8670            if (r != null) {
8671                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8672            }
8673
8674            N = pkg.permissions.size();
8675            r = null;
8676            for (i=0; i<N; i++) {
8677                PackageParser.Permission p = pkg.permissions.get(i);
8678
8679                // Assume by default that we did not install this permission into the system.
8680                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8681
8682                // Now that permission groups have a special meaning, we ignore permission
8683                // groups for legacy apps to prevent unexpected behavior. In particular,
8684                // permissions for one app being granted to someone just becase they happen
8685                // to be in a group defined by another app (before this had no implications).
8686                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8687                    p.group = mPermissionGroups.get(p.info.group);
8688                    // Warn for a permission in an unknown group.
8689                    if (p.info.group != null && p.group == null) {
8690                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8691                                + p.info.packageName + " in an unknown group " + p.info.group);
8692                    }
8693                }
8694
8695                ArrayMap<String, BasePermission> permissionMap =
8696                        p.tree ? mSettings.mPermissionTrees
8697                                : mSettings.mPermissions;
8698                BasePermission bp = permissionMap.get(p.info.name);
8699
8700                // Allow system apps to redefine non-system permissions
8701                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8702                    final boolean currentOwnerIsSystem = (bp.perm != null
8703                            && isSystemApp(bp.perm.owner));
8704                    if (isSystemApp(p.owner)) {
8705                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8706                            // It's a built-in permission and no owner, take ownership now
8707                            bp.packageSetting = pkgSetting;
8708                            bp.perm = p;
8709                            bp.uid = pkg.applicationInfo.uid;
8710                            bp.sourcePackage = p.info.packageName;
8711                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8712                        } else if (!currentOwnerIsSystem) {
8713                            String msg = "New decl " + p.owner + " of permission  "
8714                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8715                            reportSettingsProblem(Log.WARN, msg);
8716                            bp = null;
8717                        }
8718                    }
8719                }
8720
8721                if (bp == null) {
8722                    bp = new BasePermission(p.info.name, p.info.packageName,
8723                            BasePermission.TYPE_NORMAL);
8724                    permissionMap.put(p.info.name, bp);
8725                }
8726
8727                if (bp.perm == null) {
8728                    if (bp.sourcePackage == null
8729                            || bp.sourcePackage.equals(p.info.packageName)) {
8730                        BasePermission tree = findPermissionTreeLP(p.info.name);
8731                        if (tree == null
8732                                || tree.sourcePackage.equals(p.info.packageName)) {
8733                            bp.packageSetting = pkgSetting;
8734                            bp.perm = p;
8735                            bp.uid = pkg.applicationInfo.uid;
8736                            bp.sourcePackage = p.info.packageName;
8737                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8738                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8739                                if (r == null) {
8740                                    r = new StringBuilder(256);
8741                                } else {
8742                                    r.append(' ');
8743                                }
8744                                r.append(p.info.name);
8745                            }
8746                        } else {
8747                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8748                                    + p.info.packageName + " ignored: base tree "
8749                                    + tree.name + " is from package "
8750                                    + tree.sourcePackage);
8751                        }
8752                    } else {
8753                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8754                                + p.info.packageName + " ignored: original from "
8755                                + bp.sourcePackage);
8756                    }
8757                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8758                    if (r == null) {
8759                        r = new StringBuilder(256);
8760                    } else {
8761                        r.append(' ');
8762                    }
8763                    r.append("DUP:");
8764                    r.append(p.info.name);
8765                }
8766                if (bp.perm == p) {
8767                    bp.protectionLevel = p.info.protectionLevel;
8768                }
8769            }
8770
8771            if (r != null) {
8772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8773            }
8774
8775            N = pkg.instrumentation.size();
8776            r = null;
8777            for (i=0; i<N; i++) {
8778                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8779                a.info.packageName = pkg.applicationInfo.packageName;
8780                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8781                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8782                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8783                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8784                a.info.dataDir = pkg.applicationInfo.dataDir;
8785                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8786                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8787
8788                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8789                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8790                mInstrumentation.put(a.getComponentName(), a);
8791                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8792                    if (r == null) {
8793                        r = new StringBuilder(256);
8794                    } else {
8795                        r.append(' ');
8796                    }
8797                    r.append(a.info.name);
8798                }
8799            }
8800            if (r != null) {
8801                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8802            }
8803
8804            if (pkg.protectedBroadcasts != null) {
8805                N = pkg.protectedBroadcasts.size();
8806                for (i=0; i<N; i++) {
8807                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8808                }
8809            }
8810
8811            pkgSetting.setTimeStamp(scanFileTime);
8812
8813            // Create idmap files for pairs of (packages, overlay packages).
8814            // Note: "android", ie framework-res.apk, is handled by native layers.
8815            if (pkg.mOverlayTarget != null) {
8816                // This is an overlay package.
8817                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8818                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8819                        mOverlays.put(pkg.mOverlayTarget,
8820                                new ArrayMap<String, PackageParser.Package>());
8821                    }
8822                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8823                    map.put(pkg.packageName, pkg);
8824                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8825                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8826                        createIdmapFailed = true;
8827                    }
8828                }
8829            } else if (mOverlays.containsKey(pkg.packageName) &&
8830                    !pkg.packageName.equals("android")) {
8831                // This is a regular package, with one or more known overlay packages.
8832                createIdmapsForPackageLI(pkg);
8833            }
8834        }
8835
8836        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8837
8838        if (createIdmapFailed) {
8839            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8840                    "scanPackageLI failed to createIdmap");
8841        }
8842        return pkg;
8843    }
8844
8845    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8846            PackageParser.Package update, UserHandle user) {
8847        if (existing.applicationInfo == null || update.applicationInfo == null) {
8848            // This isn't due to an app installation.
8849            return;
8850        }
8851
8852        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8853        final File newCodePath = new File(update.applicationInfo.getCodePath());
8854
8855        // The codePath hasn't changed, so there's nothing for us to do.
8856        if (Objects.equals(oldCodePath, newCodePath)) {
8857            return;
8858        }
8859
8860        File canonicalNewCodePath;
8861        try {
8862            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8863        } catch (IOException e) {
8864            Slog.w(TAG, "Failed to get canonical path.", e);
8865            return;
8866        }
8867
8868        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8869        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8870        // that the last component of the path (i.e, the name) doesn't need canonicalization
8871        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8872        // but may change in the future. Hopefully this function won't exist at that point.
8873        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8874                oldCodePath.getName());
8875
8876        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8877        // with "@".
8878        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8879        if (!oldMarkerPrefix.endsWith("@")) {
8880            oldMarkerPrefix += "@";
8881        }
8882        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8883        if (!newMarkerPrefix.endsWith("@")) {
8884            newMarkerPrefix += "@";
8885        }
8886
8887        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8888        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8889        for (String updatedPath : updatedPaths) {
8890            String updatedPathName = new File(updatedPath).getName();
8891            markerSuffixes.add(updatedPathName.replace('/', '@'));
8892        }
8893
8894        for (int userId : resolveUserIds(user.getIdentifier())) {
8895            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8896
8897            for (String markerSuffix : markerSuffixes) {
8898                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8899                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8900                if (oldForeignUseMark.exists()) {
8901                    try {
8902                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8903                                newForeignUseMark.getAbsolutePath());
8904                    } catch (ErrnoException e) {
8905                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8906                        oldForeignUseMark.delete();
8907                    }
8908                }
8909            }
8910        }
8911    }
8912
8913    /**
8914     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8915     * is derived purely on the basis of the contents of {@code scanFile} and
8916     * {@code cpuAbiOverride}.
8917     *
8918     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8919     */
8920    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8921                                 String cpuAbiOverride, boolean extractLibs)
8922            throws PackageManagerException {
8923        // TODO: We can probably be smarter about this stuff. For installed apps,
8924        // we can calculate this information at install time once and for all. For
8925        // system apps, we can probably assume that this information doesn't change
8926        // after the first boot scan. As things stand, we do lots of unnecessary work.
8927
8928        // Give ourselves some initial paths; we'll come back for another
8929        // pass once we've determined ABI below.
8930        setNativeLibraryPaths(pkg);
8931
8932        // We would never need to extract libs for forward-locked and external packages,
8933        // since the container service will do it for us. We shouldn't attempt to
8934        // extract libs from system app when it was not updated.
8935        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8936                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8937            extractLibs = false;
8938        }
8939
8940        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8941        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8942
8943        NativeLibraryHelper.Handle handle = null;
8944        try {
8945            handle = NativeLibraryHelper.Handle.create(pkg);
8946            // TODO(multiArch): This can be null for apps that didn't go through the
8947            // usual installation process. We can calculate it again, like we
8948            // do during install time.
8949            //
8950            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8951            // unnecessary.
8952            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8953
8954            // Null out the abis so that they can be recalculated.
8955            pkg.applicationInfo.primaryCpuAbi = null;
8956            pkg.applicationInfo.secondaryCpuAbi = null;
8957            if (isMultiArch(pkg.applicationInfo)) {
8958                // Warn if we've set an abiOverride for multi-lib packages..
8959                // By definition, we need to copy both 32 and 64 bit libraries for
8960                // such packages.
8961                if (pkg.cpuAbiOverride != null
8962                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8963                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8964                }
8965
8966                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8967                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8968                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8969                    if (extractLibs) {
8970                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8971                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8972                                useIsaSpecificSubdirs);
8973                    } else {
8974                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8975                    }
8976                }
8977
8978                maybeThrowExceptionForMultiArchCopy(
8979                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8980
8981                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8982                    if (extractLibs) {
8983                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8984                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8985                                useIsaSpecificSubdirs);
8986                    } else {
8987                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8988                    }
8989                }
8990
8991                maybeThrowExceptionForMultiArchCopy(
8992                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8993
8994                if (abi64 >= 0) {
8995                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8996                }
8997
8998                if (abi32 >= 0) {
8999                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9000                    if (abi64 >= 0) {
9001                        if (pkg.use32bitAbi) {
9002                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9003                            pkg.applicationInfo.primaryCpuAbi = abi;
9004                        } else {
9005                            pkg.applicationInfo.secondaryCpuAbi = abi;
9006                        }
9007                    } else {
9008                        pkg.applicationInfo.primaryCpuAbi = abi;
9009                    }
9010                }
9011
9012            } else {
9013                String[] abiList = (cpuAbiOverride != null) ?
9014                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9015
9016                // Enable gross and lame hacks for apps that are built with old
9017                // SDK tools. We must scan their APKs for renderscript bitcode and
9018                // not launch them if it's present. Don't bother checking on devices
9019                // that don't have 64 bit support.
9020                boolean needsRenderScriptOverride = false;
9021                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9022                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9023                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9024                    needsRenderScriptOverride = true;
9025                }
9026
9027                final int copyRet;
9028                if (extractLibs) {
9029                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9030                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9031                } else {
9032                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9033                }
9034
9035                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9036                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9037                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9038                }
9039
9040                if (copyRet >= 0) {
9041                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9042                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9043                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9044                } else if (needsRenderScriptOverride) {
9045                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9046                }
9047            }
9048        } catch (IOException ioe) {
9049            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9050        } finally {
9051            IoUtils.closeQuietly(handle);
9052        }
9053
9054        // Now that we've calculated the ABIs and determined if it's an internal app,
9055        // we will go ahead and populate the nativeLibraryPath.
9056        setNativeLibraryPaths(pkg);
9057    }
9058
9059    /**
9060     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9061     * i.e, so that all packages can be run inside a single process if required.
9062     *
9063     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9064     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9065     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9066     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9067     * updating a package that belongs to a shared user.
9068     *
9069     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9070     * adds unnecessary complexity.
9071     */
9072    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9073            PackageParser.Package scannedPackage, boolean bootComplete) {
9074        String requiredInstructionSet = null;
9075        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9076            requiredInstructionSet = VMRuntime.getInstructionSet(
9077                     scannedPackage.applicationInfo.primaryCpuAbi);
9078        }
9079
9080        PackageSetting requirer = null;
9081        for (PackageSetting ps : packagesForUser) {
9082            // If packagesForUser contains scannedPackage, we skip it. This will happen
9083            // when scannedPackage is an update of an existing package. Without this check,
9084            // we will never be able to change the ABI of any package belonging to a shared
9085            // user, even if it's compatible with other packages.
9086            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9087                if (ps.primaryCpuAbiString == null) {
9088                    continue;
9089                }
9090
9091                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9092                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9093                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9094                    // this but there's not much we can do.
9095                    String errorMessage = "Instruction set mismatch, "
9096                            + ((requirer == null) ? "[caller]" : requirer)
9097                            + " requires " + requiredInstructionSet + " whereas " + ps
9098                            + " requires " + instructionSet;
9099                    Slog.w(TAG, errorMessage);
9100                }
9101
9102                if (requiredInstructionSet == null) {
9103                    requiredInstructionSet = instructionSet;
9104                    requirer = ps;
9105                }
9106            }
9107        }
9108
9109        if (requiredInstructionSet != null) {
9110            String adjustedAbi;
9111            if (requirer != null) {
9112                // requirer != null implies that either scannedPackage was null or that scannedPackage
9113                // did not require an ABI, in which case we have to adjust scannedPackage to match
9114                // the ABI of the set (which is the same as requirer's ABI)
9115                adjustedAbi = requirer.primaryCpuAbiString;
9116                if (scannedPackage != null) {
9117                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9118                }
9119            } else {
9120                // requirer == null implies that we're updating all ABIs in the set to
9121                // match scannedPackage.
9122                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9123            }
9124
9125            for (PackageSetting ps : packagesForUser) {
9126                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9127                    if (ps.primaryCpuAbiString != null) {
9128                        continue;
9129                    }
9130
9131                    ps.primaryCpuAbiString = adjustedAbi;
9132                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9133                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9134                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9135                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9136                                + " (requirer="
9137                                + (requirer == null ? "null" : requirer.pkg.packageName)
9138                                + ", scannedPackage="
9139                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9140                                + ")");
9141                        try {
9142                            mInstaller.rmdex(ps.codePathString,
9143                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9144                        } catch (InstallerException ignored) {
9145                        }
9146                    }
9147                }
9148            }
9149        }
9150    }
9151
9152    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9153        synchronized (mPackages) {
9154            mResolverReplaced = true;
9155            // Set up information for custom user intent resolution activity.
9156            mResolveActivity.applicationInfo = pkg.applicationInfo;
9157            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9158            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9159            mResolveActivity.processName = pkg.applicationInfo.packageName;
9160            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9161            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9162                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9163            mResolveActivity.theme = 0;
9164            mResolveActivity.exported = true;
9165            mResolveActivity.enabled = true;
9166            mResolveInfo.activityInfo = mResolveActivity;
9167            mResolveInfo.priority = 0;
9168            mResolveInfo.preferredOrder = 0;
9169            mResolveInfo.match = 0;
9170            mResolveComponentName = mCustomResolverComponentName;
9171            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9172                    mResolveComponentName);
9173        }
9174    }
9175
9176    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9177        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9178
9179        // Set up information for ephemeral installer activity
9180        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9181        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9182        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9183        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9184        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9185        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9186                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9187        mEphemeralInstallerActivity.theme = 0;
9188        mEphemeralInstallerActivity.exported = true;
9189        mEphemeralInstallerActivity.enabled = true;
9190        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9191        mEphemeralInstallerInfo.priority = 0;
9192        mEphemeralInstallerInfo.preferredOrder = 0;
9193        mEphemeralInstallerInfo.match = 0;
9194
9195        if (DEBUG_EPHEMERAL) {
9196            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9197        }
9198    }
9199
9200    private static String calculateBundledApkRoot(final String codePathString) {
9201        final File codePath = new File(codePathString);
9202        final File codeRoot;
9203        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9204            codeRoot = Environment.getRootDirectory();
9205        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9206            codeRoot = Environment.getOemDirectory();
9207        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9208            codeRoot = Environment.getVendorDirectory();
9209        } else {
9210            // Unrecognized code path; take its top real segment as the apk root:
9211            // e.g. /something/app/blah.apk => /something
9212            try {
9213                File f = codePath.getCanonicalFile();
9214                File parent = f.getParentFile();    // non-null because codePath is a file
9215                File tmp;
9216                while ((tmp = parent.getParentFile()) != null) {
9217                    f = parent;
9218                    parent = tmp;
9219                }
9220                codeRoot = f;
9221                Slog.w(TAG, "Unrecognized code path "
9222                        + codePath + " - using " + codeRoot);
9223            } catch (IOException e) {
9224                // Can't canonicalize the code path -- shenanigans?
9225                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9226                return Environment.getRootDirectory().getPath();
9227            }
9228        }
9229        return codeRoot.getPath();
9230    }
9231
9232    /**
9233     * Derive and set the location of native libraries for the given package,
9234     * which varies depending on where and how the package was installed.
9235     */
9236    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9237        final ApplicationInfo info = pkg.applicationInfo;
9238        final String codePath = pkg.codePath;
9239        final File codeFile = new File(codePath);
9240        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9241        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9242
9243        info.nativeLibraryRootDir = null;
9244        info.nativeLibraryRootRequiresIsa = false;
9245        info.nativeLibraryDir = null;
9246        info.secondaryNativeLibraryDir = null;
9247
9248        if (isApkFile(codeFile)) {
9249            // Monolithic install
9250            if (bundledApp) {
9251                // If "/system/lib64/apkname" exists, assume that is the per-package
9252                // native library directory to use; otherwise use "/system/lib/apkname".
9253                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9254                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9255                        getPrimaryInstructionSet(info));
9256
9257                // This is a bundled system app so choose the path based on the ABI.
9258                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9259                // is just the default path.
9260                final String apkName = deriveCodePathName(codePath);
9261                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9262                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9263                        apkName).getAbsolutePath();
9264
9265                if (info.secondaryCpuAbi != null) {
9266                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9267                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9268                            secondaryLibDir, apkName).getAbsolutePath();
9269                }
9270            } else if (asecApp) {
9271                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9272                        .getAbsolutePath();
9273            } else {
9274                final String apkName = deriveCodePathName(codePath);
9275                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9276                        .getAbsolutePath();
9277            }
9278
9279            info.nativeLibraryRootRequiresIsa = false;
9280            info.nativeLibraryDir = info.nativeLibraryRootDir;
9281        } else {
9282            // Cluster install
9283            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9284            info.nativeLibraryRootRequiresIsa = true;
9285
9286            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9287                    getPrimaryInstructionSet(info)).getAbsolutePath();
9288
9289            if (info.secondaryCpuAbi != null) {
9290                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9291                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9292            }
9293        }
9294    }
9295
9296    /**
9297     * Calculate the abis and roots for a bundled app. These can uniquely
9298     * be determined from the contents of the system partition, i.e whether
9299     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9300     * of this information, and instead assume that the system was built
9301     * sensibly.
9302     */
9303    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9304                                           PackageSetting pkgSetting) {
9305        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9306
9307        // If "/system/lib64/apkname" exists, assume that is the per-package
9308        // native library directory to use; otherwise use "/system/lib/apkname".
9309        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9310        setBundledAppAbi(pkg, apkRoot, apkName);
9311        // pkgSetting might be null during rescan following uninstall of updates
9312        // to a bundled app, so accommodate that possibility.  The settings in
9313        // that case will be established later from the parsed package.
9314        //
9315        // If the settings aren't null, sync them up with what we've just derived.
9316        // note that apkRoot isn't stored in the package settings.
9317        if (pkgSetting != null) {
9318            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9319            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9320        }
9321    }
9322
9323    /**
9324     * Deduces the ABI of a bundled app and sets the relevant fields on the
9325     * parsed pkg object.
9326     *
9327     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9328     *        under which system libraries are installed.
9329     * @param apkName the name of the installed package.
9330     */
9331    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9332        final File codeFile = new File(pkg.codePath);
9333
9334        final boolean has64BitLibs;
9335        final boolean has32BitLibs;
9336        if (isApkFile(codeFile)) {
9337            // Monolithic install
9338            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9339            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9340        } else {
9341            // Cluster install
9342            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9343            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9344                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9345                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9346                has64BitLibs = (new File(rootDir, isa)).exists();
9347            } else {
9348                has64BitLibs = false;
9349            }
9350            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9351                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9352                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9353                has32BitLibs = (new File(rootDir, isa)).exists();
9354            } else {
9355                has32BitLibs = false;
9356            }
9357        }
9358
9359        if (has64BitLibs && !has32BitLibs) {
9360            // The package has 64 bit libs, but not 32 bit libs. Its primary
9361            // ABI should be 64 bit. We can safely assume here that the bundled
9362            // native libraries correspond to the most preferred ABI in the list.
9363
9364            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9365            pkg.applicationInfo.secondaryCpuAbi = null;
9366        } else if (has32BitLibs && !has64BitLibs) {
9367            // The package has 32 bit libs but not 64 bit libs. Its primary
9368            // ABI should be 32 bit.
9369
9370            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9371            pkg.applicationInfo.secondaryCpuAbi = null;
9372        } else if (has32BitLibs && has64BitLibs) {
9373            // The application has both 64 and 32 bit bundled libraries. We check
9374            // here that the app declares multiArch support, and warn if it doesn't.
9375            //
9376            // We will be lenient here and record both ABIs. The primary will be the
9377            // ABI that's higher on the list, i.e, a device that's configured to prefer
9378            // 64 bit apps will see a 64 bit primary ABI,
9379
9380            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9381                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9382            }
9383
9384            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9385                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9386                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9387            } else {
9388                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9389                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9390            }
9391        } else {
9392            pkg.applicationInfo.primaryCpuAbi = null;
9393            pkg.applicationInfo.secondaryCpuAbi = null;
9394        }
9395    }
9396
9397    private void killApplication(String pkgName, int appId, String reason) {
9398        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9399    }
9400
9401    private void killApplication(String pkgName, int appId, int userId, String reason) {
9402        // Request the ActivityManager to kill the process(only for existing packages)
9403        // so that we do not end up in a confused state while the user is still using the older
9404        // version of the application while the new one gets installed.
9405        final long token = Binder.clearCallingIdentity();
9406        try {
9407            IActivityManager am = ActivityManagerNative.getDefault();
9408            if (am != null) {
9409                try {
9410                    am.killApplication(pkgName, appId, userId, reason);
9411                } catch (RemoteException e) {
9412                }
9413            }
9414        } finally {
9415            Binder.restoreCallingIdentity(token);
9416        }
9417    }
9418
9419    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9420        // Remove the parent package setting
9421        PackageSetting ps = (PackageSetting) pkg.mExtras;
9422        if (ps != null) {
9423            removePackageLI(ps, chatty);
9424        }
9425        // Remove the child package setting
9426        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9427        for (int i = 0; i < childCount; i++) {
9428            PackageParser.Package childPkg = pkg.childPackages.get(i);
9429            ps = (PackageSetting) childPkg.mExtras;
9430            if (ps != null) {
9431                removePackageLI(ps, chatty);
9432            }
9433        }
9434    }
9435
9436    void removePackageLI(PackageSetting ps, boolean chatty) {
9437        if (DEBUG_INSTALL) {
9438            if (chatty)
9439                Log.d(TAG, "Removing package " + ps.name);
9440        }
9441
9442        // writer
9443        synchronized (mPackages) {
9444            mPackages.remove(ps.name);
9445            final PackageParser.Package pkg = ps.pkg;
9446            if (pkg != null) {
9447                cleanPackageDataStructuresLILPw(pkg, chatty);
9448            }
9449        }
9450    }
9451
9452    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9453        if (DEBUG_INSTALL) {
9454            if (chatty)
9455                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9456        }
9457
9458        // writer
9459        synchronized (mPackages) {
9460            // Remove the parent package
9461            mPackages.remove(pkg.applicationInfo.packageName);
9462            cleanPackageDataStructuresLILPw(pkg, chatty);
9463
9464            // Remove the child packages
9465            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9466            for (int i = 0; i < childCount; i++) {
9467                PackageParser.Package childPkg = pkg.childPackages.get(i);
9468                mPackages.remove(childPkg.applicationInfo.packageName);
9469                cleanPackageDataStructuresLILPw(childPkg, chatty);
9470            }
9471        }
9472    }
9473
9474    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9475        int N = pkg.providers.size();
9476        StringBuilder r = null;
9477        int i;
9478        for (i=0; i<N; i++) {
9479            PackageParser.Provider p = pkg.providers.get(i);
9480            mProviders.removeProvider(p);
9481            if (p.info.authority == null) {
9482
9483                /* There was another ContentProvider with this authority when
9484                 * this app was installed so this authority is null,
9485                 * Ignore it as we don't have to unregister the provider.
9486                 */
9487                continue;
9488            }
9489            String names[] = p.info.authority.split(";");
9490            for (int j = 0; j < names.length; j++) {
9491                if (mProvidersByAuthority.get(names[j]) == p) {
9492                    mProvidersByAuthority.remove(names[j]);
9493                    if (DEBUG_REMOVE) {
9494                        if (chatty)
9495                            Log.d(TAG, "Unregistered content provider: " + names[j]
9496                                    + ", className = " + p.info.name + ", isSyncable = "
9497                                    + p.info.isSyncable);
9498                    }
9499                }
9500            }
9501            if (DEBUG_REMOVE && chatty) {
9502                if (r == null) {
9503                    r = new StringBuilder(256);
9504                } else {
9505                    r.append(' ');
9506                }
9507                r.append(p.info.name);
9508            }
9509        }
9510        if (r != null) {
9511            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9512        }
9513
9514        N = pkg.services.size();
9515        r = null;
9516        for (i=0; i<N; i++) {
9517            PackageParser.Service s = pkg.services.get(i);
9518            mServices.removeService(s);
9519            if (chatty) {
9520                if (r == null) {
9521                    r = new StringBuilder(256);
9522                } else {
9523                    r.append(' ');
9524                }
9525                r.append(s.info.name);
9526            }
9527        }
9528        if (r != null) {
9529            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9530        }
9531
9532        N = pkg.receivers.size();
9533        r = null;
9534        for (i=0; i<N; i++) {
9535            PackageParser.Activity a = pkg.receivers.get(i);
9536            mReceivers.removeActivity(a, "receiver");
9537            if (DEBUG_REMOVE && chatty) {
9538                if (r == null) {
9539                    r = new StringBuilder(256);
9540                } else {
9541                    r.append(' ');
9542                }
9543                r.append(a.info.name);
9544            }
9545        }
9546        if (r != null) {
9547            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9548        }
9549
9550        N = pkg.activities.size();
9551        r = null;
9552        for (i=0; i<N; i++) {
9553            PackageParser.Activity a = pkg.activities.get(i);
9554            mActivities.removeActivity(a, "activity");
9555            if (DEBUG_REMOVE && chatty) {
9556                if (r == null) {
9557                    r = new StringBuilder(256);
9558                } else {
9559                    r.append(' ');
9560                }
9561                r.append(a.info.name);
9562            }
9563        }
9564        if (r != null) {
9565            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9566        }
9567
9568        N = pkg.permissions.size();
9569        r = null;
9570        for (i=0; i<N; i++) {
9571            PackageParser.Permission p = pkg.permissions.get(i);
9572            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9573            if (bp == null) {
9574                bp = mSettings.mPermissionTrees.get(p.info.name);
9575            }
9576            if (bp != null && bp.perm == p) {
9577                bp.perm = null;
9578                if (DEBUG_REMOVE && chatty) {
9579                    if (r == null) {
9580                        r = new StringBuilder(256);
9581                    } else {
9582                        r.append(' ');
9583                    }
9584                    r.append(p.info.name);
9585                }
9586            }
9587            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9588                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9589                if (appOpPkgs != null) {
9590                    appOpPkgs.remove(pkg.packageName);
9591                }
9592            }
9593        }
9594        if (r != null) {
9595            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9596        }
9597
9598        N = pkg.requestedPermissions.size();
9599        r = null;
9600        for (i=0; i<N; i++) {
9601            String perm = pkg.requestedPermissions.get(i);
9602            BasePermission bp = mSettings.mPermissions.get(perm);
9603            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9604                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9605                if (appOpPkgs != null) {
9606                    appOpPkgs.remove(pkg.packageName);
9607                    if (appOpPkgs.isEmpty()) {
9608                        mAppOpPermissionPackages.remove(perm);
9609                    }
9610                }
9611            }
9612        }
9613        if (r != null) {
9614            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9615        }
9616
9617        N = pkg.instrumentation.size();
9618        r = null;
9619        for (i=0; i<N; i++) {
9620            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9621            mInstrumentation.remove(a.getComponentName());
9622            if (DEBUG_REMOVE && chatty) {
9623                if (r == null) {
9624                    r = new StringBuilder(256);
9625                } else {
9626                    r.append(' ');
9627                }
9628                r.append(a.info.name);
9629            }
9630        }
9631        if (r != null) {
9632            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9633        }
9634
9635        r = null;
9636        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9637            // Only system apps can hold shared libraries.
9638            if (pkg.libraryNames != null) {
9639                for (i=0; i<pkg.libraryNames.size(); i++) {
9640                    String name = pkg.libraryNames.get(i);
9641                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9642                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9643                        mSharedLibraries.remove(name);
9644                        if (DEBUG_REMOVE && chatty) {
9645                            if (r == null) {
9646                                r = new StringBuilder(256);
9647                            } else {
9648                                r.append(' ');
9649                            }
9650                            r.append(name);
9651                        }
9652                    }
9653                }
9654            }
9655        }
9656        if (r != null) {
9657            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9658        }
9659    }
9660
9661    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9662        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9663            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9664                return true;
9665            }
9666        }
9667        return false;
9668    }
9669
9670    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9671    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9672    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9673
9674    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9675        // Update the parent permissions
9676        updatePermissionsLPw(pkg.packageName, pkg, flags);
9677        // Update the child permissions
9678        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9679        for (int i = 0; i < childCount; i++) {
9680            PackageParser.Package childPkg = pkg.childPackages.get(i);
9681            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9682        }
9683    }
9684
9685    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9686            int flags) {
9687        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9688        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9689    }
9690
9691    private void updatePermissionsLPw(String changingPkg,
9692            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9693        // Make sure there are no dangling permission trees.
9694        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9695        while (it.hasNext()) {
9696            final BasePermission bp = it.next();
9697            if (bp.packageSetting == null) {
9698                // We may not yet have parsed the package, so just see if
9699                // we still know about its settings.
9700                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9701            }
9702            if (bp.packageSetting == null) {
9703                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9704                        + " from package " + bp.sourcePackage);
9705                it.remove();
9706            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9707                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9708                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9709                            + " from package " + bp.sourcePackage);
9710                    flags |= UPDATE_PERMISSIONS_ALL;
9711                    it.remove();
9712                }
9713            }
9714        }
9715
9716        // Make sure all dynamic permissions have been assigned to a package,
9717        // and make sure there are no dangling permissions.
9718        it = mSettings.mPermissions.values().iterator();
9719        while (it.hasNext()) {
9720            final BasePermission bp = it.next();
9721            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9722                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9723                        + bp.name + " pkg=" + bp.sourcePackage
9724                        + " info=" + bp.pendingInfo);
9725                if (bp.packageSetting == null && bp.pendingInfo != null) {
9726                    final BasePermission tree = findPermissionTreeLP(bp.name);
9727                    if (tree != null && tree.perm != null) {
9728                        bp.packageSetting = tree.packageSetting;
9729                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9730                                new PermissionInfo(bp.pendingInfo));
9731                        bp.perm.info.packageName = tree.perm.info.packageName;
9732                        bp.perm.info.name = bp.name;
9733                        bp.uid = tree.uid;
9734                    }
9735                }
9736            }
9737            if (bp.packageSetting == null) {
9738                // We may not yet have parsed the package, so just see if
9739                // we still know about its settings.
9740                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9741            }
9742            if (bp.packageSetting == null) {
9743                Slog.w(TAG, "Removing dangling permission: " + bp.name
9744                        + " from package " + bp.sourcePackage);
9745                it.remove();
9746            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9747                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9748                    Slog.i(TAG, "Removing old permission: " + bp.name
9749                            + " from package " + bp.sourcePackage);
9750                    flags |= UPDATE_PERMISSIONS_ALL;
9751                    it.remove();
9752                }
9753            }
9754        }
9755
9756        // Now update the permissions for all packages, in particular
9757        // replace the granted permissions of the system packages.
9758        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9759            for (PackageParser.Package pkg : mPackages.values()) {
9760                if (pkg != pkgInfo) {
9761                    // Only replace for packages on requested volume
9762                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9763                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9764                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9765                    grantPermissionsLPw(pkg, replace, changingPkg);
9766                }
9767            }
9768        }
9769
9770        if (pkgInfo != null) {
9771            // Only replace for packages on requested volume
9772            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9773            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9774                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9775            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9776        }
9777    }
9778
9779    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9780            String packageOfInterest) {
9781        // IMPORTANT: There are two types of permissions: install and runtime.
9782        // Install time permissions are granted when the app is installed to
9783        // all device users and users added in the future. Runtime permissions
9784        // are granted at runtime explicitly to specific users. Normal and signature
9785        // protected permissions are install time permissions. Dangerous permissions
9786        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9787        // otherwise they are runtime permissions. This function does not manage
9788        // runtime permissions except for the case an app targeting Lollipop MR1
9789        // being upgraded to target a newer SDK, in which case dangerous permissions
9790        // are transformed from install time to runtime ones.
9791
9792        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9793        if (ps == null) {
9794            return;
9795        }
9796
9797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9798
9799        PermissionsState permissionsState = ps.getPermissionsState();
9800        PermissionsState origPermissions = permissionsState;
9801
9802        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9803
9804        boolean runtimePermissionsRevoked = false;
9805        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9806
9807        boolean changedInstallPermission = false;
9808
9809        if (replace) {
9810            ps.installPermissionsFixed = false;
9811            if (!ps.isSharedUser()) {
9812                origPermissions = new PermissionsState(permissionsState);
9813                permissionsState.reset();
9814            } else {
9815                // We need to know only about runtime permission changes since the
9816                // calling code always writes the install permissions state but
9817                // the runtime ones are written only if changed. The only cases of
9818                // changed runtime permissions here are promotion of an install to
9819                // runtime and revocation of a runtime from a shared user.
9820                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9821                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9822                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9823                    runtimePermissionsRevoked = true;
9824                }
9825            }
9826        }
9827
9828        permissionsState.setGlobalGids(mGlobalGids);
9829
9830        final int N = pkg.requestedPermissions.size();
9831        for (int i=0; i<N; i++) {
9832            final String name = pkg.requestedPermissions.get(i);
9833            final BasePermission bp = mSettings.mPermissions.get(name);
9834
9835            if (DEBUG_INSTALL) {
9836                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9837            }
9838
9839            if (bp == null || bp.packageSetting == null) {
9840                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9841                    Slog.w(TAG, "Unknown permission " + name
9842                            + " in package " + pkg.packageName);
9843                }
9844                continue;
9845            }
9846
9847            final String perm = bp.name;
9848            boolean allowedSig = false;
9849            int grant = GRANT_DENIED;
9850
9851            // Keep track of app op permissions.
9852            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9853                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9854                if (pkgs == null) {
9855                    pkgs = new ArraySet<>();
9856                    mAppOpPermissionPackages.put(bp.name, pkgs);
9857                }
9858                pkgs.add(pkg.packageName);
9859            }
9860
9861            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9862            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9863                    >= Build.VERSION_CODES.M;
9864            switch (level) {
9865                case PermissionInfo.PROTECTION_NORMAL: {
9866                    // For all apps normal permissions are install time ones.
9867                    grant = GRANT_INSTALL;
9868                } break;
9869
9870                case PermissionInfo.PROTECTION_DANGEROUS: {
9871                    // If a permission review is required for legacy apps we represent
9872                    // their permissions as always granted runtime ones since we need
9873                    // to keep the review required permission flag per user while an
9874                    // install permission's state is shared across all users.
9875                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
9876                            && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9877                        // For legacy apps dangerous permissions are install time ones.
9878                        grant = GRANT_INSTALL;
9879                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9880                        // For legacy apps that became modern, install becomes runtime.
9881                        grant = GRANT_UPGRADE;
9882                    } else if (mPromoteSystemApps
9883                            && isSystemApp(ps)
9884                            && mExistingSystemPackages.contains(ps.name)) {
9885                        // For legacy system apps, install becomes runtime.
9886                        // We cannot check hasInstallPermission() for system apps since those
9887                        // permissions were granted implicitly and not persisted pre-M.
9888                        grant = GRANT_UPGRADE;
9889                    } else {
9890                        // For modern apps keep runtime permissions unchanged.
9891                        grant = GRANT_RUNTIME;
9892                    }
9893                } break;
9894
9895                case PermissionInfo.PROTECTION_SIGNATURE: {
9896                    // For all apps signature permissions are install time ones.
9897                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9898                    if (allowedSig) {
9899                        grant = GRANT_INSTALL;
9900                    }
9901                } break;
9902            }
9903
9904            if (DEBUG_INSTALL) {
9905                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9906            }
9907
9908            if (grant != GRANT_DENIED) {
9909                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9910                    // If this is an existing, non-system package, then
9911                    // we can't add any new permissions to it.
9912                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9913                        // Except...  if this is a permission that was added
9914                        // to the platform (note: need to only do this when
9915                        // updating the platform).
9916                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9917                            grant = GRANT_DENIED;
9918                        }
9919                    }
9920                }
9921
9922                switch (grant) {
9923                    case GRANT_INSTALL: {
9924                        // Revoke this as runtime permission to handle the case of
9925                        // a runtime permission being downgraded to an install one.
9926                        // Also in permission review mode we keep dangerous permissions
9927                        // for legacy apps
9928                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9929                            if (origPermissions.getRuntimePermissionState(
9930                                    bp.name, userId) != null) {
9931                                // Revoke the runtime permission and clear the flags.
9932                                origPermissions.revokeRuntimePermission(bp, userId);
9933                                origPermissions.updatePermissionFlags(bp, userId,
9934                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9935                                // If we revoked a permission permission, we have to write.
9936                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9937                                        changedRuntimePermissionUserIds, userId);
9938                            }
9939                        }
9940                        // Grant an install permission.
9941                        if (permissionsState.grantInstallPermission(bp) !=
9942                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9943                            changedInstallPermission = true;
9944                        }
9945                    } break;
9946
9947                    case GRANT_RUNTIME: {
9948                        // Grant previously granted runtime permissions.
9949                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9950                            PermissionState permissionState = origPermissions
9951                                    .getRuntimePermissionState(bp.name, userId);
9952                            int flags = permissionState != null
9953                                    ? permissionState.getFlags() : 0;
9954                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9955                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9956                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9957                                    // If we cannot put the permission as it was, we have to write.
9958                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9959                                            changedRuntimePermissionUserIds, userId);
9960                                }
9961                                // If the app supports runtime permissions no need for a review.
9962                                if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
9963                                        && appSupportsRuntimePermissions
9964                                        && (flags & PackageManager
9965                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9966                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9967                                    // Since we changed the flags, we have to write.
9968                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9969                                            changedRuntimePermissionUserIds, userId);
9970                                }
9971                            } else if ((mPermissionReviewRequired
9972                                        || Build.PERMISSIONS_REVIEW_REQUIRED)
9973                                    && !appSupportsRuntimePermissions) {
9974                                // For legacy apps that need a permission review, every new
9975                                // runtime permission is granted but it is pending a review.
9976                                // We also need to review only platform defined runtime
9977                                // permissions as these are the only ones the platform knows
9978                                // how to disable the API to simulate revocation as legacy
9979                                // apps don't expect to run with revoked permissions.
9980                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9981                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9982                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9983                                        // We changed the flags, hence have to write.
9984                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9985                                                changedRuntimePermissionUserIds, userId);
9986                                    }
9987                                }
9988                                if (permissionsState.grantRuntimePermission(bp, userId)
9989                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9990                                    // We changed the permission, hence have to write.
9991                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9992                                            changedRuntimePermissionUserIds, userId);
9993                                }
9994                            }
9995                            // Propagate the permission flags.
9996                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9997                        }
9998                    } break;
9999
10000                    case GRANT_UPGRADE: {
10001                        // Grant runtime permissions for a previously held install permission.
10002                        PermissionState permissionState = origPermissions
10003                                .getInstallPermissionState(bp.name);
10004                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10005
10006                        if (origPermissions.revokeInstallPermission(bp)
10007                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10008                            // We will be transferring the permission flags, so clear them.
10009                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10010                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10011                            changedInstallPermission = true;
10012                        }
10013
10014                        // If the permission is not to be promoted to runtime we ignore it and
10015                        // also its other flags as they are not applicable to install permissions.
10016                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10017                            for (int userId : currentUserIds) {
10018                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10019                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10020                                    // Transfer the permission flags.
10021                                    permissionsState.updatePermissionFlags(bp, userId,
10022                                            flags, flags);
10023                                    // If we granted the permission, we have to write.
10024                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10025                                            changedRuntimePermissionUserIds, userId);
10026                                }
10027                            }
10028                        }
10029                    } break;
10030
10031                    default: {
10032                        if (packageOfInterest == null
10033                                || packageOfInterest.equals(pkg.packageName)) {
10034                            Slog.w(TAG, "Not granting permission " + perm
10035                                    + " to package " + pkg.packageName
10036                                    + " because it was previously installed without");
10037                        }
10038                    } break;
10039                }
10040            } else {
10041                if (permissionsState.revokeInstallPermission(bp) !=
10042                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10043                    // Also drop the permission flags.
10044                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10045                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10046                    changedInstallPermission = true;
10047                    Slog.i(TAG, "Un-granting permission " + perm
10048                            + " from package " + pkg.packageName
10049                            + " (protectionLevel=" + bp.protectionLevel
10050                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10051                            + ")");
10052                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10053                    // Don't print warning for app op permissions, since it is fine for them
10054                    // not to be granted, there is a UI for the user to decide.
10055                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10056                        Slog.w(TAG, "Not granting permission " + perm
10057                                + " to package " + pkg.packageName
10058                                + " (protectionLevel=" + bp.protectionLevel
10059                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10060                                + ")");
10061                    }
10062                }
10063            }
10064        }
10065
10066        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10067                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10068            // This is the first that we have heard about this package, so the
10069            // permissions we have now selected are fixed until explicitly
10070            // changed.
10071            ps.installPermissionsFixed = true;
10072        }
10073
10074        // Persist the runtime permissions state for users with changes. If permissions
10075        // were revoked because no app in the shared user declares them we have to
10076        // write synchronously to avoid losing runtime permissions state.
10077        for (int userId : changedRuntimePermissionUserIds) {
10078            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10079        }
10080
10081        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10082    }
10083
10084    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10085        boolean allowed = false;
10086        final int NP = PackageParser.NEW_PERMISSIONS.length;
10087        for (int ip=0; ip<NP; ip++) {
10088            final PackageParser.NewPermissionInfo npi
10089                    = PackageParser.NEW_PERMISSIONS[ip];
10090            if (npi.name.equals(perm)
10091                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10092                allowed = true;
10093                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10094                        + pkg.packageName);
10095                break;
10096            }
10097        }
10098        return allowed;
10099    }
10100
10101    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10102            BasePermission bp, PermissionsState origPermissions) {
10103        boolean allowed;
10104        allowed = (compareSignatures(
10105                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10106                        == PackageManager.SIGNATURE_MATCH)
10107                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10108                        == PackageManager.SIGNATURE_MATCH);
10109        if (!allowed && (bp.protectionLevel
10110                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10111            if (isSystemApp(pkg)) {
10112                // For updated system applications, a system permission
10113                // is granted only if it had been defined by the original application.
10114                if (pkg.isUpdatedSystemApp()) {
10115                    final PackageSetting sysPs = mSettings
10116                            .getDisabledSystemPkgLPr(pkg.packageName);
10117                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10118                        // If the original was granted this permission, we take
10119                        // that grant decision as read and propagate it to the
10120                        // update.
10121                        if (sysPs.isPrivileged()) {
10122                            allowed = true;
10123                        }
10124                    } else {
10125                        // The system apk may have been updated with an older
10126                        // version of the one on the data partition, but which
10127                        // granted a new system permission that it didn't have
10128                        // before.  In this case we do want to allow the app to
10129                        // now get the new permission if the ancestral apk is
10130                        // privileged to get it.
10131                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10132                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10133                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10134                                    allowed = true;
10135                                    break;
10136                                }
10137                            }
10138                        }
10139                        // Also if a privileged parent package on the system image or any of
10140                        // its children requested a privileged permission, the updated child
10141                        // packages can also get the permission.
10142                        if (pkg.parentPackage != null) {
10143                            final PackageSetting disabledSysParentPs = mSettings
10144                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10145                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10146                                    && disabledSysParentPs.isPrivileged()) {
10147                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10148                                    allowed = true;
10149                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10150                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10151                                    for (int i = 0; i < count; i++) {
10152                                        PackageParser.Package disabledSysChildPkg =
10153                                                disabledSysParentPs.pkg.childPackages.get(i);
10154                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10155                                                perm)) {
10156                                            allowed = true;
10157                                            break;
10158                                        }
10159                                    }
10160                                }
10161                            }
10162                        }
10163                    }
10164                } else {
10165                    allowed = isPrivilegedApp(pkg);
10166                }
10167            }
10168        }
10169        if (!allowed) {
10170            if (!allowed && (bp.protectionLevel
10171                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10172                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10173                // If this was a previously normal/dangerous permission that got moved
10174                // to a system permission as part of the runtime permission redesign, then
10175                // we still want to blindly grant it to old apps.
10176                allowed = true;
10177            }
10178            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10179                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10180                // If this permission is to be granted to the system installer and
10181                // this app is an installer, then it gets the permission.
10182                allowed = true;
10183            }
10184            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10185                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10186                // If this permission is to be granted to the system verifier and
10187                // this app is a verifier, then it gets the permission.
10188                allowed = true;
10189            }
10190            if (!allowed && (bp.protectionLevel
10191                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10192                    && isSystemApp(pkg)) {
10193                // Any pre-installed system app is allowed to get this permission.
10194                allowed = true;
10195            }
10196            if (!allowed && (bp.protectionLevel
10197                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10198                // For development permissions, a development permission
10199                // is granted only if it was already granted.
10200                allowed = origPermissions.hasInstallPermission(perm);
10201            }
10202            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10203                    && pkg.packageName.equals(mSetupWizardPackage)) {
10204                // If this permission is to be granted to the system setup wizard and
10205                // this app is a setup wizard, then it gets the permission.
10206                allowed = true;
10207            }
10208        }
10209        return allowed;
10210    }
10211
10212    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10213        final int permCount = pkg.requestedPermissions.size();
10214        for (int j = 0; j < permCount; j++) {
10215            String requestedPermission = pkg.requestedPermissions.get(j);
10216            if (permission.equals(requestedPermission)) {
10217                return true;
10218            }
10219        }
10220        return false;
10221    }
10222
10223    final class ActivityIntentResolver
10224            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10225        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10226                boolean defaultOnly, int userId) {
10227            if (!sUserManager.exists(userId)) return null;
10228            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10229            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10230        }
10231
10232        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10233                int userId) {
10234            if (!sUserManager.exists(userId)) return null;
10235            mFlags = flags;
10236            return super.queryIntent(intent, resolvedType,
10237                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10238        }
10239
10240        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10241                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10242            if (!sUserManager.exists(userId)) return null;
10243            if (packageActivities == null) {
10244                return null;
10245            }
10246            mFlags = flags;
10247            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10248            final int N = packageActivities.size();
10249            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10250                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10251
10252            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10253            for (int i = 0; i < N; ++i) {
10254                intentFilters = packageActivities.get(i).intents;
10255                if (intentFilters != null && intentFilters.size() > 0) {
10256                    PackageParser.ActivityIntentInfo[] array =
10257                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10258                    intentFilters.toArray(array);
10259                    listCut.add(array);
10260                }
10261            }
10262            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10263        }
10264
10265        /**
10266         * Finds a privileged activity that matches the specified activity names.
10267         */
10268        private PackageParser.Activity findMatchingActivity(
10269                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10270            for (PackageParser.Activity sysActivity : activityList) {
10271                if (sysActivity.info.name.equals(activityInfo.name)) {
10272                    return sysActivity;
10273                }
10274                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10275                    return sysActivity;
10276                }
10277                if (sysActivity.info.targetActivity != null) {
10278                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10279                        return sysActivity;
10280                    }
10281                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10282                        return sysActivity;
10283                    }
10284                }
10285            }
10286            return null;
10287        }
10288
10289        public class IterGenerator<E> {
10290            public Iterator<E> generate(ActivityIntentInfo info) {
10291                return null;
10292            }
10293        }
10294
10295        public class ActionIterGenerator extends IterGenerator<String> {
10296            @Override
10297            public Iterator<String> generate(ActivityIntentInfo info) {
10298                return info.actionsIterator();
10299            }
10300        }
10301
10302        public class CategoriesIterGenerator extends IterGenerator<String> {
10303            @Override
10304            public Iterator<String> generate(ActivityIntentInfo info) {
10305                return info.categoriesIterator();
10306            }
10307        }
10308
10309        public class SchemesIterGenerator extends IterGenerator<String> {
10310            @Override
10311            public Iterator<String> generate(ActivityIntentInfo info) {
10312                return info.schemesIterator();
10313            }
10314        }
10315
10316        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10317            @Override
10318            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10319                return info.authoritiesIterator();
10320            }
10321        }
10322
10323        /**
10324         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10325         * MODIFIED. Do not pass in a list that should not be changed.
10326         */
10327        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10328                IterGenerator<T> generator, Iterator<T> searchIterator) {
10329            // loop through the set of actions; every one must be found in the intent filter
10330            while (searchIterator.hasNext()) {
10331                // we must have at least one filter in the list to consider a match
10332                if (intentList.size() == 0) {
10333                    break;
10334                }
10335
10336                final T searchAction = searchIterator.next();
10337
10338                // loop through the set of intent filters
10339                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10340                while (intentIter.hasNext()) {
10341                    final ActivityIntentInfo intentInfo = intentIter.next();
10342                    boolean selectionFound = false;
10343
10344                    // loop through the intent filter's selection criteria; at least one
10345                    // of them must match the searched criteria
10346                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10347                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10348                        final T intentSelection = intentSelectionIter.next();
10349                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10350                            selectionFound = true;
10351                            break;
10352                        }
10353                    }
10354
10355                    // the selection criteria wasn't found in this filter's set; this filter
10356                    // is not a potential match
10357                    if (!selectionFound) {
10358                        intentIter.remove();
10359                    }
10360                }
10361            }
10362        }
10363
10364        private boolean isProtectedAction(ActivityIntentInfo filter) {
10365            final Iterator<String> actionsIter = filter.actionsIterator();
10366            while (actionsIter != null && actionsIter.hasNext()) {
10367                final String filterAction = actionsIter.next();
10368                if (PROTECTED_ACTIONS.contains(filterAction)) {
10369                    return true;
10370                }
10371            }
10372            return false;
10373        }
10374
10375        /**
10376         * Adjusts the priority of the given intent filter according to policy.
10377         * <p>
10378         * <ul>
10379         * <li>The priority for non privileged applications is capped to '0'</li>
10380         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10381         * <li>The priority for unbundled updates to privileged applications is capped to the
10382         *      priority defined on the system partition</li>
10383         * </ul>
10384         * <p>
10385         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10386         * allowed to obtain any priority on any action.
10387         */
10388        private void adjustPriority(
10389                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10390            // nothing to do; priority is fine as-is
10391            if (intent.getPriority() <= 0) {
10392                return;
10393            }
10394
10395            final ActivityInfo activityInfo = intent.activity.info;
10396            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10397
10398            final boolean privilegedApp =
10399                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10400            if (!privilegedApp) {
10401                // non-privileged applications can never define a priority >0
10402                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10403                        + " package: " + applicationInfo.packageName
10404                        + " activity: " + intent.activity.className
10405                        + " origPrio: " + intent.getPriority());
10406                intent.setPriority(0);
10407                return;
10408            }
10409
10410            if (systemActivities == null) {
10411                // the system package is not disabled; we're parsing the system partition
10412                if (isProtectedAction(intent)) {
10413                    if (mDeferProtectedFilters) {
10414                        // We can't deal with these just yet. No component should ever obtain a
10415                        // >0 priority for a protected actions, with ONE exception -- the setup
10416                        // wizard. The setup wizard, however, cannot be known until we're able to
10417                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10418                        // until all intent filters have been processed. Chicken, meet egg.
10419                        // Let the filter temporarily have a high priority and rectify the
10420                        // priorities after all system packages have been scanned.
10421                        mProtectedFilters.add(intent);
10422                        if (DEBUG_FILTERS) {
10423                            Slog.i(TAG, "Protected action; save for later;"
10424                                    + " package: " + applicationInfo.packageName
10425                                    + " activity: " + intent.activity.className
10426                                    + " origPrio: " + intent.getPriority());
10427                        }
10428                        return;
10429                    } else {
10430                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10431                            Slog.i(TAG, "No setup wizard;"
10432                                + " All protected intents capped to priority 0");
10433                        }
10434                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10435                            if (DEBUG_FILTERS) {
10436                                Slog.i(TAG, "Found setup wizard;"
10437                                    + " allow priority " + intent.getPriority() + ";"
10438                                    + " package: " + intent.activity.info.packageName
10439                                    + " activity: " + intent.activity.className
10440                                    + " priority: " + intent.getPriority());
10441                            }
10442                            // setup wizard gets whatever it wants
10443                            return;
10444                        }
10445                        Slog.w(TAG, "Protected action; cap priority to 0;"
10446                                + " package: " + intent.activity.info.packageName
10447                                + " activity: " + intent.activity.className
10448                                + " origPrio: " + intent.getPriority());
10449                        intent.setPriority(0);
10450                        return;
10451                    }
10452                }
10453                // privileged apps on the system image get whatever priority they request
10454                return;
10455            }
10456
10457            // privileged app unbundled update ... try to find the same activity
10458            final PackageParser.Activity foundActivity =
10459                    findMatchingActivity(systemActivities, activityInfo);
10460            if (foundActivity == null) {
10461                // this is a new activity; it cannot obtain >0 priority
10462                if (DEBUG_FILTERS) {
10463                    Slog.i(TAG, "New activity; cap priority to 0;"
10464                            + " package: " + applicationInfo.packageName
10465                            + " activity: " + intent.activity.className
10466                            + " origPrio: " + intent.getPriority());
10467                }
10468                intent.setPriority(0);
10469                return;
10470            }
10471
10472            // found activity, now check for filter equivalence
10473
10474            // a shallow copy is enough; we modify the list, not its contents
10475            final List<ActivityIntentInfo> intentListCopy =
10476                    new ArrayList<>(foundActivity.intents);
10477            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10478
10479            // find matching action subsets
10480            final Iterator<String> actionsIterator = intent.actionsIterator();
10481            if (actionsIterator != null) {
10482                getIntentListSubset(
10483                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10484                if (intentListCopy.size() == 0) {
10485                    // no more intents to match; we're not equivalent
10486                    if (DEBUG_FILTERS) {
10487                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10488                                + " package: " + applicationInfo.packageName
10489                                + " activity: " + intent.activity.className
10490                                + " origPrio: " + intent.getPriority());
10491                    }
10492                    intent.setPriority(0);
10493                    return;
10494                }
10495            }
10496
10497            // find matching category subsets
10498            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10499            if (categoriesIterator != null) {
10500                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10501                        categoriesIterator);
10502                if (intentListCopy.size() == 0) {
10503                    // no more intents to match; we're not equivalent
10504                    if (DEBUG_FILTERS) {
10505                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10506                                + " package: " + applicationInfo.packageName
10507                                + " activity: " + intent.activity.className
10508                                + " origPrio: " + intent.getPriority());
10509                    }
10510                    intent.setPriority(0);
10511                    return;
10512                }
10513            }
10514
10515            // find matching schemes subsets
10516            final Iterator<String> schemesIterator = intent.schemesIterator();
10517            if (schemesIterator != null) {
10518                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10519                        schemesIterator);
10520                if (intentListCopy.size() == 0) {
10521                    // no more intents to match; we're not equivalent
10522                    if (DEBUG_FILTERS) {
10523                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10524                                + " package: " + applicationInfo.packageName
10525                                + " activity: " + intent.activity.className
10526                                + " origPrio: " + intent.getPriority());
10527                    }
10528                    intent.setPriority(0);
10529                    return;
10530                }
10531            }
10532
10533            // find matching authorities subsets
10534            final Iterator<IntentFilter.AuthorityEntry>
10535                    authoritiesIterator = intent.authoritiesIterator();
10536            if (authoritiesIterator != null) {
10537                getIntentListSubset(intentListCopy,
10538                        new AuthoritiesIterGenerator(),
10539                        authoritiesIterator);
10540                if (intentListCopy.size() == 0) {
10541                    // no more intents to match; we're not equivalent
10542                    if (DEBUG_FILTERS) {
10543                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10544                                + " package: " + applicationInfo.packageName
10545                                + " activity: " + intent.activity.className
10546                                + " origPrio: " + intent.getPriority());
10547                    }
10548                    intent.setPriority(0);
10549                    return;
10550                }
10551            }
10552
10553            // we found matching filter(s); app gets the max priority of all intents
10554            int cappedPriority = 0;
10555            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10556                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10557            }
10558            if (intent.getPriority() > cappedPriority) {
10559                if (DEBUG_FILTERS) {
10560                    Slog.i(TAG, "Found matching filter(s);"
10561                            + " cap priority to " + cappedPriority + ";"
10562                            + " package: " + applicationInfo.packageName
10563                            + " activity: " + intent.activity.className
10564                            + " origPrio: " + intent.getPriority());
10565                }
10566                intent.setPriority(cappedPriority);
10567                return;
10568            }
10569            // all this for nothing; the requested priority was <= what was on the system
10570        }
10571
10572        public final void addActivity(PackageParser.Activity a, String type) {
10573            mActivities.put(a.getComponentName(), a);
10574            if (DEBUG_SHOW_INFO)
10575                Log.v(
10576                TAG, "  " + type + " " +
10577                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10578            if (DEBUG_SHOW_INFO)
10579                Log.v(TAG, "    Class=" + a.info.name);
10580            final int NI = a.intents.size();
10581            for (int j=0; j<NI; j++) {
10582                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10583                if ("activity".equals(type)) {
10584                    final PackageSetting ps =
10585                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10586                    final List<PackageParser.Activity> systemActivities =
10587                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10588                    adjustPriority(systemActivities, intent);
10589                }
10590                if (DEBUG_SHOW_INFO) {
10591                    Log.v(TAG, "    IntentFilter:");
10592                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10593                }
10594                if (!intent.debugCheck()) {
10595                    Log.w(TAG, "==> For Activity " + a.info.name);
10596                }
10597                addFilter(intent);
10598            }
10599        }
10600
10601        public final void removeActivity(PackageParser.Activity a, String type) {
10602            mActivities.remove(a.getComponentName());
10603            if (DEBUG_SHOW_INFO) {
10604                Log.v(TAG, "  " + type + " "
10605                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10606                                : a.info.name) + ":");
10607                Log.v(TAG, "    Class=" + a.info.name);
10608            }
10609            final int NI = a.intents.size();
10610            for (int j=0; j<NI; j++) {
10611                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10612                if (DEBUG_SHOW_INFO) {
10613                    Log.v(TAG, "    IntentFilter:");
10614                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10615                }
10616                removeFilter(intent);
10617            }
10618        }
10619
10620        @Override
10621        protected boolean allowFilterResult(
10622                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10623            ActivityInfo filterAi = filter.activity.info;
10624            for (int i=dest.size()-1; i>=0; i--) {
10625                ActivityInfo destAi = dest.get(i).activityInfo;
10626                if (destAi.name == filterAi.name
10627                        && destAi.packageName == filterAi.packageName) {
10628                    return false;
10629                }
10630            }
10631            return true;
10632        }
10633
10634        @Override
10635        protected ActivityIntentInfo[] newArray(int size) {
10636            return new ActivityIntentInfo[size];
10637        }
10638
10639        @Override
10640        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10641            if (!sUserManager.exists(userId)) return true;
10642            PackageParser.Package p = filter.activity.owner;
10643            if (p != null) {
10644                PackageSetting ps = (PackageSetting)p.mExtras;
10645                if (ps != null) {
10646                    // System apps are never considered stopped for purposes of
10647                    // filtering, because there may be no way for the user to
10648                    // actually re-launch them.
10649                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10650                            && ps.getStopped(userId);
10651                }
10652            }
10653            return false;
10654        }
10655
10656        @Override
10657        protected boolean isPackageForFilter(String packageName,
10658                PackageParser.ActivityIntentInfo info) {
10659            return packageName.equals(info.activity.owner.packageName);
10660        }
10661
10662        @Override
10663        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10664                int match, int userId) {
10665            if (!sUserManager.exists(userId)) return null;
10666            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10667                return null;
10668            }
10669            final PackageParser.Activity activity = info.activity;
10670            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10671            if (ps == null) {
10672                return null;
10673            }
10674            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10675                    ps.readUserState(userId), userId);
10676            if (ai == null) {
10677                return null;
10678            }
10679            final ResolveInfo res = new ResolveInfo();
10680            res.activityInfo = ai;
10681            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10682                res.filter = info;
10683            }
10684            if (info != null) {
10685                res.handleAllWebDataURI = info.handleAllWebDataURI();
10686            }
10687            res.priority = info.getPriority();
10688            res.preferredOrder = activity.owner.mPreferredOrder;
10689            //System.out.println("Result: " + res.activityInfo.className +
10690            //                   " = " + res.priority);
10691            res.match = match;
10692            res.isDefault = info.hasDefault;
10693            res.labelRes = info.labelRes;
10694            res.nonLocalizedLabel = info.nonLocalizedLabel;
10695            if (userNeedsBadging(userId)) {
10696                res.noResourceId = true;
10697            } else {
10698                res.icon = info.icon;
10699            }
10700            res.iconResourceId = info.icon;
10701            res.system = res.activityInfo.applicationInfo.isSystemApp();
10702            return res;
10703        }
10704
10705        @Override
10706        protected void sortResults(List<ResolveInfo> results) {
10707            Collections.sort(results, mResolvePrioritySorter);
10708        }
10709
10710        @Override
10711        protected void dumpFilter(PrintWriter out, String prefix,
10712                PackageParser.ActivityIntentInfo filter) {
10713            out.print(prefix); out.print(
10714                    Integer.toHexString(System.identityHashCode(filter.activity)));
10715                    out.print(' ');
10716                    filter.activity.printComponentShortName(out);
10717                    out.print(" filter ");
10718                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10719        }
10720
10721        @Override
10722        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10723            return filter.activity;
10724        }
10725
10726        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10727            PackageParser.Activity activity = (PackageParser.Activity)label;
10728            out.print(prefix); out.print(
10729                    Integer.toHexString(System.identityHashCode(activity)));
10730                    out.print(' ');
10731                    activity.printComponentShortName(out);
10732            if (count > 1) {
10733                out.print(" ("); out.print(count); out.print(" filters)");
10734            }
10735            out.println();
10736        }
10737
10738        // Keys are String (activity class name), values are Activity.
10739        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10740                = new ArrayMap<ComponentName, PackageParser.Activity>();
10741        private int mFlags;
10742    }
10743
10744    private final class ServiceIntentResolver
10745            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10746        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10747                boolean defaultOnly, int userId) {
10748            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10749            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10750        }
10751
10752        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10753                int userId) {
10754            if (!sUserManager.exists(userId)) return null;
10755            mFlags = flags;
10756            return super.queryIntent(intent, resolvedType,
10757                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10758        }
10759
10760        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10761                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10762            if (!sUserManager.exists(userId)) return null;
10763            if (packageServices == null) {
10764                return null;
10765            }
10766            mFlags = flags;
10767            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10768            final int N = packageServices.size();
10769            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10770                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10771
10772            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10773            for (int i = 0; i < N; ++i) {
10774                intentFilters = packageServices.get(i).intents;
10775                if (intentFilters != null && intentFilters.size() > 0) {
10776                    PackageParser.ServiceIntentInfo[] array =
10777                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10778                    intentFilters.toArray(array);
10779                    listCut.add(array);
10780                }
10781            }
10782            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10783        }
10784
10785        public final void addService(PackageParser.Service s) {
10786            mServices.put(s.getComponentName(), s);
10787            if (DEBUG_SHOW_INFO) {
10788                Log.v(TAG, "  "
10789                        + (s.info.nonLocalizedLabel != null
10790                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10791                Log.v(TAG, "    Class=" + s.info.name);
10792            }
10793            final int NI = s.intents.size();
10794            int j;
10795            for (j=0; j<NI; j++) {
10796                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10797                if (DEBUG_SHOW_INFO) {
10798                    Log.v(TAG, "    IntentFilter:");
10799                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10800                }
10801                if (!intent.debugCheck()) {
10802                    Log.w(TAG, "==> For Service " + s.info.name);
10803                }
10804                addFilter(intent);
10805            }
10806        }
10807
10808        public final void removeService(PackageParser.Service s) {
10809            mServices.remove(s.getComponentName());
10810            if (DEBUG_SHOW_INFO) {
10811                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10812                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10813                Log.v(TAG, "    Class=" + s.info.name);
10814            }
10815            final int NI = s.intents.size();
10816            int j;
10817            for (j=0; j<NI; j++) {
10818                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10819                if (DEBUG_SHOW_INFO) {
10820                    Log.v(TAG, "    IntentFilter:");
10821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10822                }
10823                removeFilter(intent);
10824            }
10825        }
10826
10827        @Override
10828        protected boolean allowFilterResult(
10829                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10830            ServiceInfo filterSi = filter.service.info;
10831            for (int i=dest.size()-1; i>=0; i--) {
10832                ServiceInfo destAi = dest.get(i).serviceInfo;
10833                if (destAi.name == filterSi.name
10834                        && destAi.packageName == filterSi.packageName) {
10835                    return false;
10836                }
10837            }
10838            return true;
10839        }
10840
10841        @Override
10842        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10843            return new PackageParser.ServiceIntentInfo[size];
10844        }
10845
10846        @Override
10847        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10848            if (!sUserManager.exists(userId)) return true;
10849            PackageParser.Package p = filter.service.owner;
10850            if (p != null) {
10851                PackageSetting ps = (PackageSetting)p.mExtras;
10852                if (ps != null) {
10853                    // System apps are never considered stopped for purposes of
10854                    // filtering, because there may be no way for the user to
10855                    // actually re-launch them.
10856                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10857                            && ps.getStopped(userId);
10858                }
10859            }
10860            return false;
10861        }
10862
10863        @Override
10864        protected boolean isPackageForFilter(String packageName,
10865                PackageParser.ServiceIntentInfo info) {
10866            return packageName.equals(info.service.owner.packageName);
10867        }
10868
10869        @Override
10870        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10871                int match, int userId) {
10872            if (!sUserManager.exists(userId)) return null;
10873            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10874            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10875                return null;
10876            }
10877            final PackageParser.Service service = info.service;
10878            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10879            if (ps == null) {
10880                return null;
10881            }
10882            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10883                    ps.readUserState(userId), userId);
10884            if (si == null) {
10885                return null;
10886            }
10887            final ResolveInfo res = new ResolveInfo();
10888            res.serviceInfo = si;
10889            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10890                res.filter = filter;
10891            }
10892            res.priority = info.getPriority();
10893            res.preferredOrder = service.owner.mPreferredOrder;
10894            res.match = match;
10895            res.isDefault = info.hasDefault;
10896            res.labelRes = info.labelRes;
10897            res.nonLocalizedLabel = info.nonLocalizedLabel;
10898            res.icon = info.icon;
10899            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10900            return res;
10901        }
10902
10903        @Override
10904        protected void sortResults(List<ResolveInfo> results) {
10905            Collections.sort(results, mResolvePrioritySorter);
10906        }
10907
10908        @Override
10909        protected void dumpFilter(PrintWriter out, String prefix,
10910                PackageParser.ServiceIntentInfo filter) {
10911            out.print(prefix); out.print(
10912                    Integer.toHexString(System.identityHashCode(filter.service)));
10913                    out.print(' ');
10914                    filter.service.printComponentShortName(out);
10915                    out.print(" filter ");
10916                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10917        }
10918
10919        @Override
10920        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10921            return filter.service;
10922        }
10923
10924        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10925            PackageParser.Service service = (PackageParser.Service)label;
10926            out.print(prefix); out.print(
10927                    Integer.toHexString(System.identityHashCode(service)));
10928                    out.print(' ');
10929                    service.printComponentShortName(out);
10930            if (count > 1) {
10931                out.print(" ("); out.print(count); out.print(" filters)");
10932            }
10933            out.println();
10934        }
10935
10936//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10937//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10938//            final List<ResolveInfo> retList = Lists.newArrayList();
10939//            while (i.hasNext()) {
10940//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10941//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10942//                    retList.add(resolveInfo);
10943//                }
10944//            }
10945//            return retList;
10946//        }
10947
10948        // Keys are String (activity class name), values are Activity.
10949        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10950                = new ArrayMap<ComponentName, PackageParser.Service>();
10951        private int mFlags;
10952    };
10953
10954    private final class ProviderIntentResolver
10955            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10957                boolean defaultOnly, int userId) {
10958            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10959            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10960        }
10961
10962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10963                int userId) {
10964            if (!sUserManager.exists(userId))
10965                return null;
10966            mFlags = flags;
10967            return super.queryIntent(intent, resolvedType,
10968                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10969        }
10970
10971        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10972                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10973            if (!sUserManager.exists(userId))
10974                return null;
10975            if (packageProviders == null) {
10976                return null;
10977            }
10978            mFlags = flags;
10979            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10980            final int N = packageProviders.size();
10981            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10982                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10983
10984            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10985            for (int i = 0; i < N; ++i) {
10986                intentFilters = packageProviders.get(i).intents;
10987                if (intentFilters != null && intentFilters.size() > 0) {
10988                    PackageParser.ProviderIntentInfo[] array =
10989                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10990                    intentFilters.toArray(array);
10991                    listCut.add(array);
10992                }
10993            }
10994            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10995        }
10996
10997        public final void addProvider(PackageParser.Provider p) {
10998            if (mProviders.containsKey(p.getComponentName())) {
10999                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11000                return;
11001            }
11002
11003            mProviders.put(p.getComponentName(), p);
11004            if (DEBUG_SHOW_INFO) {
11005                Log.v(TAG, "  "
11006                        + (p.info.nonLocalizedLabel != null
11007                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11008                Log.v(TAG, "    Class=" + p.info.name);
11009            }
11010            final int NI = p.intents.size();
11011            int j;
11012            for (j = 0; j < NI; j++) {
11013                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11014                if (DEBUG_SHOW_INFO) {
11015                    Log.v(TAG, "    IntentFilter:");
11016                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11017                }
11018                if (!intent.debugCheck()) {
11019                    Log.w(TAG, "==> For Provider " + p.info.name);
11020                }
11021                addFilter(intent);
11022            }
11023        }
11024
11025        public final void removeProvider(PackageParser.Provider p) {
11026            mProviders.remove(p.getComponentName());
11027            if (DEBUG_SHOW_INFO) {
11028                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11029                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11030                Log.v(TAG, "    Class=" + p.info.name);
11031            }
11032            final int NI = p.intents.size();
11033            int j;
11034            for (j = 0; j < NI; j++) {
11035                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11036                if (DEBUG_SHOW_INFO) {
11037                    Log.v(TAG, "    IntentFilter:");
11038                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11039                }
11040                removeFilter(intent);
11041            }
11042        }
11043
11044        @Override
11045        protected boolean allowFilterResult(
11046                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11047            ProviderInfo filterPi = filter.provider.info;
11048            for (int i = dest.size() - 1; i >= 0; i--) {
11049                ProviderInfo destPi = dest.get(i).providerInfo;
11050                if (destPi.name == filterPi.name
11051                        && destPi.packageName == filterPi.packageName) {
11052                    return false;
11053                }
11054            }
11055            return true;
11056        }
11057
11058        @Override
11059        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11060            return new PackageParser.ProviderIntentInfo[size];
11061        }
11062
11063        @Override
11064        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11065            if (!sUserManager.exists(userId))
11066                return true;
11067            PackageParser.Package p = filter.provider.owner;
11068            if (p != null) {
11069                PackageSetting ps = (PackageSetting) p.mExtras;
11070                if (ps != null) {
11071                    // System apps are never considered stopped for purposes of
11072                    // filtering, because there may be no way for the user to
11073                    // actually re-launch them.
11074                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11075                            && ps.getStopped(userId);
11076                }
11077            }
11078            return false;
11079        }
11080
11081        @Override
11082        protected boolean isPackageForFilter(String packageName,
11083                PackageParser.ProviderIntentInfo info) {
11084            return packageName.equals(info.provider.owner.packageName);
11085        }
11086
11087        @Override
11088        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11089                int match, int userId) {
11090            if (!sUserManager.exists(userId))
11091                return null;
11092            final PackageParser.ProviderIntentInfo info = filter;
11093            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11094                return null;
11095            }
11096            final PackageParser.Provider provider = info.provider;
11097            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11098            if (ps == null) {
11099                return null;
11100            }
11101            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11102                    ps.readUserState(userId), userId);
11103            if (pi == null) {
11104                return null;
11105            }
11106            final ResolveInfo res = new ResolveInfo();
11107            res.providerInfo = pi;
11108            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11109                res.filter = filter;
11110            }
11111            res.priority = info.getPriority();
11112            res.preferredOrder = provider.owner.mPreferredOrder;
11113            res.match = match;
11114            res.isDefault = info.hasDefault;
11115            res.labelRes = info.labelRes;
11116            res.nonLocalizedLabel = info.nonLocalizedLabel;
11117            res.icon = info.icon;
11118            res.system = res.providerInfo.applicationInfo.isSystemApp();
11119            return res;
11120        }
11121
11122        @Override
11123        protected void sortResults(List<ResolveInfo> results) {
11124            Collections.sort(results, mResolvePrioritySorter);
11125        }
11126
11127        @Override
11128        protected void dumpFilter(PrintWriter out, String prefix,
11129                PackageParser.ProviderIntentInfo filter) {
11130            out.print(prefix);
11131            out.print(
11132                    Integer.toHexString(System.identityHashCode(filter.provider)));
11133            out.print(' ');
11134            filter.provider.printComponentShortName(out);
11135            out.print(" filter ");
11136            out.println(Integer.toHexString(System.identityHashCode(filter)));
11137        }
11138
11139        @Override
11140        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11141            return filter.provider;
11142        }
11143
11144        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11145            PackageParser.Provider provider = (PackageParser.Provider)label;
11146            out.print(prefix); out.print(
11147                    Integer.toHexString(System.identityHashCode(provider)));
11148                    out.print(' ');
11149                    provider.printComponentShortName(out);
11150            if (count > 1) {
11151                out.print(" ("); out.print(count); out.print(" filters)");
11152            }
11153            out.println();
11154        }
11155
11156        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11157                = new ArrayMap<ComponentName, PackageParser.Provider>();
11158        private int mFlags;
11159    }
11160
11161    private static final class EphemeralIntentResolver
11162            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11163        @Override
11164        protected EphemeralResolveIntentInfo[] newArray(int size) {
11165            return new EphemeralResolveIntentInfo[size];
11166        }
11167
11168        @Override
11169        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11170            return true;
11171        }
11172
11173        @Override
11174        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11175                int userId) {
11176            if (!sUserManager.exists(userId)) {
11177                return null;
11178            }
11179            return info.getEphemeralResolveInfo();
11180        }
11181    }
11182
11183    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11184            new Comparator<ResolveInfo>() {
11185        public int compare(ResolveInfo r1, ResolveInfo r2) {
11186            int v1 = r1.priority;
11187            int v2 = r2.priority;
11188            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11189            if (v1 != v2) {
11190                return (v1 > v2) ? -1 : 1;
11191            }
11192            v1 = r1.preferredOrder;
11193            v2 = r2.preferredOrder;
11194            if (v1 != v2) {
11195                return (v1 > v2) ? -1 : 1;
11196            }
11197            if (r1.isDefault != r2.isDefault) {
11198                return r1.isDefault ? -1 : 1;
11199            }
11200            v1 = r1.match;
11201            v2 = r2.match;
11202            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11203            if (v1 != v2) {
11204                return (v1 > v2) ? -1 : 1;
11205            }
11206            if (r1.system != r2.system) {
11207                return r1.system ? -1 : 1;
11208            }
11209            if (r1.activityInfo != null) {
11210                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11211            }
11212            if (r1.serviceInfo != null) {
11213                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11214            }
11215            if (r1.providerInfo != null) {
11216                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11217            }
11218            return 0;
11219        }
11220    };
11221
11222    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11223            new Comparator<ProviderInfo>() {
11224        public int compare(ProviderInfo p1, ProviderInfo p2) {
11225            final int v1 = p1.initOrder;
11226            final int v2 = p2.initOrder;
11227            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11228        }
11229    };
11230
11231    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11232            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11233            final int[] userIds) {
11234        mHandler.post(new Runnable() {
11235            @Override
11236            public void run() {
11237                try {
11238                    final IActivityManager am = ActivityManagerNative.getDefault();
11239                    if (am == null) return;
11240                    final int[] resolvedUserIds;
11241                    if (userIds == null) {
11242                        resolvedUserIds = am.getRunningUserIds();
11243                    } else {
11244                        resolvedUserIds = userIds;
11245                    }
11246                    for (int id : resolvedUserIds) {
11247                        final Intent intent = new Intent(action,
11248                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11249                        if (extras != null) {
11250                            intent.putExtras(extras);
11251                        }
11252                        if (targetPkg != null) {
11253                            intent.setPackage(targetPkg);
11254                        }
11255                        // Modify the UID when posting to other users
11256                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11257                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11258                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11259                            intent.putExtra(Intent.EXTRA_UID, uid);
11260                        }
11261                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11262                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11263                        if (DEBUG_BROADCASTS) {
11264                            RuntimeException here = new RuntimeException("here");
11265                            here.fillInStackTrace();
11266                            Slog.d(TAG, "Sending to user " + id + ": "
11267                                    + intent.toShortString(false, true, false, false)
11268                                    + " " + intent.getExtras(), here);
11269                        }
11270                        am.broadcastIntent(null, intent, null, finishedReceiver,
11271                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11272                                null, finishedReceiver != null, false, id);
11273                    }
11274                } catch (RemoteException ex) {
11275                }
11276            }
11277        });
11278    }
11279
11280    /**
11281     * Check if the external storage media is available. This is true if there
11282     * is a mounted external storage medium or if the external storage is
11283     * emulated.
11284     */
11285    private boolean isExternalMediaAvailable() {
11286        return mMediaMounted || Environment.isExternalStorageEmulated();
11287    }
11288
11289    @Override
11290    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11291        // writer
11292        synchronized (mPackages) {
11293            if (!isExternalMediaAvailable()) {
11294                // If the external storage is no longer mounted at this point,
11295                // the caller may not have been able to delete all of this
11296                // packages files and can not delete any more.  Bail.
11297                return null;
11298            }
11299            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11300            if (lastPackage != null) {
11301                pkgs.remove(lastPackage);
11302            }
11303            if (pkgs.size() > 0) {
11304                return pkgs.get(0);
11305            }
11306        }
11307        return null;
11308    }
11309
11310    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11311        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11312                userId, andCode ? 1 : 0, packageName);
11313        if (mSystemReady) {
11314            msg.sendToTarget();
11315        } else {
11316            if (mPostSystemReadyMessages == null) {
11317                mPostSystemReadyMessages = new ArrayList<>();
11318            }
11319            mPostSystemReadyMessages.add(msg);
11320        }
11321    }
11322
11323    void startCleaningPackages() {
11324        // reader
11325        if (!isExternalMediaAvailable()) {
11326            return;
11327        }
11328        synchronized (mPackages) {
11329            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11330                return;
11331            }
11332        }
11333        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11334        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11335        IActivityManager am = ActivityManagerNative.getDefault();
11336        if (am != null) {
11337            try {
11338                am.startService(null, intent, null, mContext.getOpPackageName(),
11339                        UserHandle.USER_SYSTEM);
11340            } catch (RemoteException e) {
11341            }
11342        }
11343    }
11344
11345    @Override
11346    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11347            int installFlags, String installerPackageName, int userId) {
11348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11349
11350        final int callingUid = Binder.getCallingUid();
11351        enforceCrossUserPermission(callingUid, userId,
11352                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11353
11354        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11355            try {
11356                if (observer != null) {
11357                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11358                }
11359            } catch (RemoteException re) {
11360            }
11361            return;
11362        }
11363
11364        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11365            installFlags |= PackageManager.INSTALL_FROM_ADB;
11366
11367        } else {
11368            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11369            // about installerPackageName.
11370
11371            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11372            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11373        }
11374
11375        UserHandle user;
11376        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11377            user = UserHandle.ALL;
11378        } else {
11379            user = new UserHandle(userId);
11380        }
11381
11382        // Only system components can circumvent runtime permissions when installing.
11383        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11384                && mContext.checkCallingOrSelfPermission(Manifest.permission
11385                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11386            throw new SecurityException("You need the "
11387                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11388                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11389        }
11390
11391        final File originFile = new File(originPath);
11392        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11393
11394        final Message msg = mHandler.obtainMessage(INIT_COPY);
11395        final VerificationInfo verificationInfo = new VerificationInfo(
11396                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11397        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11398                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11399                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11400                null /*certificates*/);
11401        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11402        msg.obj = params;
11403
11404        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11405                System.identityHashCode(msg.obj));
11406        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11407                System.identityHashCode(msg.obj));
11408
11409        mHandler.sendMessage(msg);
11410    }
11411
11412    void installStage(String packageName, File stagedDir, String stagedCid,
11413            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11414            String installerPackageName, int installerUid, UserHandle user,
11415            Certificate[][] certificates) {
11416        if (DEBUG_EPHEMERAL) {
11417            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11418                Slog.d(TAG, "Ephemeral install of " + packageName);
11419            }
11420        }
11421        final VerificationInfo verificationInfo = new VerificationInfo(
11422                sessionParams.originatingUri, sessionParams.referrerUri,
11423                sessionParams.originatingUid, installerUid);
11424
11425        final OriginInfo origin;
11426        if (stagedDir != null) {
11427            origin = OriginInfo.fromStagedFile(stagedDir);
11428        } else {
11429            origin = OriginInfo.fromStagedContainer(stagedCid);
11430        }
11431
11432        final Message msg = mHandler.obtainMessage(INIT_COPY);
11433        final InstallParams params = new InstallParams(origin, null, observer,
11434                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11435                verificationInfo, user, sessionParams.abiOverride,
11436                sessionParams.grantedRuntimePermissions, certificates);
11437        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11438        msg.obj = params;
11439
11440        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11441                System.identityHashCode(msg.obj));
11442        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11443                System.identityHashCode(msg.obj));
11444
11445        mHandler.sendMessage(msg);
11446    }
11447
11448    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11449            int userId) {
11450        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11451        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11452    }
11453
11454    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11455            int appId, int userId) {
11456        Bundle extras = new Bundle(1);
11457        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11458
11459        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11460                packageName, extras, 0, null, null, new int[] {userId});
11461        try {
11462            IActivityManager am = ActivityManagerNative.getDefault();
11463            if (isSystem && am.isUserRunning(userId, 0)) {
11464                // The just-installed/enabled app is bundled on the system, so presumed
11465                // to be able to run automatically without needing an explicit launch.
11466                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11467                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11468                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11469                        .setPackage(packageName);
11470                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11471                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11472            }
11473        } catch (RemoteException e) {
11474            // shouldn't happen
11475            Slog.w(TAG, "Unable to bootstrap installed package", e);
11476        }
11477    }
11478
11479    @Override
11480    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11481            int userId) {
11482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11483        PackageSetting pkgSetting;
11484        final int uid = Binder.getCallingUid();
11485        enforceCrossUserPermission(uid, userId,
11486                true /* requireFullPermission */, true /* checkShell */,
11487                "setApplicationHiddenSetting for user " + userId);
11488
11489        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11490            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11491            return false;
11492        }
11493
11494        long callingId = Binder.clearCallingIdentity();
11495        try {
11496            boolean sendAdded = false;
11497            boolean sendRemoved = false;
11498            // writer
11499            synchronized (mPackages) {
11500                pkgSetting = mSettings.mPackages.get(packageName);
11501                if (pkgSetting == null) {
11502                    return false;
11503                }
11504                if (pkgSetting.getHidden(userId) != hidden) {
11505                    pkgSetting.setHidden(hidden, userId);
11506                    mSettings.writePackageRestrictionsLPr(userId);
11507                    if (hidden) {
11508                        sendRemoved = true;
11509                    } else {
11510                        sendAdded = true;
11511                    }
11512                }
11513            }
11514            if (sendAdded) {
11515                sendPackageAddedForUser(packageName, pkgSetting, userId);
11516                return true;
11517            }
11518            if (sendRemoved) {
11519                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11520                        "hiding pkg");
11521                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11522                return true;
11523            }
11524        } finally {
11525            Binder.restoreCallingIdentity(callingId);
11526        }
11527        return false;
11528    }
11529
11530    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11531            int userId) {
11532        final PackageRemovedInfo info = new PackageRemovedInfo();
11533        info.removedPackage = packageName;
11534        info.removedUsers = new int[] {userId};
11535        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11536        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11537    }
11538
11539    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11540        if (pkgList.length > 0) {
11541            Bundle extras = new Bundle(1);
11542            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11543
11544            sendPackageBroadcast(
11545                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11546                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11547                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11548                    new int[] {userId});
11549        }
11550    }
11551
11552    /**
11553     * Returns true if application is not found or there was an error. Otherwise it returns
11554     * the hidden state of the package for the given user.
11555     */
11556    @Override
11557    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11559        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11560                true /* requireFullPermission */, false /* checkShell */,
11561                "getApplicationHidden for user " + userId);
11562        PackageSetting pkgSetting;
11563        long callingId = Binder.clearCallingIdentity();
11564        try {
11565            // writer
11566            synchronized (mPackages) {
11567                pkgSetting = mSettings.mPackages.get(packageName);
11568                if (pkgSetting == null) {
11569                    return true;
11570                }
11571                return pkgSetting.getHidden(userId);
11572            }
11573        } finally {
11574            Binder.restoreCallingIdentity(callingId);
11575        }
11576    }
11577
11578    /**
11579     * @hide
11580     */
11581    @Override
11582    public int installExistingPackageAsUser(String packageName, int userId) {
11583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11584                null);
11585        PackageSetting pkgSetting;
11586        final int uid = Binder.getCallingUid();
11587        enforceCrossUserPermission(uid, userId,
11588                true /* requireFullPermission */, true /* checkShell */,
11589                "installExistingPackage for user " + userId);
11590        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11591            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11592        }
11593
11594        long callingId = Binder.clearCallingIdentity();
11595        try {
11596            boolean installed = false;
11597
11598            // writer
11599            synchronized (mPackages) {
11600                pkgSetting = mSettings.mPackages.get(packageName);
11601                if (pkgSetting == null) {
11602                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11603                }
11604                if (!pkgSetting.getInstalled(userId)) {
11605                    pkgSetting.setInstalled(true, userId);
11606                    pkgSetting.setHidden(false, userId);
11607                    mSettings.writePackageRestrictionsLPr(userId);
11608                    installed = true;
11609                }
11610            }
11611
11612            if (installed) {
11613                if (pkgSetting.pkg != null) {
11614                    synchronized (mInstallLock) {
11615                        // We don't need to freeze for a brand new install
11616                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11617                    }
11618                }
11619                sendPackageAddedForUser(packageName, pkgSetting, userId);
11620            }
11621        } finally {
11622            Binder.restoreCallingIdentity(callingId);
11623        }
11624
11625        return PackageManager.INSTALL_SUCCEEDED;
11626    }
11627
11628    boolean isUserRestricted(int userId, String restrictionKey) {
11629        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11630        if (restrictions.getBoolean(restrictionKey, false)) {
11631            Log.w(TAG, "User is restricted: " + restrictionKey);
11632            return true;
11633        }
11634        return false;
11635    }
11636
11637    @Override
11638    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11639            int userId) {
11640        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11642                true /* requireFullPermission */, true /* checkShell */,
11643                "setPackagesSuspended for user " + userId);
11644
11645        if (ArrayUtils.isEmpty(packageNames)) {
11646            return packageNames;
11647        }
11648
11649        // List of package names for whom the suspended state has changed.
11650        List<String> changedPackages = new ArrayList<>(packageNames.length);
11651        // List of package names for whom the suspended state is not set as requested in this
11652        // method.
11653        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11654        long callingId = Binder.clearCallingIdentity();
11655        try {
11656            for (int i = 0; i < packageNames.length; i++) {
11657                String packageName = packageNames[i];
11658                boolean changed = false;
11659                final int appId;
11660                synchronized (mPackages) {
11661                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11662                    if (pkgSetting == null) {
11663                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11664                                + "\". Skipping suspending/un-suspending.");
11665                        unactionedPackages.add(packageName);
11666                        continue;
11667                    }
11668                    appId = pkgSetting.appId;
11669                    if (pkgSetting.getSuspended(userId) != suspended) {
11670                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11671                            unactionedPackages.add(packageName);
11672                            continue;
11673                        }
11674                        pkgSetting.setSuspended(suspended, userId);
11675                        mSettings.writePackageRestrictionsLPr(userId);
11676                        changed = true;
11677                        changedPackages.add(packageName);
11678                    }
11679                }
11680
11681                if (changed && suspended) {
11682                    killApplication(packageName, UserHandle.getUid(userId, appId),
11683                            "suspending package");
11684                }
11685            }
11686        } finally {
11687            Binder.restoreCallingIdentity(callingId);
11688        }
11689
11690        if (!changedPackages.isEmpty()) {
11691            sendPackagesSuspendedForUser(changedPackages.toArray(
11692                    new String[changedPackages.size()]), userId, suspended);
11693        }
11694
11695        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11696    }
11697
11698    @Override
11699    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11701                true /* requireFullPermission */, false /* checkShell */,
11702                "isPackageSuspendedForUser for user " + userId);
11703        synchronized (mPackages) {
11704            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11705            if (pkgSetting == null) {
11706                throw new IllegalArgumentException("Unknown target package: " + packageName);
11707            }
11708            return pkgSetting.getSuspended(userId);
11709        }
11710    }
11711
11712    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11713        if (isPackageDeviceAdmin(packageName, userId)) {
11714            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11715                    + "\": has an active device admin");
11716            return false;
11717        }
11718
11719        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11720        if (packageName.equals(activeLauncherPackageName)) {
11721            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11722                    + "\": contains the active launcher");
11723            return false;
11724        }
11725
11726        if (packageName.equals(mRequiredInstallerPackage)) {
11727            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11728                    + "\": required for package installation");
11729            return false;
11730        }
11731
11732        if (packageName.equals(mRequiredVerifierPackage)) {
11733            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11734                    + "\": required for package verification");
11735            return false;
11736        }
11737
11738        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11739            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11740                    + "\": is the default dialer");
11741            return false;
11742        }
11743
11744        return true;
11745    }
11746
11747    private String getActiveLauncherPackageName(int userId) {
11748        Intent intent = new Intent(Intent.ACTION_MAIN);
11749        intent.addCategory(Intent.CATEGORY_HOME);
11750        ResolveInfo resolveInfo = resolveIntent(
11751                intent,
11752                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11753                PackageManager.MATCH_DEFAULT_ONLY,
11754                userId);
11755
11756        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11757    }
11758
11759    private String getDefaultDialerPackageName(int userId) {
11760        synchronized (mPackages) {
11761            return mSettings.getDefaultDialerPackageNameLPw(userId);
11762        }
11763    }
11764
11765    @Override
11766    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11767        mContext.enforceCallingOrSelfPermission(
11768                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11769                "Only package verification agents can verify applications");
11770
11771        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11772        final PackageVerificationResponse response = new PackageVerificationResponse(
11773                verificationCode, Binder.getCallingUid());
11774        msg.arg1 = id;
11775        msg.obj = response;
11776        mHandler.sendMessage(msg);
11777    }
11778
11779    @Override
11780    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11781            long millisecondsToDelay) {
11782        mContext.enforceCallingOrSelfPermission(
11783                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11784                "Only package verification agents can extend verification timeouts");
11785
11786        final PackageVerificationState state = mPendingVerification.get(id);
11787        final PackageVerificationResponse response = new PackageVerificationResponse(
11788                verificationCodeAtTimeout, Binder.getCallingUid());
11789
11790        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11791            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11792        }
11793        if (millisecondsToDelay < 0) {
11794            millisecondsToDelay = 0;
11795        }
11796        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11797                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11798            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11799        }
11800
11801        if ((state != null) && !state.timeoutExtended()) {
11802            state.extendTimeout();
11803
11804            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11805            msg.arg1 = id;
11806            msg.obj = response;
11807            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11808        }
11809    }
11810
11811    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11812            int verificationCode, UserHandle user) {
11813        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11814        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11815        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11816        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11817        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11818
11819        mContext.sendBroadcastAsUser(intent, user,
11820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11821    }
11822
11823    private ComponentName matchComponentForVerifier(String packageName,
11824            List<ResolveInfo> receivers) {
11825        ActivityInfo targetReceiver = null;
11826
11827        final int NR = receivers.size();
11828        for (int i = 0; i < NR; i++) {
11829            final ResolveInfo info = receivers.get(i);
11830            if (info.activityInfo == null) {
11831                continue;
11832            }
11833
11834            if (packageName.equals(info.activityInfo.packageName)) {
11835                targetReceiver = info.activityInfo;
11836                break;
11837            }
11838        }
11839
11840        if (targetReceiver == null) {
11841            return null;
11842        }
11843
11844        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11845    }
11846
11847    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11848            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11849        if (pkgInfo.verifiers.length == 0) {
11850            return null;
11851        }
11852
11853        final int N = pkgInfo.verifiers.length;
11854        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11855        for (int i = 0; i < N; i++) {
11856            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11857
11858            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11859                    receivers);
11860            if (comp == null) {
11861                continue;
11862            }
11863
11864            final int verifierUid = getUidForVerifier(verifierInfo);
11865            if (verifierUid == -1) {
11866                continue;
11867            }
11868
11869            if (DEBUG_VERIFY) {
11870                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11871                        + " with the correct signature");
11872            }
11873            sufficientVerifiers.add(comp);
11874            verificationState.addSufficientVerifier(verifierUid);
11875        }
11876
11877        return sufficientVerifiers;
11878    }
11879
11880    private int getUidForVerifier(VerifierInfo verifierInfo) {
11881        synchronized (mPackages) {
11882            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11883            if (pkg == null) {
11884                return -1;
11885            } else if (pkg.mSignatures.length != 1) {
11886                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11887                        + " has more than one signature; ignoring");
11888                return -1;
11889            }
11890
11891            /*
11892             * If the public key of the package's signature does not match
11893             * our expected public key, then this is a different package and
11894             * we should skip.
11895             */
11896
11897            final byte[] expectedPublicKey;
11898            try {
11899                final Signature verifierSig = pkg.mSignatures[0];
11900                final PublicKey publicKey = verifierSig.getPublicKey();
11901                expectedPublicKey = publicKey.getEncoded();
11902            } catch (CertificateException e) {
11903                return -1;
11904            }
11905
11906            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11907
11908            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11909                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11910                        + " does not have the expected public key; ignoring");
11911                return -1;
11912            }
11913
11914            return pkg.applicationInfo.uid;
11915        }
11916    }
11917
11918    @Override
11919    public void finishPackageInstall(int token, boolean didLaunch) {
11920        enforceSystemOrRoot("Only the system is allowed to finish installs");
11921
11922        if (DEBUG_INSTALL) {
11923            Slog.v(TAG, "BM finishing package install for " + token);
11924        }
11925        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11926
11927        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11928        mHandler.sendMessage(msg);
11929    }
11930
11931    /**
11932     * Get the verification agent timeout.
11933     *
11934     * @return verification timeout in milliseconds
11935     */
11936    private long getVerificationTimeout() {
11937        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11938                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11939                DEFAULT_VERIFICATION_TIMEOUT);
11940    }
11941
11942    /**
11943     * Get the default verification agent response code.
11944     *
11945     * @return default verification response code
11946     */
11947    private int getDefaultVerificationResponse() {
11948        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11949                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11950                DEFAULT_VERIFICATION_RESPONSE);
11951    }
11952
11953    /**
11954     * Check whether or not package verification has been enabled.
11955     *
11956     * @return true if verification should be performed
11957     */
11958    private boolean isVerificationEnabled(int userId, int installFlags) {
11959        if (!DEFAULT_VERIFY_ENABLE) {
11960            return false;
11961        }
11962        // Ephemeral apps don't get the full verification treatment
11963        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11964            if (DEBUG_EPHEMERAL) {
11965                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11966            }
11967            return false;
11968        }
11969
11970        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11971
11972        // Check if installing from ADB
11973        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11974            // Do not run verification in a test harness environment
11975            if (ActivityManager.isRunningInTestHarness()) {
11976                return false;
11977            }
11978            if (ensureVerifyAppsEnabled) {
11979                return true;
11980            }
11981            // Check if the developer does not want package verification for ADB installs
11982            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11983                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11984                return false;
11985            }
11986        }
11987
11988        if (ensureVerifyAppsEnabled) {
11989            return true;
11990        }
11991
11992        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11993                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11994    }
11995
11996    @Override
11997    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11998            throws RemoteException {
11999        mContext.enforceCallingOrSelfPermission(
12000                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12001                "Only intentfilter verification agents can verify applications");
12002
12003        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12004        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12005                Binder.getCallingUid(), verificationCode, failedDomains);
12006        msg.arg1 = id;
12007        msg.obj = response;
12008        mHandler.sendMessage(msg);
12009    }
12010
12011    @Override
12012    public int getIntentVerificationStatus(String packageName, int userId) {
12013        synchronized (mPackages) {
12014            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12015        }
12016    }
12017
12018    @Override
12019    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12020        mContext.enforceCallingOrSelfPermission(
12021                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12022
12023        boolean result = false;
12024        synchronized (mPackages) {
12025            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12026        }
12027        if (result) {
12028            scheduleWritePackageRestrictionsLocked(userId);
12029        }
12030        return result;
12031    }
12032
12033    @Override
12034    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12035            String packageName) {
12036        synchronized (mPackages) {
12037            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12038        }
12039    }
12040
12041    @Override
12042    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12043        if (TextUtils.isEmpty(packageName)) {
12044            return ParceledListSlice.emptyList();
12045        }
12046        synchronized (mPackages) {
12047            PackageParser.Package pkg = mPackages.get(packageName);
12048            if (pkg == null || pkg.activities == null) {
12049                return ParceledListSlice.emptyList();
12050            }
12051            final int count = pkg.activities.size();
12052            ArrayList<IntentFilter> result = new ArrayList<>();
12053            for (int n=0; n<count; n++) {
12054                PackageParser.Activity activity = pkg.activities.get(n);
12055                if (activity.intents != null && activity.intents.size() > 0) {
12056                    result.addAll(activity.intents);
12057                }
12058            }
12059            return new ParceledListSlice<>(result);
12060        }
12061    }
12062
12063    @Override
12064    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12065        mContext.enforceCallingOrSelfPermission(
12066                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12067
12068        synchronized (mPackages) {
12069            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12070            if (packageName != null) {
12071                result |= updateIntentVerificationStatus(packageName,
12072                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12073                        userId);
12074                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12075                        packageName, userId);
12076            }
12077            return result;
12078        }
12079    }
12080
12081    @Override
12082    public String getDefaultBrowserPackageName(int userId) {
12083        synchronized (mPackages) {
12084            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12085        }
12086    }
12087
12088    /**
12089     * Get the "allow unknown sources" setting.
12090     *
12091     * @return the current "allow unknown sources" setting
12092     */
12093    private int getUnknownSourcesSettings() {
12094        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12095                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12096                -1);
12097    }
12098
12099    @Override
12100    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12101        final int uid = Binder.getCallingUid();
12102        // writer
12103        synchronized (mPackages) {
12104            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12105            if (targetPackageSetting == null) {
12106                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12107            }
12108
12109            PackageSetting installerPackageSetting;
12110            if (installerPackageName != null) {
12111                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12112                if (installerPackageSetting == null) {
12113                    throw new IllegalArgumentException("Unknown installer package: "
12114                            + installerPackageName);
12115                }
12116            } else {
12117                installerPackageSetting = null;
12118            }
12119
12120            Signature[] callerSignature;
12121            Object obj = mSettings.getUserIdLPr(uid);
12122            if (obj != null) {
12123                if (obj instanceof SharedUserSetting) {
12124                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12125                } else if (obj instanceof PackageSetting) {
12126                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12127                } else {
12128                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12129                }
12130            } else {
12131                throw new SecurityException("Unknown calling UID: " + uid);
12132            }
12133
12134            // Verify: can't set installerPackageName to a package that is
12135            // not signed with the same cert as the caller.
12136            if (installerPackageSetting != null) {
12137                if (compareSignatures(callerSignature,
12138                        installerPackageSetting.signatures.mSignatures)
12139                        != PackageManager.SIGNATURE_MATCH) {
12140                    throw new SecurityException(
12141                            "Caller does not have same cert as new installer package "
12142                            + installerPackageName);
12143                }
12144            }
12145
12146            // Verify: if target already has an installer package, it must
12147            // be signed with the same cert as the caller.
12148            if (targetPackageSetting.installerPackageName != null) {
12149                PackageSetting setting = mSettings.mPackages.get(
12150                        targetPackageSetting.installerPackageName);
12151                // If the currently set package isn't valid, then it's always
12152                // okay to change it.
12153                if (setting != null) {
12154                    if (compareSignatures(callerSignature,
12155                            setting.signatures.mSignatures)
12156                            != PackageManager.SIGNATURE_MATCH) {
12157                        throw new SecurityException(
12158                                "Caller does not have same cert as old installer package "
12159                                + targetPackageSetting.installerPackageName);
12160                    }
12161                }
12162            }
12163
12164            // Okay!
12165            targetPackageSetting.installerPackageName = installerPackageName;
12166            if (installerPackageName != null) {
12167                mSettings.mInstallerPackages.add(installerPackageName);
12168            }
12169            scheduleWriteSettingsLocked();
12170        }
12171    }
12172
12173    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12174        // Queue up an async operation since the package installation may take a little while.
12175        mHandler.post(new Runnable() {
12176            public void run() {
12177                mHandler.removeCallbacks(this);
12178                 // Result object to be returned
12179                PackageInstalledInfo res = new PackageInstalledInfo();
12180                res.setReturnCode(currentStatus);
12181                res.uid = -1;
12182                res.pkg = null;
12183                res.removedInfo = null;
12184                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12185                    args.doPreInstall(res.returnCode);
12186                    synchronized (mInstallLock) {
12187                        installPackageTracedLI(args, res);
12188                    }
12189                    args.doPostInstall(res.returnCode, res.uid);
12190                }
12191
12192                // A restore should be performed at this point if (a) the install
12193                // succeeded, (b) the operation is not an update, and (c) the new
12194                // package has not opted out of backup participation.
12195                final boolean update = res.removedInfo != null
12196                        && res.removedInfo.removedPackage != null;
12197                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12198                boolean doRestore = !update
12199                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12200
12201                // Set up the post-install work request bookkeeping.  This will be used
12202                // and cleaned up by the post-install event handling regardless of whether
12203                // there's a restore pass performed.  Token values are >= 1.
12204                int token;
12205                if (mNextInstallToken < 0) mNextInstallToken = 1;
12206                token = mNextInstallToken++;
12207
12208                PostInstallData data = new PostInstallData(args, res);
12209                mRunningInstalls.put(token, data);
12210                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12211
12212                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12213                    // Pass responsibility to the Backup Manager.  It will perform a
12214                    // restore if appropriate, then pass responsibility back to the
12215                    // Package Manager to run the post-install observer callbacks
12216                    // and broadcasts.
12217                    IBackupManager bm = IBackupManager.Stub.asInterface(
12218                            ServiceManager.getService(Context.BACKUP_SERVICE));
12219                    if (bm != null) {
12220                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12221                                + " to BM for possible restore");
12222                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12223                        try {
12224                            // TODO: http://b/22388012
12225                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12226                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12227                            } else {
12228                                doRestore = false;
12229                            }
12230                        } catch (RemoteException e) {
12231                            // can't happen; the backup manager is local
12232                        } catch (Exception e) {
12233                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12234                            doRestore = false;
12235                        }
12236                    } else {
12237                        Slog.e(TAG, "Backup Manager not found!");
12238                        doRestore = false;
12239                    }
12240                }
12241
12242                if (!doRestore) {
12243                    // No restore possible, or the Backup Manager was mysteriously not
12244                    // available -- just fire the post-install work request directly.
12245                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12246
12247                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12248
12249                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12250                    mHandler.sendMessage(msg);
12251                }
12252            }
12253        });
12254    }
12255
12256    /**
12257     * Callback from PackageSettings whenever an app is first transitioned out of the
12258     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12259     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12260     * here whether the app is the target of an ongoing install, and only send the
12261     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12262     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12263     * handling.
12264     */
12265    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12266        // Serialize this with the rest of the install-process message chain.  In the
12267        // restore-at-install case, this Runnable will necessarily run before the
12268        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12269        // are coherent.  In the non-restore case, the app has already completed install
12270        // and been launched through some other means, so it is not in a problematic
12271        // state for observers to see the FIRST_LAUNCH signal.
12272        mHandler.post(new Runnable() {
12273            @Override
12274            public void run() {
12275                for (int i = 0; i < mRunningInstalls.size(); i++) {
12276                    final PostInstallData data = mRunningInstalls.valueAt(i);
12277                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12278                        // right package; but is it for the right user?
12279                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12280                            if (userId == data.res.newUsers[uIndex]) {
12281                                if (DEBUG_BACKUP) {
12282                                    Slog.i(TAG, "Package " + pkgName
12283                                            + " being restored so deferring FIRST_LAUNCH");
12284                                }
12285                                return;
12286                            }
12287                        }
12288                    }
12289                }
12290                // didn't find it, so not being restored
12291                if (DEBUG_BACKUP) {
12292                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12293                }
12294                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12295            }
12296        });
12297    }
12298
12299    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12300        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12301                installerPkg, null, userIds);
12302    }
12303
12304    private abstract class HandlerParams {
12305        private static final int MAX_RETRIES = 4;
12306
12307        /**
12308         * Number of times startCopy() has been attempted and had a non-fatal
12309         * error.
12310         */
12311        private int mRetries = 0;
12312
12313        /** User handle for the user requesting the information or installation. */
12314        private final UserHandle mUser;
12315        String traceMethod;
12316        int traceCookie;
12317
12318        HandlerParams(UserHandle user) {
12319            mUser = user;
12320        }
12321
12322        UserHandle getUser() {
12323            return mUser;
12324        }
12325
12326        HandlerParams setTraceMethod(String traceMethod) {
12327            this.traceMethod = traceMethod;
12328            return this;
12329        }
12330
12331        HandlerParams setTraceCookie(int traceCookie) {
12332            this.traceCookie = traceCookie;
12333            return this;
12334        }
12335
12336        final boolean startCopy() {
12337            boolean res;
12338            try {
12339                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12340
12341                if (++mRetries > MAX_RETRIES) {
12342                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12343                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12344                    handleServiceError();
12345                    return false;
12346                } else {
12347                    handleStartCopy();
12348                    res = true;
12349                }
12350            } catch (RemoteException e) {
12351                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12352                mHandler.sendEmptyMessage(MCS_RECONNECT);
12353                res = false;
12354            }
12355            handleReturnCode();
12356            return res;
12357        }
12358
12359        final void serviceError() {
12360            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12361            handleServiceError();
12362            handleReturnCode();
12363        }
12364
12365        abstract void handleStartCopy() throws RemoteException;
12366        abstract void handleServiceError();
12367        abstract void handleReturnCode();
12368    }
12369
12370    class MeasureParams extends HandlerParams {
12371        private final PackageStats mStats;
12372        private boolean mSuccess;
12373
12374        private final IPackageStatsObserver mObserver;
12375
12376        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12377            super(new UserHandle(stats.userHandle));
12378            mObserver = observer;
12379            mStats = stats;
12380        }
12381
12382        @Override
12383        public String toString() {
12384            return "MeasureParams{"
12385                + Integer.toHexString(System.identityHashCode(this))
12386                + " " + mStats.packageName + "}";
12387        }
12388
12389        @Override
12390        void handleStartCopy() throws RemoteException {
12391            synchronized (mInstallLock) {
12392                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12393            }
12394
12395            if (mSuccess) {
12396                boolean mounted = false;
12397                try {
12398                    final String status = Environment.getExternalStorageState();
12399                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12400                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12401                } catch (Exception e) {
12402                }
12403
12404                if (mounted) {
12405                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12406
12407                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12408                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12409
12410                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12411                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12412
12413                    // Always subtract cache size, since it's a subdirectory
12414                    mStats.externalDataSize -= mStats.externalCacheSize;
12415
12416                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12417                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12418
12419                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12420                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12421                }
12422            }
12423        }
12424
12425        @Override
12426        void handleReturnCode() {
12427            if (mObserver != null) {
12428                try {
12429                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12430                } catch (RemoteException e) {
12431                    Slog.i(TAG, "Observer no longer exists.");
12432                }
12433            }
12434        }
12435
12436        @Override
12437        void handleServiceError() {
12438            Slog.e(TAG, "Could not measure application " + mStats.packageName
12439                            + " external storage");
12440        }
12441    }
12442
12443    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12444            throws RemoteException {
12445        long result = 0;
12446        for (File path : paths) {
12447            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12448        }
12449        return result;
12450    }
12451
12452    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12453        for (File path : paths) {
12454            try {
12455                mcs.clearDirectory(path.getAbsolutePath());
12456            } catch (RemoteException e) {
12457            }
12458        }
12459    }
12460
12461    static class OriginInfo {
12462        /**
12463         * Location where install is coming from, before it has been
12464         * copied/renamed into place. This could be a single monolithic APK
12465         * file, or a cluster directory. This location may be untrusted.
12466         */
12467        final File file;
12468        final String cid;
12469
12470        /**
12471         * Flag indicating that {@link #file} or {@link #cid} has already been
12472         * staged, meaning downstream users don't need to defensively copy the
12473         * contents.
12474         */
12475        final boolean staged;
12476
12477        /**
12478         * Flag indicating that {@link #file} or {@link #cid} is an already
12479         * installed app that is being moved.
12480         */
12481        final boolean existing;
12482
12483        final String resolvedPath;
12484        final File resolvedFile;
12485
12486        static OriginInfo fromNothing() {
12487            return new OriginInfo(null, null, false, false);
12488        }
12489
12490        static OriginInfo fromUntrustedFile(File file) {
12491            return new OriginInfo(file, null, false, false);
12492        }
12493
12494        static OriginInfo fromExistingFile(File file) {
12495            return new OriginInfo(file, null, false, true);
12496        }
12497
12498        static OriginInfo fromStagedFile(File file) {
12499            return new OriginInfo(file, null, true, false);
12500        }
12501
12502        static OriginInfo fromStagedContainer(String cid) {
12503            return new OriginInfo(null, cid, true, false);
12504        }
12505
12506        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12507            this.file = file;
12508            this.cid = cid;
12509            this.staged = staged;
12510            this.existing = existing;
12511
12512            if (cid != null) {
12513                resolvedPath = PackageHelper.getSdDir(cid);
12514                resolvedFile = new File(resolvedPath);
12515            } else if (file != null) {
12516                resolvedPath = file.getAbsolutePath();
12517                resolvedFile = file;
12518            } else {
12519                resolvedPath = null;
12520                resolvedFile = null;
12521            }
12522        }
12523    }
12524
12525    static class MoveInfo {
12526        final int moveId;
12527        final String fromUuid;
12528        final String toUuid;
12529        final String packageName;
12530        final String dataAppName;
12531        final int appId;
12532        final String seinfo;
12533        final int targetSdkVersion;
12534
12535        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12536                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12537            this.moveId = moveId;
12538            this.fromUuid = fromUuid;
12539            this.toUuid = toUuid;
12540            this.packageName = packageName;
12541            this.dataAppName = dataAppName;
12542            this.appId = appId;
12543            this.seinfo = seinfo;
12544            this.targetSdkVersion = targetSdkVersion;
12545        }
12546    }
12547
12548    static class VerificationInfo {
12549        /** A constant used to indicate that a uid value is not present. */
12550        public static final int NO_UID = -1;
12551
12552        /** URI referencing where the package was downloaded from. */
12553        final Uri originatingUri;
12554
12555        /** HTTP referrer URI associated with the originatingURI. */
12556        final Uri referrer;
12557
12558        /** UID of the application that the install request originated from. */
12559        final int originatingUid;
12560
12561        /** UID of application requesting the install */
12562        final int installerUid;
12563
12564        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12565            this.originatingUri = originatingUri;
12566            this.referrer = referrer;
12567            this.originatingUid = originatingUid;
12568            this.installerUid = installerUid;
12569        }
12570    }
12571
12572    class InstallParams extends HandlerParams {
12573        final OriginInfo origin;
12574        final MoveInfo move;
12575        final IPackageInstallObserver2 observer;
12576        int installFlags;
12577        final String installerPackageName;
12578        final String volumeUuid;
12579        private InstallArgs mArgs;
12580        private int mRet;
12581        final String packageAbiOverride;
12582        final String[] grantedRuntimePermissions;
12583        final VerificationInfo verificationInfo;
12584        final Certificate[][] certificates;
12585
12586        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12587                int installFlags, String installerPackageName, String volumeUuid,
12588                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12589                String[] grantedPermissions, Certificate[][] certificates) {
12590            super(user);
12591            this.origin = origin;
12592            this.move = move;
12593            this.observer = observer;
12594            this.installFlags = installFlags;
12595            this.installerPackageName = installerPackageName;
12596            this.volumeUuid = volumeUuid;
12597            this.verificationInfo = verificationInfo;
12598            this.packageAbiOverride = packageAbiOverride;
12599            this.grantedRuntimePermissions = grantedPermissions;
12600            this.certificates = certificates;
12601        }
12602
12603        @Override
12604        public String toString() {
12605            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12606                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12607        }
12608
12609        private int installLocationPolicy(PackageInfoLite pkgLite) {
12610            String packageName = pkgLite.packageName;
12611            int installLocation = pkgLite.installLocation;
12612            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12613            // reader
12614            synchronized (mPackages) {
12615                // Currently installed package which the new package is attempting to replace or
12616                // null if no such package is installed.
12617                PackageParser.Package installedPkg = mPackages.get(packageName);
12618                // Package which currently owns the data which the new package will own if installed.
12619                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12620                // will be null whereas dataOwnerPkg will contain information about the package
12621                // which was uninstalled while keeping its data.
12622                PackageParser.Package dataOwnerPkg = installedPkg;
12623                if (dataOwnerPkg  == null) {
12624                    PackageSetting ps = mSettings.mPackages.get(packageName);
12625                    if (ps != null) {
12626                        dataOwnerPkg = ps.pkg;
12627                    }
12628                }
12629
12630                if (dataOwnerPkg != null) {
12631                    // If installed, the package will get access to data left on the device by its
12632                    // predecessor. As a security measure, this is permited only if this is not a
12633                    // version downgrade or if the predecessor package is marked as debuggable and
12634                    // a downgrade is explicitly requested.
12635                    //
12636                    // On debuggable platform builds, downgrades are permitted even for
12637                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12638                    // not offer security guarantees and thus it's OK to disable some security
12639                    // mechanisms to make debugging/testing easier on those builds. However, even on
12640                    // debuggable builds downgrades of packages are permitted only if requested via
12641                    // installFlags. This is because we aim to keep the behavior of debuggable
12642                    // platform builds as close as possible to the behavior of non-debuggable
12643                    // platform builds.
12644                    final boolean downgradeRequested =
12645                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12646                    final boolean packageDebuggable =
12647                                (dataOwnerPkg.applicationInfo.flags
12648                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12649                    final boolean downgradePermitted =
12650                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12651                    if (!downgradePermitted) {
12652                        try {
12653                            checkDowngrade(dataOwnerPkg, pkgLite);
12654                        } catch (PackageManagerException e) {
12655                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12656                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12657                        }
12658                    }
12659                }
12660
12661                if (installedPkg != null) {
12662                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12663                        // Check for updated system application.
12664                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12665                            if (onSd) {
12666                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12667                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12668                            }
12669                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12670                        } else {
12671                            if (onSd) {
12672                                // Install flag overrides everything.
12673                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12674                            }
12675                            // If current upgrade specifies particular preference
12676                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12677                                // Application explicitly specified internal.
12678                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12679                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12680                                // App explictly prefers external. Let policy decide
12681                            } else {
12682                                // Prefer previous location
12683                                if (isExternal(installedPkg)) {
12684                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12685                                }
12686                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12687                            }
12688                        }
12689                    } else {
12690                        // Invalid install. Return error code
12691                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12692                    }
12693                }
12694            }
12695            // All the special cases have been taken care of.
12696            // Return result based on recommended install location.
12697            if (onSd) {
12698                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12699            }
12700            return pkgLite.recommendedInstallLocation;
12701        }
12702
12703        /*
12704         * Invoke remote method to get package information and install
12705         * location values. Override install location based on default
12706         * policy if needed and then create install arguments based
12707         * on the install location.
12708         */
12709        public void handleStartCopy() throws RemoteException {
12710            int ret = PackageManager.INSTALL_SUCCEEDED;
12711
12712            // If we're already staged, we've firmly committed to an install location
12713            if (origin.staged) {
12714                if (origin.file != null) {
12715                    installFlags |= PackageManager.INSTALL_INTERNAL;
12716                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12717                } else if (origin.cid != null) {
12718                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12719                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12720                } else {
12721                    throw new IllegalStateException("Invalid stage location");
12722                }
12723            }
12724
12725            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12726            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12727            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12728            PackageInfoLite pkgLite = null;
12729
12730            if (onInt && onSd) {
12731                // Check if both bits are set.
12732                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12733                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12734            } else if (onSd && ephemeral) {
12735                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12736                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12737            } else {
12738                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12739                        packageAbiOverride);
12740
12741                if (DEBUG_EPHEMERAL && ephemeral) {
12742                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12743                }
12744
12745                /*
12746                 * If we have too little free space, try to free cache
12747                 * before giving up.
12748                 */
12749                if (!origin.staged && pkgLite.recommendedInstallLocation
12750                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12751                    // TODO: focus freeing disk space on the target device
12752                    final StorageManager storage = StorageManager.from(mContext);
12753                    final long lowThreshold = storage.getStorageLowBytes(
12754                            Environment.getDataDirectory());
12755
12756                    final long sizeBytes = mContainerService.calculateInstalledSize(
12757                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12758
12759                    try {
12760                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12761                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12762                                installFlags, packageAbiOverride);
12763                    } catch (InstallerException e) {
12764                        Slog.w(TAG, "Failed to free cache", e);
12765                    }
12766
12767                    /*
12768                     * The cache free must have deleted the file we
12769                     * downloaded to install.
12770                     *
12771                     * TODO: fix the "freeCache" call to not delete
12772                     *       the file we care about.
12773                     */
12774                    if (pkgLite.recommendedInstallLocation
12775                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12776                        pkgLite.recommendedInstallLocation
12777                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12778                    }
12779                }
12780            }
12781
12782            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12783                int loc = pkgLite.recommendedInstallLocation;
12784                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12785                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12786                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12787                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12788                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12789                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12790                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12791                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12792                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12793                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12794                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12795                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12796                } else {
12797                    // Override with defaults if needed.
12798                    loc = installLocationPolicy(pkgLite);
12799                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12800                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12801                    } else if (!onSd && !onInt) {
12802                        // Override install location with flags
12803                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12804                            // Set the flag to install on external media.
12805                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12806                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12807                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12808                            if (DEBUG_EPHEMERAL) {
12809                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12810                            }
12811                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12812                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12813                                    |PackageManager.INSTALL_INTERNAL);
12814                        } else {
12815                            // Make sure the flag for installing on external
12816                            // media is unset
12817                            installFlags |= PackageManager.INSTALL_INTERNAL;
12818                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12819                        }
12820                    }
12821                }
12822            }
12823
12824            final InstallArgs args = createInstallArgs(this);
12825            mArgs = args;
12826
12827            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12828                // TODO: http://b/22976637
12829                // Apps installed for "all" users use the device owner to verify the app
12830                UserHandle verifierUser = getUser();
12831                if (verifierUser == UserHandle.ALL) {
12832                    verifierUser = UserHandle.SYSTEM;
12833                }
12834
12835                /*
12836                 * Determine if we have any installed package verifiers. If we
12837                 * do, then we'll defer to them to verify the packages.
12838                 */
12839                final int requiredUid = mRequiredVerifierPackage == null ? -1
12840                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12841                                verifierUser.getIdentifier());
12842                if (!origin.existing && requiredUid != -1
12843                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12844                    final Intent verification = new Intent(
12845                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12846                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12847                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12848                            PACKAGE_MIME_TYPE);
12849                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12850
12851                    // Query all live verifiers based on current user state
12852                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12853                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12854
12855                    if (DEBUG_VERIFY) {
12856                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12857                                + verification.toString() + " with " + pkgLite.verifiers.length
12858                                + " optional verifiers");
12859                    }
12860
12861                    final int verificationId = mPendingVerificationToken++;
12862
12863                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12864
12865                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12866                            installerPackageName);
12867
12868                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12869                            installFlags);
12870
12871                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12872                            pkgLite.packageName);
12873
12874                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12875                            pkgLite.versionCode);
12876
12877                    if (verificationInfo != null) {
12878                        if (verificationInfo.originatingUri != null) {
12879                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12880                                    verificationInfo.originatingUri);
12881                        }
12882                        if (verificationInfo.referrer != null) {
12883                            verification.putExtra(Intent.EXTRA_REFERRER,
12884                                    verificationInfo.referrer);
12885                        }
12886                        if (verificationInfo.originatingUid >= 0) {
12887                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12888                                    verificationInfo.originatingUid);
12889                        }
12890                        if (verificationInfo.installerUid >= 0) {
12891                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12892                                    verificationInfo.installerUid);
12893                        }
12894                    }
12895
12896                    final PackageVerificationState verificationState = new PackageVerificationState(
12897                            requiredUid, args);
12898
12899                    mPendingVerification.append(verificationId, verificationState);
12900
12901                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12902                            receivers, verificationState);
12903
12904                    /*
12905                     * If any sufficient verifiers were listed in the package
12906                     * manifest, attempt to ask them.
12907                     */
12908                    if (sufficientVerifiers != null) {
12909                        final int N = sufficientVerifiers.size();
12910                        if (N == 0) {
12911                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12912                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12913                        } else {
12914                            for (int i = 0; i < N; i++) {
12915                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12916
12917                                final Intent sufficientIntent = new Intent(verification);
12918                                sufficientIntent.setComponent(verifierComponent);
12919                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12920                            }
12921                        }
12922                    }
12923
12924                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12925                            mRequiredVerifierPackage, receivers);
12926                    if (ret == PackageManager.INSTALL_SUCCEEDED
12927                            && mRequiredVerifierPackage != null) {
12928                        Trace.asyncTraceBegin(
12929                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12930                        /*
12931                         * Send the intent to the required verification agent,
12932                         * but only start the verification timeout after the
12933                         * target BroadcastReceivers have run.
12934                         */
12935                        verification.setComponent(requiredVerifierComponent);
12936                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12937                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12938                                new BroadcastReceiver() {
12939                                    @Override
12940                                    public void onReceive(Context context, Intent intent) {
12941                                        final Message msg = mHandler
12942                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12943                                        msg.arg1 = verificationId;
12944                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12945                                    }
12946                                }, null, 0, null, null);
12947
12948                        /*
12949                         * We don't want the copy to proceed until verification
12950                         * succeeds, so null out this field.
12951                         */
12952                        mArgs = null;
12953                    }
12954                } else {
12955                    /*
12956                     * No package verification is enabled, so immediately start
12957                     * the remote call to initiate copy using temporary file.
12958                     */
12959                    ret = args.copyApk(mContainerService, true);
12960                }
12961            }
12962
12963            mRet = ret;
12964        }
12965
12966        @Override
12967        void handleReturnCode() {
12968            // If mArgs is null, then MCS couldn't be reached. When it
12969            // reconnects, it will try again to install. At that point, this
12970            // will succeed.
12971            if (mArgs != null) {
12972                processPendingInstall(mArgs, mRet);
12973            }
12974        }
12975
12976        @Override
12977        void handleServiceError() {
12978            mArgs = createInstallArgs(this);
12979            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12980        }
12981
12982        public boolean isForwardLocked() {
12983            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12984        }
12985    }
12986
12987    /**
12988     * Used during creation of InstallArgs
12989     *
12990     * @param installFlags package installation flags
12991     * @return true if should be installed on external storage
12992     */
12993    private static boolean installOnExternalAsec(int installFlags) {
12994        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12995            return false;
12996        }
12997        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12998            return true;
12999        }
13000        return false;
13001    }
13002
13003    /**
13004     * Used during creation of InstallArgs
13005     *
13006     * @param installFlags package installation flags
13007     * @return true if should be installed as forward locked
13008     */
13009    private static boolean installForwardLocked(int installFlags) {
13010        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13011    }
13012
13013    private InstallArgs createInstallArgs(InstallParams params) {
13014        if (params.move != null) {
13015            return new MoveInstallArgs(params);
13016        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13017            return new AsecInstallArgs(params);
13018        } else {
13019            return new FileInstallArgs(params);
13020        }
13021    }
13022
13023    /**
13024     * Create args that describe an existing installed package. Typically used
13025     * when cleaning up old installs, or used as a move source.
13026     */
13027    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13028            String resourcePath, String[] instructionSets) {
13029        final boolean isInAsec;
13030        if (installOnExternalAsec(installFlags)) {
13031            /* Apps on SD card are always in ASEC containers. */
13032            isInAsec = true;
13033        } else if (installForwardLocked(installFlags)
13034                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13035            /*
13036             * Forward-locked apps are only in ASEC containers if they're the
13037             * new style
13038             */
13039            isInAsec = true;
13040        } else {
13041            isInAsec = false;
13042        }
13043
13044        if (isInAsec) {
13045            return new AsecInstallArgs(codePath, instructionSets,
13046                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13047        } else {
13048            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13049        }
13050    }
13051
13052    static abstract class InstallArgs {
13053        /** @see InstallParams#origin */
13054        final OriginInfo origin;
13055        /** @see InstallParams#move */
13056        final MoveInfo move;
13057
13058        final IPackageInstallObserver2 observer;
13059        // Always refers to PackageManager flags only
13060        final int installFlags;
13061        final String installerPackageName;
13062        final String volumeUuid;
13063        final UserHandle user;
13064        final String abiOverride;
13065        final String[] installGrantPermissions;
13066        /** If non-null, drop an async trace when the install completes */
13067        final String traceMethod;
13068        final int traceCookie;
13069        final Certificate[][] certificates;
13070
13071        // The list of instruction sets supported by this app. This is currently
13072        // only used during the rmdex() phase to clean up resources. We can get rid of this
13073        // if we move dex files under the common app path.
13074        /* nullable */ String[] instructionSets;
13075
13076        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13077                int installFlags, String installerPackageName, String volumeUuid,
13078                UserHandle user, String[] instructionSets,
13079                String abiOverride, String[] installGrantPermissions,
13080                String traceMethod, int traceCookie, Certificate[][] certificates) {
13081            this.origin = origin;
13082            this.move = move;
13083            this.installFlags = installFlags;
13084            this.observer = observer;
13085            this.installerPackageName = installerPackageName;
13086            this.volumeUuid = volumeUuid;
13087            this.user = user;
13088            this.instructionSets = instructionSets;
13089            this.abiOverride = abiOverride;
13090            this.installGrantPermissions = installGrantPermissions;
13091            this.traceMethod = traceMethod;
13092            this.traceCookie = traceCookie;
13093            this.certificates = certificates;
13094        }
13095
13096        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13097        abstract int doPreInstall(int status);
13098
13099        /**
13100         * Rename package into final resting place. All paths on the given
13101         * scanned package should be updated to reflect the rename.
13102         */
13103        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13104        abstract int doPostInstall(int status, int uid);
13105
13106        /** @see PackageSettingBase#codePathString */
13107        abstract String getCodePath();
13108        /** @see PackageSettingBase#resourcePathString */
13109        abstract String getResourcePath();
13110
13111        // Need installer lock especially for dex file removal.
13112        abstract void cleanUpResourcesLI();
13113        abstract boolean doPostDeleteLI(boolean delete);
13114
13115        /**
13116         * Called before the source arguments are copied. This is used mostly
13117         * for MoveParams when it needs to read the source file to put it in the
13118         * destination.
13119         */
13120        int doPreCopy() {
13121            return PackageManager.INSTALL_SUCCEEDED;
13122        }
13123
13124        /**
13125         * Called after the source arguments are copied. This is used mostly for
13126         * MoveParams when it needs to read the source file to put it in the
13127         * destination.
13128         */
13129        int doPostCopy(int uid) {
13130            return PackageManager.INSTALL_SUCCEEDED;
13131        }
13132
13133        protected boolean isFwdLocked() {
13134            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13135        }
13136
13137        protected boolean isExternalAsec() {
13138            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13139        }
13140
13141        protected boolean isEphemeral() {
13142            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13143        }
13144
13145        UserHandle getUser() {
13146            return user;
13147        }
13148    }
13149
13150    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13151        if (!allCodePaths.isEmpty()) {
13152            if (instructionSets == null) {
13153                throw new IllegalStateException("instructionSet == null");
13154            }
13155            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13156            for (String codePath : allCodePaths) {
13157                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13158                    try {
13159                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13160                    } catch (InstallerException ignored) {
13161                    }
13162                }
13163            }
13164        }
13165    }
13166
13167    /**
13168     * Logic to handle installation of non-ASEC applications, including copying
13169     * and renaming logic.
13170     */
13171    class FileInstallArgs extends InstallArgs {
13172        private File codeFile;
13173        private File resourceFile;
13174
13175        // Example topology:
13176        // /data/app/com.example/base.apk
13177        // /data/app/com.example/split_foo.apk
13178        // /data/app/com.example/lib/arm/libfoo.so
13179        // /data/app/com.example/lib/arm64/libfoo.so
13180        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13181
13182        /** New install */
13183        FileInstallArgs(InstallParams params) {
13184            super(params.origin, params.move, params.observer, params.installFlags,
13185                    params.installerPackageName, params.volumeUuid,
13186                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13187                    params.grantedRuntimePermissions,
13188                    params.traceMethod, params.traceCookie, params.certificates);
13189            if (isFwdLocked()) {
13190                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13191            }
13192        }
13193
13194        /** Existing install */
13195        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13196            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13197                    null, null, null, 0, null /*certificates*/);
13198            this.codeFile = (codePath != null) ? new File(codePath) : null;
13199            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13200        }
13201
13202        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13203            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13204            try {
13205                return doCopyApk(imcs, temp);
13206            } finally {
13207                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13208            }
13209        }
13210
13211        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13212            if (origin.staged) {
13213                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13214                codeFile = origin.file;
13215                resourceFile = origin.file;
13216                return PackageManager.INSTALL_SUCCEEDED;
13217            }
13218
13219            try {
13220                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13221                final File tempDir =
13222                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13223                codeFile = tempDir;
13224                resourceFile = tempDir;
13225            } catch (IOException e) {
13226                Slog.w(TAG, "Failed to create copy file: " + e);
13227                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13228            }
13229
13230            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13231                @Override
13232                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13233                    if (!FileUtils.isValidExtFilename(name)) {
13234                        throw new IllegalArgumentException("Invalid filename: " + name);
13235                    }
13236                    try {
13237                        final File file = new File(codeFile, name);
13238                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13239                                O_RDWR | O_CREAT, 0644);
13240                        Os.chmod(file.getAbsolutePath(), 0644);
13241                        return new ParcelFileDescriptor(fd);
13242                    } catch (ErrnoException e) {
13243                        throw new RemoteException("Failed to open: " + e.getMessage());
13244                    }
13245                }
13246            };
13247
13248            int ret = PackageManager.INSTALL_SUCCEEDED;
13249            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13250            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13251                Slog.e(TAG, "Failed to copy package");
13252                return ret;
13253            }
13254
13255            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13256            NativeLibraryHelper.Handle handle = null;
13257            try {
13258                handle = NativeLibraryHelper.Handle.create(codeFile);
13259                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13260                        abiOverride);
13261            } catch (IOException e) {
13262                Slog.e(TAG, "Copying native libraries failed", e);
13263                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13264            } finally {
13265                IoUtils.closeQuietly(handle);
13266            }
13267
13268            return ret;
13269        }
13270
13271        int doPreInstall(int status) {
13272            if (status != PackageManager.INSTALL_SUCCEEDED) {
13273                cleanUp();
13274            }
13275            return status;
13276        }
13277
13278        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13279            if (status != PackageManager.INSTALL_SUCCEEDED) {
13280                cleanUp();
13281                return false;
13282            }
13283
13284            final File targetDir = codeFile.getParentFile();
13285            final File beforeCodeFile = codeFile;
13286            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13287
13288            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13289            try {
13290                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13291            } catch (ErrnoException e) {
13292                Slog.w(TAG, "Failed to rename", e);
13293                return false;
13294            }
13295
13296            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13297                Slog.w(TAG, "Failed to restorecon");
13298                return false;
13299            }
13300
13301            // Reflect the rename internally
13302            codeFile = afterCodeFile;
13303            resourceFile = afterCodeFile;
13304
13305            // Reflect the rename in scanned details
13306            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13307            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13308                    afterCodeFile, pkg.baseCodePath));
13309            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13310                    afterCodeFile, pkg.splitCodePaths));
13311
13312            // Reflect the rename in app info
13313            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13314            pkg.setApplicationInfoCodePath(pkg.codePath);
13315            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13316            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13317            pkg.setApplicationInfoResourcePath(pkg.codePath);
13318            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13319            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13320
13321            return true;
13322        }
13323
13324        int doPostInstall(int status, int uid) {
13325            if (status != PackageManager.INSTALL_SUCCEEDED) {
13326                cleanUp();
13327            }
13328            return status;
13329        }
13330
13331        @Override
13332        String getCodePath() {
13333            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13334        }
13335
13336        @Override
13337        String getResourcePath() {
13338            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13339        }
13340
13341        private boolean cleanUp() {
13342            if (codeFile == null || !codeFile.exists()) {
13343                return false;
13344            }
13345
13346            removeCodePathLI(codeFile);
13347
13348            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13349                resourceFile.delete();
13350            }
13351
13352            return true;
13353        }
13354
13355        void cleanUpResourcesLI() {
13356            // Try enumerating all code paths before deleting
13357            List<String> allCodePaths = Collections.EMPTY_LIST;
13358            if (codeFile != null && codeFile.exists()) {
13359                try {
13360                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13361                    allCodePaths = pkg.getAllCodePaths();
13362                } catch (PackageParserException e) {
13363                    // Ignored; we tried our best
13364                }
13365            }
13366
13367            cleanUp();
13368            removeDexFiles(allCodePaths, instructionSets);
13369        }
13370
13371        boolean doPostDeleteLI(boolean delete) {
13372            // XXX err, shouldn't we respect the delete flag?
13373            cleanUpResourcesLI();
13374            return true;
13375        }
13376    }
13377
13378    private boolean isAsecExternal(String cid) {
13379        final String asecPath = PackageHelper.getSdFilesystem(cid);
13380        return !asecPath.startsWith(mAsecInternalPath);
13381    }
13382
13383    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13384            PackageManagerException {
13385        if (copyRet < 0) {
13386            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13387                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13388                throw new PackageManagerException(copyRet, message);
13389            }
13390        }
13391    }
13392
13393    /**
13394     * Extract the MountService "container ID" from the full code path of an
13395     * .apk.
13396     */
13397    static String cidFromCodePath(String fullCodePath) {
13398        int eidx = fullCodePath.lastIndexOf("/");
13399        String subStr1 = fullCodePath.substring(0, eidx);
13400        int sidx = subStr1.lastIndexOf("/");
13401        return subStr1.substring(sidx+1, eidx);
13402    }
13403
13404    /**
13405     * Logic to handle installation of ASEC applications, including copying and
13406     * renaming logic.
13407     */
13408    class AsecInstallArgs extends InstallArgs {
13409        static final String RES_FILE_NAME = "pkg.apk";
13410        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13411
13412        String cid;
13413        String packagePath;
13414        String resourcePath;
13415
13416        /** New install */
13417        AsecInstallArgs(InstallParams params) {
13418            super(params.origin, params.move, params.observer, params.installFlags,
13419                    params.installerPackageName, params.volumeUuid,
13420                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13421                    params.grantedRuntimePermissions,
13422                    params.traceMethod, params.traceCookie, params.certificates);
13423        }
13424
13425        /** Existing install */
13426        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13427                        boolean isExternal, boolean isForwardLocked) {
13428            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13429              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13430                    instructionSets, null, null, null, 0, null /*certificates*/);
13431            // Hackily pretend we're still looking at a full code path
13432            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13433                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13434            }
13435
13436            // Extract cid from fullCodePath
13437            int eidx = fullCodePath.lastIndexOf("/");
13438            String subStr1 = fullCodePath.substring(0, eidx);
13439            int sidx = subStr1.lastIndexOf("/");
13440            cid = subStr1.substring(sidx+1, eidx);
13441            setMountPath(subStr1);
13442        }
13443
13444        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13445            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13446              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13447                    instructionSets, null, null, null, 0, null /*certificates*/);
13448            this.cid = cid;
13449            setMountPath(PackageHelper.getSdDir(cid));
13450        }
13451
13452        void createCopyFile() {
13453            cid = mInstallerService.allocateExternalStageCidLegacy();
13454        }
13455
13456        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13457            if (origin.staged && origin.cid != null) {
13458                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13459                cid = origin.cid;
13460                setMountPath(PackageHelper.getSdDir(cid));
13461                return PackageManager.INSTALL_SUCCEEDED;
13462            }
13463
13464            if (temp) {
13465                createCopyFile();
13466            } else {
13467                /*
13468                 * Pre-emptively destroy the container since it's destroyed if
13469                 * copying fails due to it existing anyway.
13470                 */
13471                PackageHelper.destroySdDir(cid);
13472            }
13473
13474            final String newMountPath = imcs.copyPackageToContainer(
13475                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13476                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13477
13478            if (newMountPath != null) {
13479                setMountPath(newMountPath);
13480                return PackageManager.INSTALL_SUCCEEDED;
13481            } else {
13482                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13483            }
13484        }
13485
13486        @Override
13487        String getCodePath() {
13488            return packagePath;
13489        }
13490
13491        @Override
13492        String getResourcePath() {
13493            return resourcePath;
13494        }
13495
13496        int doPreInstall(int status) {
13497            if (status != PackageManager.INSTALL_SUCCEEDED) {
13498                // Destroy container
13499                PackageHelper.destroySdDir(cid);
13500            } else {
13501                boolean mounted = PackageHelper.isContainerMounted(cid);
13502                if (!mounted) {
13503                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13504                            Process.SYSTEM_UID);
13505                    if (newMountPath != null) {
13506                        setMountPath(newMountPath);
13507                    } else {
13508                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13509                    }
13510                }
13511            }
13512            return status;
13513        }
13514
13515        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13516            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13517            String newMountPath = null;
13518            if (PackageHelper.isContainerMounted(cid)) {
13519                // Unmount the container
13520                if (!PackageHelper.unMountSdDir(cid)) {
13521                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13522                    return false;
13523                }
13524            }
13525            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13526                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13527                        " which might be stale. Will try to clean up.");
13528                // Clean up the stale container and proceed to recreate.
13529                if (!PackageHelper.destroySdDir(newCacheId)) {
13530                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13531                    return false;
13532                }
13533                // Successfully cleaned up stale container. Try to rename again.
13534                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13535                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13536                            + " inspite of cleaning it up.");
13537                    return false;
13538                }
13539            }
13540            if (!PackageHelper.isContainerMounted(newCacheId)) {
13541                Slog.w(TAG, "Mounting container " + newCacheId);
13542                newMountPath = PackageHelper.mountSdDir(newCacheId,
13543                        getEncryptKey(), Process.SYSTEM_UID);
13544            } else {
13545                newMountPath = PackageHelper.getSdDir(newCacheId);
13546            }
13547            if (newMountPath == null) {
13548                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13549                return false;
13550            }
13551            Log.i(TAG, "Succesfully renamed " + cid +
13552                    " to " + newCacheId +
13553                    " at new path: " + newMountPath);
13554            cid = newCacheId;
13555
13556            final File beforeCodeFile = new File(packagePath);
13557            setMountPath(newMountPath);
13558            final File afterCodeFile = new File(packagePath);
13559
13560            // Reflect the rename in scanned details
13561            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13562            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13563                    afterCodeFile, pkg.baseCodePath));
13564            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13565                    afterCodeFile, pkg.splitCodePaths));
13566
13567            // Reflect the rename in app info
13568            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13569            pkg.setApplicationInfoCodePath(pkg.codePath);
13570            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13571            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13572            pkg.setApplicationInfoResourcePath(pkg.codePath);
13573            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13574            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13575
13576            return true;
13577        }
13578
13579        private void setMountPath(String mountPath) {
13580            final File mountFile = new File(mountPath);
13581
13582            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13583            if (monolithicFile.exists()) {
13584                packagePath = monolithicFile.getAbsolutePath();
13585                if (isFwdLocked()) {
13586                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13587                } else {
13588                    resourcePath = packagePath;
13589                }
13590            } else {
13591                packagePath = mountFile.getAbsolutePath();
13592                resourcePath = packagePath;
13593            }
13594        }
13595
13596        int doPostInstall(int status, int uid) {
13597            if (status != PackageManager.INSTALL_SUCCEEDED) {
13598                cleanUp();
13599            } else {
13600                final int groupOwner;
13601                final String protectedFile;
13602                if (isFwdLocked()) {
13603                    groupOwner = UserHandle.getSharedAppGid(uid);
13604                    protectedFile = RES_FILE_NAME;
13605                } else {
13606                    groupOwner = -1;
13607                    protectedFile = null;
13608                }
13609
13610                if (uid < Process.FIRST_APPLICATION_UID
13611                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13612                    Slog.e(TAG, "Failed to finalize " + cid);
13613                    PackageHelper.destroySdDir(cid);
13614                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13615                }
13616
13617                boolean mounted = PackageHelper.isContainerMounted(cid);
13618                if (!mounted) {
13619                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13620                }
13621            }
13622            return status;
13623        }
13624
13625        private void cleanUp() {
13626            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13627
13628            // Destroy secure container
13629            PackageHelper.destroySdDir(cid);
13630        }
13631
13632        private List<String> getAllCodePaths() {
13633            final File codeFile = new File(getCodePath());
13634            if (codeFile != null && codeFile.exists()) {
13635                try {
13636                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13637                    return pkg.getAllCodePaths();
13638                } catch (PackageParserException e) {
13639                    // Ignored; we tried our best
13640                }
13641            }
13642            return Collections.EMPTY_LIST;
13643        }
13644
13645        void cleanUpResourcesLI() {
13646            // Enumerate all code paths before deleting
13647            cleanUpResourcesLI(getAllCodePaths());
13648        }
13649
13650        private void cleanUpResourcesLI(List<String> allCodePaths) {
13651            cleanUp();
13652            removeDexFiles(allCodePaths, instructionSets);
13653        }
13654
13655        String getPackageName() {
13656            return getAsecPackageName(cid);
13657        }
13658
13659        boolean doPostDeleteLI(boolean delete) {
13660            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13661            final List<String> allCodePaths = getAllCodePaths();
13662            boolean mounted = PackageHelper.isContainerMounted(cid);
13663            if (mounted) {
13664                // Unmount first
13665                if (PackageHelper.unMountSdDir(cid)) {
13666                    mounted = false;
13667                }
13668            }
13669            if (!mounted && delete) {
13670                cleanUpResourcesLI(allCodePaths);
13671            }
13672            return !mounted;
13673        }
13674
13675        @Override
13676        int doPreCopy() {
13677            if (isFwdLocked()) {
13678                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13679                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13680                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13681                }
13682            }
13683
13684            return PackageManager.INSTALL_SUCCEEDED;
13685        }
13686
13687        @Override
13688        int doPostCopy(int uid) {
13689            if (isFwdLocked()) {
13690                if (uid < Process.FIRST_APPLICATION_UID
13691                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13692                                RES_FILE_NAME)) {
13693                    Slog.e(TAG, "Failed to finalize " + cid);
13694                    PackageHelper.destroySdDir(cid);
13695                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13696                }
13697            }
13698
13699            return PackageManager.INSTALL_SUCCEEDED;
13700        }
13701    }
13702
13703    /**
13704     * Logic to handle movement of existing installed applications.
13705     */
13706    class MoveInstallArgs extends InstallArgs {
13707        private File codeFile;
13708        private File resourceFile;
13709
13710        /** New install */
13711        MoveInstallArgs(InstallParams params) {
13712            super(params.origin, params.move, params.observer, params.installFlags,
13713                    params.installerPackageName, params.volumeUuid,
13714                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13715                    params.grantedRuntimePermissions,
13716                    params.traceMethod, params.traceCookie, params.certificates);
13717        }
13718
13719        int copyApk(IMediaContainerService imcs, boolean temp) {
13720            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13721                    + move.fromUuid + " to " + move.toUuid);
13722            synchronized (mInstaller) {
13723                try {
13724                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13725                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13726                } catch (InstallerException e) {
13727                    Slog.w(TAG, "Failed to move app", e);
13728                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13729                }
13730            }
13731
13732            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13733            resourceFile = codeFile;
13734            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13735
13736            return PackageManager.INSTALL_SUCCEEDED;
13737        }
13738
13739        int doPreInstall(int status) {
13740            if (status != PackageManager.INSTALL_SUCCEEDED) {
13741                cleanUp(move.toUuid);
13742            }
13743            return status;
13744        }
13745
13746        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13747            if (status != PackageManager.INSTALL_SUCCEEDED) {
13748                cleanUp(move.toUuid);
13749                return false;
13750            }
13751
13752            // Reflect the move in app info
13753            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13754            pkg.setApplicationInfoCodePath(pkg.codePath);
13755            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13756            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13757            pkg.setApplicationInfoResourcePath(pkg.codePath);
13758            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13759            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13760
13761            return true;
13762        }
13763
13764        int doPostInstall(int status, int uid) {
13765            if (status == PackageManager.INSTALL_SUCCEEDED) {
13766                cleanUp(move.fromUuid);
13767            } else {
13768                cleanUp(move.toUuid);
13769            }
13770            return status;
13771        }
13772
13773        @Override
13774        String getCodePath() {
13775            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13776        }
13777
13778        @Override
13779        String getResourcePath() {
13780            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13781        }
13782
13783        private boolean cleanUp(String volumeUuid) {
13784            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13785                    move.dataAppName);
13786            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13787            final int[] userIds = sUserManager.getUserIds();
13788            synchronized (mInstallLock) {
13789                // Clean up both app data and code
13790                // All package moves are frozen until finished
13791                for (int userId : userIds) {
13792                    try {
13793                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13794                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13795                    } catch (InstallerException e) {
13796                        Slog.w(TAG, String.valueOf(e));
13797                    }
13798                }
13799                removeCodePathLI(codeFile);
13800            }
13801            return true;
13802        }
13803
13804        void cleanUpResourcesLI() {
13805            throw new UnsupportedOperationException();
13806        }
13807
13808        boolean doPostDeleteLI(boolean delete) {
13809            throw new UnsupportedOperationException();
13810        }
13811    }
13812
13813    static String getAsecPackageName(String packageCid) {
13814        int idx = packageCid.lastIndexOf("-");
13815        if (idx == -1) {
13816            return packageCid;
13817        }
13818        return packageCid.substring(0, idx);
13819    }
13820
13821    // Utility method used to create code paths based on package name and available index.
13822    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13823        String idxStr = "";
13824        int idx = 1;
13825        // Fall back to default value of idx=1 if prefix is not
13826        // part of oldCodePath
13827        if (oldCodePath != null) {
13828            String subStr = oldCodePath;
13829            // Drop the suffix right away
13830            if (suffix != null && subStr.endsWith(suffix)) {
13831                subStr = subStr.substring(0, subStr.length() - suffix.length());
13832            }
13833            // If oldCodePath already contains prefix find out the
13834            // ending index to either increment or decrement.
13835            int sidx = subStr.lastIndexOf(prefix);
13836            if (sidx != -1) {
13837                subStr = subStr.substring(sidx + prefix.length());
13838                if (subStr != null) {
13839                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13840                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13841                    }
13842                    try {
13843                        idx = Integer.parseInt(subStr);
13844                        if (idx <= 1) {
13845                            idx++;
13846                        } else {
13847                            idx--;
13848                        }
13849                    } catch(NumberFormatException e) {
13850                    }
13851                }
13852            }
13853        }
13854        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13855        return prefix + idxStr;
13856    }
13857
13858    private File getNextCodePath(File targetDir, String packageName) {
13859        int suffix = 1;
13860        File result;
13861        do {
13862            result = new File(targetDir, packageName + "-" + suffix);
13863            suffix++;
13864        } while (result.exists());
13865        return result;
13866    }
13867
13868    // Utility method that returns the relative package path with respect
13869    // to the installation directory. Like say for /data/data/com.test-1.apk
13870    // string com.test-1 is returned.
13871    static String deriveCodePathName(String codePath) {
13872        if (codePath == null) {
13873            return null;
13874        }
13875        final File codeFile = new File(codePath);
13876        final String name = codeFile.getName();
13877        if (codeFile.isDirectory()) {
13878            return name;
13879        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13880            final int lastDot = name.lastIndexOf('.');
13881            return name.substring(0, lastDot);
13882        } else {
13883            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13884            return null;
13885        }
13886    }
13887
13888    static class PackageInstalledInfo {
13889        String name;
13890        int uid;
13891        // The set of users that originally had this package installed.
13892        int[] origUsers;
13893        // The set of users that now have this package installed.
13894        int[] newUsers;
13895        PackageParser.Package pkg;
13896        int returnCode;
13897        String returnMsg;
13898        PackageRemovedInfo removedInfo;
13899        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13900
13901        public void setError(int code, String msg) {
13902            setReturnCode(code);
13903            setReturnMessage(msg);
13904            Slog.w(TAG, msg);
13905        }
13906
13907        public void setError(String msg, PackageParserException e) {
13908            setReturnCode(e.error);
13909            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13910            Slog.w(TAG, msg, e);
13911        }
13912
13913        public void setError(String msg, PackageManagerException e) {
13914            returnCode = e.error;
13915            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13916            Slog.w(TAG, msg, e);
13917        }
13918
13919        public void setReturnCode(int returnCode) {
13920            this.returnCode = returnCode;
13921            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13922            for (int i = 0; i < childCount; i++) {
13923                addedChildPackages.valueAt(i).returnCode = returnCode;
13924            }
13925        }
13926
13927        private void setReturnMessage(String returnMsg) {
13928            this.returnMsg = returnMsg;
13929            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13930            for (int i = 0; i < childCount; i++) {
13931                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13932            }
13933        }
13934
13935        // In some error cases we want to convey more info back to the observer
13936        String origPackage;
13937        String origPermission;
13938    }
13939
13940    /*
13941     * Install a non-existing package.
13942     */
13943    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13944            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13945            PackageInstalledInfo res) {
13946        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13947
13948        // Remember this for later, in case we need to rollback this install
13949        String pkgName = pkg.packageName;
13950
13951        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13952
13953        synchronized(mPackages) {
13954            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13955                // A package with the same name is already installed, though
13956                // it has been renamed to an older name.  The package we
13957                // are trying to install should be installed as an update to
13958                // the existing one, but that has not been requested, so bail.
13959                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13960                        + " without first uninstalling package running as "
13961                        + mSettings.mRenamedPackages.get(pkgName));
13962                return;
13963            }
13964            if (mPackages.containsKey(pkgName)) {
13965                // Don't allow installation over an existing package with the same name.
13966                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13967                        + " without first uninstalling.");
13968                return;
13969            }
13970        }
13971
13972        try {
13973            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13974                    System.currentTimeMillis(), user);
13975
13976            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13977
13978            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13979                prepareAppDataAfterInstallLIF(newPackage);
13980
13981            } else {
13982                // Remove package from internal structures, but keep around any
13983                // data that might have already existed
13984                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13985                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13986            }
13987        } catch (PackageManagerException e) {
13988            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13989        }
13990
13991        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13992    }
13993
13994    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13995        // Can't rotate keys during boot or if sharedUser.
13996        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13997                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13998            return false;
13999        }
14000        // app is using upgradeKeySets; make sure all are valid
14001        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14002        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14003        for (int i = 0; i < upgradeKeySets.length; i++) {
14004            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14005                Slog.wtf(TAG, "Package "
14006                         + (oldPs.name != null ? oldPs.name : "<null>")
14007                         + " contains upgrade-key-set reference to unknown key-set: "
14008                         + upgradeKeySets[i]
14009                         + " reverting to signatures check.");
14010                return false;
14011            }
14012        }
14013        return true;
14014    }
14015
14016    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14017        // Upgrade keysets are being used.  Determine if new package has a superset of the
14018        // required keys.
14019        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14020        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14021        for (int i = 0; i < upgradeKeySets.length; i++) {
14022            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14023            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14024                return true;
14025            }
14026        }
14027        return false;
14028    }
14029
14030    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14031        try (DigestInputStream digestStream =
14032                new DigestInputStream(new FileInputStream(file), digest)) {
14033            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14034        }
14035    }
14036
14037    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14038            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14039        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14040
14041        final PackageParser.Package oldPackage;
14042        final String pkgName = pkg.packageName;
14043        final int[] allUsers;
14044        final int[] installedUsers;
14045
14046        synchronized(mPackages) {
14047            oldPackage = mPackages.get(pkgName);
14048            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14049
14050            // don't allow upgrade to target a release SDK from a pre-release SDK
14051            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14052                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14053            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14054                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14055            if (oldTargetsPreRelease
14056                    && !newTargetsPreRelease
14057                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14058                Slog.w(TAG, "Can't install package targeting released sdk");
14059                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14060                return;
14061            }
14062
14063            // don't allow an upgrade from full to ephemeral
14064            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14065            if (isEphemeral && !oldIsEphemeral) {
14066                // can't downgrade from full to ephemeral
14067                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14068                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14069                return;
14070            }
14071
14072            // verify signatures are valid
14073            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14074            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14075                if (!checkUpgradeKeySetLP(ps, pkg)) {
14076                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14077                            "New package not signed by keys specified by upgrade-keysets: "
14078                                    + pkgName);
14079                    return;
14080                }
14081            } else {
14082                // default to original signature matching
14083                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14084                        != PackageManager.SIGNATURE_MATCH) {
14085                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14086                            "New package has a different signature: " + pkgName);
14087                    return;
14088                }
14089            }
14090
14091            // don't allow a system upgrade unless the upgrade hash matches
14092            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14093                byte[] digestBytes = null;
14094                try {
14095                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14096                    updateDigest(digest, new File(pkg.baseCodePath));
14097                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14098                        for (String path : pkg.splitCodePaths) {
14099                            updateDigest(digest, new File(path));
14100                        }
14101                    }
14102                    digestBytes = digest.digest();
14103                } catch (NoSuchAlgorithmException | IOException e) {
14104                    res.setError(INSTALL_FAILED_INVALID_APK,
14105                            "Could not compute hash: " + pkgName);
14106                    return;
14107                }
14108                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14109                    res.setError(INSTALL_FAILED_INVALID_APK,
14110                            "New package fails restrict-update check: " + pkgName);
14111                    return;
14112                }
14113                // retain upgrade restriction
14114                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14115            }
14116
14117            // Check for shared user id changes
14118            String invalidPackageName =
14119                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14120            if (invalidPackageName != null) {
14121                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14122                        "Package " + invalidPackageName + " tried to change user "
14123                                + oldPackage.mSharedUserId);
14124                return;
14125            }
14126
14127            // In case of rollback, remember per-user/profile install state
14128            allUsers = sUserManager.getUserIds();
14129            installedUsers = ps.queryInstalledUsers(allUsers, true);
14130        }
14131
14132        // Update what is removed
14133        res.removedInfo = new PackageRemovedInfo();
14134        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14135        res.removedInfo.removedPackage = oldPackage.packageName;
14136        res.removedInfo.isUpdate = true;
14137        res.removedInfo.origUsers = installedUsers;
14138        final int childCount = (oldPackage.childPackages != null)
14139                ? oldPackage.childPackages.size() : 0;
14140        for (int i = 0; i < childCount; i++) {
14141            boolean childPackageUpdated = false;
14142            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14143            if (res.addedChildPackages != null) {
14144                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14145                if (childRes != null) {
14146                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14147                    childRes.removedInfo.removedPackage = childPkg.packageName;
14148                    childRes.removedInfo.isUpdate = true;
14149                    childPackageUpdated = true;
14150                }
14151            }
14152            if (!childPackageUpdated) {
14153                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14154                childRemovedRes.removedPackage = childPkg.packageName;
14155                childRemovedRes.isUpdate = false;
14156                childRemovedRes.dataRemoved = true;
14157                synchronized (mPackages) {
14158                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14159                    if (childPs != null) {
14160                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14161                    }
14162                }
14163                if (res.removedInfo.removedChildPackages == null) {
14164                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14165                }
14166                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14167            }
14168        }
14169
14170        boolean sysPkg = (isSystemApp(oldPackage));
14171        if (sysPkg) {
14172            // Set the system/privileged flags as needed
14173            final boolean privileged =
14174                    (oldPackage.applicationInfo.privateFlags
14175                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14176            final int systemPolicyFlags = policyFlags
14177                    | PackageParser.PARSE_IS_SYSTEM
14178                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14179
14180            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14181                    user, allUsers, installerPackageName, res);
14182        } else {
14183            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14184                    user, allUsers, installerPackageName, res);
14185        }
14186    }
14187
14188    public List<String> getPreviousCodePaths(String packageName) {
14189        final PackageSetting ps = mSettings.mPackages.get(packageName);
14190        final List<String> result = new ArrayList<String>();
14191        if (ps != null && ps.oldCodePaths != null) {
14192            result.addAll(ps.oldCodePaths);
14193        }
14194        return result;
14195    }
14196
14197    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14198            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14199            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14200        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14201                + deletedPackage);
14202
14203        String pkgName = deletedPackage.packageName;
14204        boolean deletedPkg = true;
14205        boolean addedPkg = false;
14206        boolean updatedSettings = false;
14207        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14208        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14209                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14210
14211        final long origUpdateTime = (pkg.mExtras != null)
14212                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14213
14214        // First delete the existing package while retaining the data directory
14215        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14216                res.removedInfo, true, pkg)) {
14217            // If the existing package wasn't successfully deleted
14218            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14219            deletedPkg = false;
14220        } else {
14221            // Successfully deleted the old package; proceed with replace.
14222
14223            // If deleted package lived in a container, give users a chance to
14224            // relinquish resources before killing.
14225            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14226                if (DEBUG_INSTALL) {
14227                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14228                }
14229                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14230                final ArrayList<String> pkgList = new ArrayList<String>(1);
14231                pkgList.add(deletedPackage.applicationInfo.packageName);
14232                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14233            }
14234
14235            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14236                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14237            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14238
14239            try {
14240                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14241                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14242                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14243
14244                // Update the in-memory copy of the previous code paths.
14245                PackageSetting ps = mSettings.mPackages.get(pkgName);
14246                if (!killApp) {
14247                    if (ps.oldCodePaths == null) {
14248                        ps.oldCodePaths = new ArraySet<>();
14249                    }
14250                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14251                    if (deletedPackage.splitCodePaths != null) {
14252                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14253                    }
14254                } else {
14255                    ps.oldCodePaths = null;
14256                }
14257                if (ps.childPackageNames != null) {
14258                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14259                        final String childPkgName = ps.childPackageNames.get(i);
14260                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14261                        childPs.oldCodePaths = ps.oldCodePaths;
14262                    }
14263                }
14264                prepareAppDataAfterInstallLIF(newPackage);
14265                addedPkg = true;
14266            } catch (PackageManagerException e) {
14267                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14268            }
14269        }
14270
14271        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14272            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14273
14274            // Revert all internal state mutations and added folders for the failed install
14275            if (addedPkg) {
14276                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14277                        res.removedInfo, true, null);
14278            }
14279
14280            // Restore the old package
14281            if (deletedPkg) {
14282                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14283                File restoreFile = new File(deletedPackage.codePath);
14284                // Parse old package
14285                boolean oldExternal = isExternal(deletedPackage);
14286                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14287                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14288                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14289                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14290                try {
14291                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14292                            null);
14293                } catch (PackageManagerException e) {
14294                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14295                            + e.getMessage());
14296                    return;
14297                }
14298
14299                synchronized (mPackages) {
14300                    // Ensure the installer package name up to date
14301                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14302
14303                    // Update permissions for restored package
14304                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14305
14306                    mSettings.writeLPr();
14307                }
14308
14309                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14310            }
14311        } else {
14312            synchronized (mPackages) {
14313                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14314                if (ps != null) {
14315                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14316                    if (res.removedInfo.removedChildPackages != null) {
14317                        final int childCount = res.removedInfo.removedChildPackages.size();
14318                        // Iterate in reverse as we may modify the collection
14319                        for (int i = childCount - 1; i >= 0; i--) {
14320                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14321                            if (res.addedChildPackages.containsKey(childPackageName)) {
14322                                res.removedInfo.removedChildPackages.removeAt(i);
14323                            } else {
14324                                PackageRemovedInfo childInfo = res.removedInfo
14325                                        .removedChildPackages.valueAt(i);
14326                                childInfo.removedForAllUsers = mPackages.get(
14327                                        childInfo.removedPackage) == null;
14328                            }
14329                        }
14330                    }
14331                }
14332            }
14333        }
14334    }
14335
14336    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14337            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14338            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14339        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14340                + ", old=" + deletedPackage);
14341
14342        final boolean disabledSystem;
14343
14344        // Remove existing system package
14345        removePackageLI(deletedPackage, true);
14346
14347        synchronized (mPackages) {
14348            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14349        }
14350        if (!disabledSystem) {
14351            // We didn't need to disable the .apk as a current system package,
14352            // which means we are replacing another update that is already
14353            // installed.  We need to make sure to delete the older one's .apk.
14354            res.removedInfo.args = createInstallArgsForExisting(0,
14355                    deletedPackage.applicationInfo.getCodePath(),
14356                    deletedPackage.applicationInfo.getResourcePath(),
14357                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14358        } else {
14359            res.removedInfo.args = null;
14360        }
14361
14362        // Successfully disabled the old package. Now proceed with re-installation
14363        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14364                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14365        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14366
14367        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14368        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14369                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14370
14371        PackageParser.Package newPackage = null;
14372        try {
14373            // Add the package to the internal data structures
14374            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14375
14376            // Set the update and install times
14377            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14378            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14379                    System.currentTimeMillis());
14380
14381            // Update the package dynamic state if succeeded
14382            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14383                // Now that the install succeeded make sure we remove data
14384                // directories for any child package the update removed.
14385                final int deletedChildCount = (deletedPackage.childPackages != null)
14386                        ? deletedPackage.childPackages.size() : 0;
14387                final int newChildCount = (newPackage.childPackages != null)
14388                        ? newPackage.childPackages.size() : 0;
14389                for (int i = 0; i < deletedChildCount; i++) {
14390                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14391                    boolean childPackageDeleted = true;
14392                    for (int j = 0; j < newChildCount; j++) {
14393                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14394                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14395                            childPackageDeleted = false;
14396                            break;
14397                        }
14398                    }
14399                    if (childPackageDeleted) {
14400                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14401                                deletedChildPkg.packageName);
14402                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14403                            PackageRemovedInfo removedChildRes = res.removedInfo
14404                                    .removedChildPackages.get(deletedChildPkg.packageName);
14405                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14406                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14407                        }
14408                    }
14409                }
14410
14411                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14412                prepareAppDataAfterInstallLIF(newPackage);
14413            }
14414        } catch (PackageManagerException e) {
14415            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14416            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14417        }
14418
14419        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14420            // Re installation failed. Restore old information
14421            // Remove new pkg information
14422            if (newPackage != null) {
14423                removeInstalledPackageLI(newPackage, true);
14424            }
14425            // Add back the old system package
14426            try {
14427                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14428            } catch (PackageManagerException e) {
14429                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14430            }
14431
14432            synchronized (mPackages) {
14433                if (disabledSystem) {
14434                    enableSystemPackageLPw(deletedPackage);
14435                }
14436
14437                // Ensure the installer package name up to date
14438                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14439
14440                // Update permissions for restored package
14441                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14442
14443                mSettings.writeLPr();
14444            }
14445
14446            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14447                    + " after failed upgrade");
14448        }
14449    }
14450
14451    /**
14452     * Checks whether the parent or any of the child packages have a change shared
14453     * user. For a package to be a valid update the shred users of the parent and
14454     * the children should match. We may later support changing child shared users.
14455     * @param oldPkg The updated package.
14456     * @param newPkg The update package.
14457     * @return The shared user that change between the versions.
14458     */
14459    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14460            PackageParser.Package newPkg) {
14461        // Check parent shared user
14462        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14463            return newPkg.packageName;
14464        }
14465        // Check child shared users
14466        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14467        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14468        for (int i = 0; i < newChildCount; i++) {
14469            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14470            // If this child was present, did it have the same shared user?
14471            for (int j = 0; j < oldChildCount; j++) {
14472                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14473                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14474                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14475                    return newChildPkg.packageName;
14476                }
14477            }
14478        }
14479        return null;
14480    }
14481
14482    private void removeNativeBinariesLI(PackageSetting ps) {
14483        // Remove the lib path for the parent package
14484        if (ps != null) {
14485            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14486            // Remove the lib path for the child packages
14487            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14488            for (int i = 0; i < childCount; i++) {
14489                PackageSetting childPs = null;
14490                synchronized (mPackages) {
14491                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14492                }
14493                if (childPs != null) {
14494                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14495                            .legacyNativeLibraryPathString);
14496                }
14497            }
14498        }
14499    }
14500
14501    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14502        // Enable the parent package
14503        mSettings.enableSystemPackageLPw(pkg.packageName);
14504        // Enable the child packages
14505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14506        for (int i = 0; i < childCount; i++) {
14507            PackageParser.Package childPkg = pkg.childPackages.get(i);
14508            mSettings.enableSystemPackageLPw(childPkg.packageName);
14509        }
14510    }
14511
14512    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14513            PackageParser.Package newPkg) {
14514        // Disable the parent package (parent always replaced)
14515        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14516        // Disable the child packages
14517        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14518        for (int i = 0; i < childCount; i++) {
14519            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14520            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14521            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14522        }
14523        return disabled;
14524    }
14525
14526    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14527            String installerPackageName) {
14528        // Enable the parent package
14529        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14530        // Enable the child packages
14531        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14532        for (int i = 0; i < childCount; i++) {
14533            PackageParser.Package childPkg = pkg.childPackages.get(i);
14534            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14535        }
14536    }
14537
14538    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14539        // Collect all used permissions in the UID
14540        ArraySet<String> usedPermissions = new ArraySet<>();
14541        final int packageCount = su.packages.size();
14542        for (int i = 0; i < packageCount; i++) {
14543            PackageSetting ps = su.packages.valueAt(i);
14544            if (ps.pkg == null) {
14545                continue;
14546            }
14547            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14548            for (int j = 0; j < requestedPermCount; j++) {
14549                String permission = ps.pkg.requestedPermissions.get(j);
14550                BasePermission bp = mSettings.mPermissions.get(permission);
14551                if (bp != null) {
14552                    usedPermissions.add(permission);
14553                }
14554            }
14555        }
14556
14557        PermissionsState permissionsState = su.getPermissionsState();
14558        // Prune install permissions
14559        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14560        final int installPermCount = installPermStates.size();
14561        for (int i = installPermCount - 1; i >= 0;  i--) {
14562            PermissionState permissionState = installPermStates.get(i);
14563            if (!usedPermissions.contains(permissionState.getName())) {
14564                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14565                if (bp != null) {
14566                    permissionsState.revokeInstallPermission(bp);
14567                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14568                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14569                }
14570            }
14571        }
14572
14573        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14574
14575        // Prune runtime permissions
14576        for (int userId : allUserIds) {
14577            List<PermissionState> runtimePermStates = permissionsState
14578                    .getRuntimePermissionStates(userId);
14579            final int runtimePermCount = runtimePermStates.size();
14580            for (int i = runtimePermCount - 1; i >= 0; i--) {
14581                PermissionState permissionState = runtimePermStates.get(i);
14582                if (!usedPermissions.contains(permissionState.getName())) {
14583                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14584                    if (bp != null) {
14585                        permissionsState.revokeRuntimePermission(bp, userId);
14586                        permissionsState.updatePermissionFlags(bp, userId,
14587                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14588                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14589                                runtimePermissionChangedUserIds, userId);
14590                    }
14591                }
14592            }
14593        }
14594
14595        return runtimePermissionChangedUserIds;
14596    }
14597
14598    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14599            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14600        // Update the parent package setting
14601        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14602                res, user);
14603        // Update the child packages setting
14604        final int childCount = (newPackage.childPackages != null)
14605                ? newPackage.childPackages.size() : 0;
14606        for (int i = 0; i < childCount; i++) {
14607            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14608            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14609            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14610                    childRes.origUsers, childRes, user);
14611        }
14612    }
14613
14614    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14615            String installerPackageName, int[] allUsers, int[] installedForUsers,
14616            PackageInstalledInfo res, UserHandle user) {
14617        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14618
14619        String pkgName = newPackage.packageName;
14620        synchronized (mPackages) {
14621            //write settings. the installStatus will be incomplete at this stage.
14622            //note that the new package setting would have already been
14623            //added to mPackages. It hasn't been persisted yet.
14624            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14625            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14626            mSettings.writeLPr();
14627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14628        }
14629
14630        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14631        synchronized (mPackages) {
14632            updatePermissionsLPw(newPackage.packageName, newPackage,
14633                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14634                            ? UPDATE_PERMISSIONS_ALL : 0));
14635            // For system-bundled packages, we assume that installing an upgraded version
14636            // of the package implies that the user actually wants to run that new code,
14637            // so we enable the package.
14638            PackageSetting ps = mSettings.mPackages.get(pkgName);
14639            final int userId = user.getIdentifier();
14640            if (ps != null) {
14641                if (isSystemApp(newPackage)) {
14642                    if (DEBUG_INSTALL) {
14643                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14644                    }
14645                    // Enable system package for requested users
14646                    if (res.origUsers != null) {
14647                        for (int origUserId : res.origUsers) {
14648                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14649                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14650                                        origUserId, installerPackageName);
14651                            }
14652                        }
14653                    }
14654                    // Also convey the prior install/uninstall state
14655                    if (allUsers != null && installedForUsers != null) {
14656                        for (int currentUserId : allUsers) {
14657                            final boolean installed = ArrayUtils.contains(
14658                                    installedForUsers, currentUserId);
14659                            if (DEBUG_INSTALL) {
14660                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14661                            }
14662                            ps.setInstalled(installed, currentUserId);
14663                        }
14664                        // these install state changes will be persisted in the
14665                        // upcoming call to mSettings.writeLPr().
14666                    }
14667                }
14668                // It's implied that when a user requests installation, they want the app to be
14669                // installed and enabled.
14670                if (userId != UserHandle.USER_ALL) {
14671                    ps.setInstalled(true, userId);
14672                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14673                }
14674            }
14675            res.name = pkgName;
14676            res.uid = newPackage.applicationInfo.uid;
14677            res.pkg = newPackage;
14678            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14679            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14680            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14681            //to update install status
14682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14683            mSettings.writeLPr();
14684            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14685        }
14686
14687        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14688    }
14689
14690    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14691        try {
14692            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14693            installPackageLI(args, res);
14694        } finally {
14695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14696        }
14697    }
14698
14699    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14700        final int installFlags = args.installFlags;
14701        final String installerPackageName = args.installerPackageName;
14702        final String volumeUuid = args.volumeUuid;
14703        final File tmpPackageFile = new File(args.getCodePath());
14704        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14705        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14706                || (args.volumeUuid != null));
14707        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14708        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14709        boolean replace = false;
14710        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14711        if (args.move != null) {
14712            // moving a complete application; perform an initial scan on the new install location
14713            scanFlags |= SCAN_INITIAL;
14714        }
14715        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14716            scanFlags |= SCAN_DONT_KILL_APP;
14717        }
14718
14719        // Result object to be returned
14720        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14721
14722        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14723
14724        // Sanity check
14725        if (ephemeral && (forwardLocked || onExternal)) {
14726            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14727                    + " external=" + onExternal);
14728            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14729            return;
14730        }
14731
14732        // Retrieve PackageSettings and parse package
14733        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14734                | PackageParser.PARSE_ENFORCE_CODE
14735                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14736                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14737                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14738                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14739        PackageParser pp = new PackageParser();
14740        pp.setSeparateProcesses(mSeparateProcesses);
14741        pp.setDisplayMetrics(mMetrics);
14742
14743        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14744        final PackageParser.Package pkg;
14745        try {
14746            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14747        } catch (PackageParserException e) {
14748            res.setError("Failed parse during installPackageLI", e);
14749            return;
14750        } finally {
14751            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14752        }
14753
14754        // If we are installing a clustered package add results for the children
14755        if (pkg.childPackages != null) {
14756            synchronized (mPackages) {
14757                final int childCount = pkg.childPackages.size();
14758                for (int i = 0; i < childCount; i++) {
14759                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14760                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14761                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14762                    childRes.pkg = childPkg;
14763                    childRes.name = childPkg.packageName;
14764                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14765                    if (childPs != null) {
14766                        childRes.origUsers = childPs.queryInstalledUsers(
14767                                sUserManager.getUserIds(), true);
14768                    }
14769                    if ((mPackages.containsKey(childPkg.packageName))) {
14770                        childRes.removedInfo = new PackageRemovedInfo();
14771                        childRes.removedInfo.removedPackage = childPkg.packageName;
14772                    }
14773                    if (res.addedChildPackages == null) {
14774                        res.addedChildPackages = new ArrayMap<>();
14775                    }
14776                    res.addedChildPackages.put(childPkg.packageName, childRes);
14777                }
14778            }
14779        }
14780
14781        // If package doesn't declare API override, mark that we have an install
14782        // time CPU ABI override.
14783        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14784            pkg.cpuAbiOverride = args.abiOverride;
14785        }
14786
14787        String pkgName = res.name = pkg.packageName;
14788        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14789            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14790                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14791                return;
14792            }
14793        }
14794
14795        try {
14796            // either use what we've been given or parse directly from the APK
14797            if (args.certificates != null) {
14798                try {
14799                    PackageParser.populateCertificates(pkg, args.certificates);
14800                } catch (PackageParserException e) {
14801                    // there was something wrong with the certificates we were given;
14802                    // try to pull them from the APK
14803                    PackageParser.collectCertificates(pkg, parseFlags);
14804                }
14805            } else {
14806                PackageParser.collectCertificates(pkg, parseFlags);
14807            }
14808        } catch (PackageParserException e) {
14809            res.setError("Failed collect during installPackageLI", e);
14810            return;
14811        }
14812
14813        // Get rid of all references to package scan path via parser.
14814        pp = null;
14815        String oldCodePath = null;
14816        boolean systemApp = false;
14817        synchronized (mPackages) {
14818            // Check if installing already existing package
14819            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14820                String oldName = mSettings.mRenamedPackages.get(pkgName);
14821                if (pkg.mOriginalPackages != null
14822                        && pkg.mOriginalPackages.contains(oldName)
14823                        && mPackages.containsKey(oldName)) {
14824                    // This package is derived from an original package,
14825                    // and this device has been updating from that original
14826                    // name.  We must continue using the original name, so
14827                    // rename the new package here.
14828                    pkg.setPackageName(oldName);
14829                    pkgName = pkg.packageName;
14830                    replace = true;
14831                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14832                            + oldName + " pkgName=" + pkgName);
14833                } else if (mPackages.containsKey(pkgName)) {
14834                    // This package, under its official name, already exists
14835                    // on the device; we should replace it.
14836                    replace = true;
14837                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14838                }
14839
14840                // Child packages are installed through the parent package
14841                if (pkg.parentPackage != null) {
14842                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14843                            "Package " + pkg.packageName + " is child of package "
14844                                    + pkg.parentPackage.parentPackage + ". Child packages "
14845                                    + "can be updated only through the parent package.");
14846                    return;
14847                }
14848
14849                if (replace) {
14850                    // Prevent apps opting out from runtime permissions
14851                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14852                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14853                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14854                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14855                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14856                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14857                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14858                                        + " doesn't support runtime permissions but the old"
14859                                        + " target SDK " + oldTargetSdk + " does.");
14860                        return;
14861                    }
14862
14863                    // Prevent installing of child packages
14864                    if (oldPackage.parentPackage != null) {
14865                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14866                                "Package " + pkg.packageName + " is child of package "
14867                                        + oldPackage.parentPackage + ". Child packages "
14868                                        + "can be updated only through the parent package.");
14869                        return;
14870                    }
14871                }
14872            }
14873
14874            PackageSetting ps = mSettings.mPackages.get(pkgName);
14875            if (ps != null) {
14876                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14877
14878                // Quick sanity check that we're signed correctly if updating;
14879                // we'll check this again later when scanning, but we want to
14880                // bail early here before tripping over redefined permissions.
14881                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14882                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14883                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14884                                + pkg.packageName + " upgrade keys do not match the "
14885                                + "previously installed version");
14886                        return;
14887                    }
14888                } else {
14889                    try {
14890                        verifySignaturesLP(ps, pkg);
14891                    } catch (PackageManagerException e) {
14892                        res.setError(e.error, e.getMessage());
14893                        return;
14894                    }
14895                }
14896
14897                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14898                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14899                    systemApp = (ps.pkg.applicationInfo.flags &
14900                            ApplicationInfo.FLAG_SYSTEM) != 0;
14901                }
14902                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14903            }
14904
14905            // Check whether the newly-scanned package wants to define an already-defined perm
14906            int N = pkg.permissions.size();
14907            for (int i = N-1; i >= 0; i--) {
14908                PackageParser.Permission perm = pkg.permissions.get(i);
14909                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14910                if (bp != null) {
14911                    // If the defining package is signed with our cert, it's okay.  This
14912                    // also includes the "updating the same package" case, of course.
14913                    // "updating same package" could also involve key-rotation.
14914                    final boolean sigsOk;
14915                    if (bp.sourcePackage.equals(pkg.packageName)
14916                            && (bp.packageSetting instanceof PackageSetting)
14917                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14918                                    scanFlags))) {
14919                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14920                    } else {
14921                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14922                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14923                    }
14924                    if (!sigsOk) {
14925                        // If the owning package is the system itself, we log but allow
14926                        // install to proceed; we fail the install on all other permission
14927                        // redefinitions.
14928                        if (!bp.sourcePackage.equals("android")) {
14929                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14930                                    + pkg.packageName + " attempting to redeclare permission "
14931                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14932                            res.origPermission = perm.info.name;
14933                            res.origPackage = bp.sourcePackage;
14934                            return;
14935                        } else {
14936                            Slog.w(TAG, "Package " + pkg.packageName
14937                                    + " attempting to redeclare system permission "
14938                                    + perm.info.name + "; ignoring new declaration");
14939                            pkg.permissions.remove(i);
14940                        }
14941                    }
14942                }
14943            }
14944        }
14945
14946        if (systemApp) {
14947            if (onExternal) {
14948                // Abort update; system app can't be replaced with app on sdcard
14949                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14950                        "Cannot install updates to system apps on sdcard");
14951                return;
14952            } else if (ephemeral) {
14953                // Abort update; system app can't be replaced with an ephemeral app
14954                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14955                        "Cannot update a system app with an ephemeral app");
14956                return;
14957            }
14958        }
14959
14960        if (args.move != null) {
14961            // We did an in-place move, so dex is ready to roll
14962            scanFlags |= SCAN_NO_DEX;
14963            scanFlags |= SCAN_MOVE;
14964
14965            synchronized (mPackages) {
14966                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14967                if (ps == null) {
14968                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14969                            "Missing settings for moved package " + pkgName);
14970                }
14971
14972                // We moved the entire application as-is, so bring over the
14973                // previously derived ABI information.
14974                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14975                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14976            }
14977
14978        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14979            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14980            scanFlags |= SCAN_NO_DEX;
14981
14982            try {
14983                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14984                    args.abiOverride : pkg.cpuAbiOverride);
14985                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14986                        true /* extract libs */);
14987            } catch (PackageManagerException pme) {
14988                Slog.e(TAG, "Error deriving application ABI", pme);
14989                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14990                return;
14991            }
14992
14993            // Shared libraries for the package need to be updated.
14994            synchronized (mPackages) {
14995                try {
14996                    updateSharedLibrariesLPw(pkg, null);
14997                } catch (PackageManagerException e) {
14998                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14999                }
15000            }
15001            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15002            // Do not run PackageDexOptimizer through the local performDexOpt
15003            // method because `pkg` may not be in `mPackages` yet.
15004            //
15005            // Also, don't fail application installs if the dexopt step fails.
15006            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15007                    null /* instructionSets */, false /* checkProfiles */,
15008                    getCompilerFilterForReason(REASON_INSTALL),
15009                    getOrCreateCompilerPackageStats(pkg));
15010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15011
15012            // Notify BackgroundDexOptService that the package has been changed.
15013            // If this is an update of a package which used to fail to compile,
15014            // BDOS will remove it from its blacklist.
15015            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15016        }
15017
15018        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15019            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15020            return;
15021        }
15022
15023        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15024
15025        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15026                "installPackageLI")) {
15027            if (replace) {
15028                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15029                        installerPackageName, res);
15030            } else {
15031                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15032                        args.user, installerPackageName, volumeUuid, res);
15033            }
15034        }
15035        synchronized (mPackages) {
15036            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15037            if (ps != null) {
15038                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15039            }
15040
15041            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15042            for (int i = 0; i < childCount; i++) {
15043                PackageParser.Package childPkg = pkg.childPackages.get(i);
15044                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15045                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15046                if (childPs != null) {
15047                    childRes.newUsers = childPs.queryInstalledUsers(
15048                            sUserManager.getUserIds(), true);
15049                }
15050            }
15051        }
15052    }
15053
15054    private void startIntentFilterVerifications(int userId, boolean replacing,
15055            PackageParser.Package pkg) {
15056        if (mIntentFilterVerifierComponent == null) {
15057            Slog.w(TAG, "No IntentFilter verification will not be done as "
15058                    + "there is no IntentFilterVerifier available!");
15059            return;
15060        }
15061
15062        final int verifierUid = getPackageUid(
15063                mIntentFilterVerifierComponent.getPackageName(),
15064                MATCH_DEBUG_TRIAGED_MISSING,
15065                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15066
15067        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15068        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15069        mHandler.sendMessage(msg);
15070
15071        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15072        for (int i = 0; i < childCount; i++) {
15073            PackageParser.Package childPkg = pkg.childPackages.get(i);
15074            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15075            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15076            mHandler.sendMessage(msg);
15077        }
15078    }
15079
15080    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15081            PackageParser.Package pkg) {
15082        int size = pkg.activities.size();
15083        if (size == 0) {
15084            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15085                    "No activity, so no need to verify any IntentFilter!");
15086            return;
15087        }
15088
15089        final boolean hasDomainURLs = hasDomainURLs(pkg);
15090        if (!hasDomainURLs) {
15091            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15092                    "No domain URLs, so no need to verify any IntentFilter!");
15093            return;
15094        }
15095
15096        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15097                + " if any IntentFilter from the " + size
15098                + " Activities needs verification ...");
15099
15100        int count = 0;
15101        final String packageName = pkg.packageName;
15102
15103        synchronized (mPackages) {
15104            // If this is a new install and we see that we've already run verification for this
15105            // package, we have nothing to do: it means the state was restored from backup.
15106            if (!replacing) {
15107                IntentFilterVerificationInfo ivi =
15108                        mSettings.getIntentFilterVerificationLPr(packageName);
15109                if (ivi != null) {
15110                    if (DEBUG_DOMAIN_VERIFICATION) {
15111                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15112                                + ivi.getStatusString());
15113                    }
15114                    return;
15115                }
15116            }
15117
15118            // If any filters need to be verified, then all need to be.
15119            boolean needToVerify = false;
15120            for (PackageParser.Activity a : pkg.activities) {
15121                for (ActivityIntentInfo filter : a.intents) {
15122                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15123                        if (DEBUG_DOMAIN_VERIFICATION) {
15124                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15125                        }
15126                        needToVerify = true;
15127                        break;
15128                    }
15129                }
15130            }
15131
15132            if (needToVerify) {
15133                final int verificationId = mIntentFilterVerificationToken++;
15134                for (PackageParser.Activity a : pkg.activities) {
15135                    for (ActivityIntentInfo filter : a.intents) {
15136                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15137                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15138                                    "Verification needed for IntentFilter:" + filter.toString());
15139                            mIntentFilterVerifier.addOneIntentFilterVerification(
15140                                    verifierUid, userId, verificationId, filter, packageName);
15141                            count++;
15142                        }
15143                    }
15144                }
15145            }
15146        }
15147
15148        if (count > 0) {
15149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15150                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15151                    +  " for userId:" + userId);
15152            mIntentFilterVerifier.startVerifications(userId);
15153        } else {
15154            if (DEBUG_DOMAIN_VERIFICATION) {
15155                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15156            }
15157        }
15158    }
15159
15160    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15161        final ComponentName cn  = filter.activity.getComponentName();
15162        final String packageName = cn.getPackageName();
15163
15164        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15165                packageName);
15166        if (ivi == null) {
15167            return true;
15168        }
15169        int status = ivi.getStatus();
15170        switch (status) {
15171            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15172            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15173                return true;
15174
15175            default:
15176                // Nothing to do
15177                return false;
15178        }
15179    }
15180
15181    private static boolean isMultiArch(ApplicationInfo info) {
15182        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15183    }
15184
15185    private static boolean isExternal(PackageParser.Package pkg) {
15186        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15187    }
15188
15189    private static boolean isExternal(PackageSetting ps) {
15190        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15191    }
15192
15193    private static boolean isEphemeral(PackageParser.Package pkg) {
15194        return pkg.applicationInfo.isEphemeralApp();
15195    }
15196
15197    private static boolean isEphemeral(PackageSetting ps) {
15198        return ps.pkg != null && isEphemeral(ps.pkg);
15199    }
15200
15201    private static boolean isSystemApp(PackageParser.Package pkg) {
15202        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15203    }
15204
15205    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15206        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15207    }
15208
15209    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15210        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15211    }
15212
15213    private static boolean isSystemApp(PackageSetting ps) {
15214        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15215    }
15216
15217    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15218        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15219    }
15220
15221    private int packageFlagsToInstallFlags(PackageSetting ps) {
15222        int installFlags = 0;
15223        if (isEphemeral(ps)) {
15224            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15225        }
15226        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15227            // This existing package was an external ASEC install when we have
15228            // the external flag without a UUID
15229            installFlags |= PackageManager.INSTALL_EXTERNAL;
15230        }
15231        if (ps.isForwardLocked()) {
15232            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15233        }
15234        return installFlags;
15235    }
15236
15237    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15238        if (isExternal(pkg)) {
15239            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15240                return StorageManager.UUID_PRIMARY_PHYSICAL;
15241            } else {
15242                return pkg.volumeUuid;
15243            }
15244        } else {
15245            return StorageManager.UUID_PRIVATE_INTERNAL;
15246        }
15247    }
15248
15249    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15250        if (isExternal(pkg)) {
15251            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15252                return mSettings.getExternalVersion();
15253            } else {
15254                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15255            }
15256        } else {
15257            return mSettings.getInternalVersion();
15258        }
15259    }
15260
15261    private void deleteTempPackageFiles() {
15262        final FilenameFilter filter = new FilenameFilter() {
15263            public boolean accept(File dir, String name) {
15264                return name.startsWith("vmdl") && name.endsWith(".tmp");
15265            }
15266        };
15267        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15268            file.delete();
15269        }
15270    }
15271
15272    @Override
15273    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15274            int flags) {
15275        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15276                flags);
15277    }
15278
15279    @Override
15280    public void deletePackage(final String packageName,
15281            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15282        mContext.enforceCallingOrSelfPermission(
15283                android.Manifest.permission.DELETE_PACKAGES, null);
15284        Preconditions.checkNotNull(packageName);
15285        Preconditions.checkNotNull(observer);
15286        final int uid = Binder.getCallingUid();
15287        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15288        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15289        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15290            mContext.enforceCallingOrSelfPermission(
15291                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15292                    "deletePackage for user " + userId);
15293        }
15294
15295        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15296            try {
15297                observer.onPackageDeleted(packageName,
15298                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15299            } catch (RemoteException re) {
15300            }
15301            return;
15302        }
15303
15304        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15305            try {
15306                observer.onPackageDeleted(packageName,
15307                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15308            } catch (RemoteException re) {
15309            }
15310            return;
15311        }
15312
15313        if (DEBUG_REMOVE) {
15314            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15315                    + " deleteAllUsers: " + deleteAllUsers );
15316        }
15317        // Queue up an async operation since the package deletion may take a little while.
15318        mHandler.post(new Runnable() {
15319            public void run() {
15320                mHandler.removeCallbacks(this);
15321                int returnCode;
15322                if (!deleteAllUsers) {
15323                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15324                } else {
15325                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15326                    // If nobody is blocking uninstall, proceed with delete for all users
15327                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15328                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15329                    } else {
15330                        // Otherwise uninstall individually for users with blockUninstalls=false
15331                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15332                        for (int userId : users) {
15333                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15334                                returnCode = deletePackageX(packageName, userId, userFlags);
15335                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15336                                    Slog.w(TAG, "Package delete failed for user " + userId
15337                                            + ", returnCode " + returnCode);
15338                                }
15339                            }
15340                        }
15341                        // The app has only been marked uninstalled for certain users.
15342                        // We still need to report that delete was blocked
15343                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15344                    }
15345                }
15346                try {
15347                    observer.onPackageDeleted(packageName, returnCode, null);
15348                } catch (RemoteException e) {
15349                    Log.i(TAG, "Observer no longer exists.");
15350                } //end catch
15351            } //end run
15352        });
15353    }
15354
15355    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15356        int[] result = EMPTY_INT_ARRAY;
15357        for (int userId : userIds) {
15358            if (getBlockUninstallForUser(packageName, userId)) {
15359                result = ArrayUtils.appendInt(result, userId);
15360            }
15361        }
15362        return result;
15363    }
15364
15365    @Override
15366    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15367        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15368    }
15369
15370    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15371        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15372                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15373        try {
15374            if (dpm != null) {
15375                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15376                        /* callingUserOnly =*/ false);
15377                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15378                        : deviceOwnerComponentName.getPackageName();
15379                // Does the package contains the device owner?
15380                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15381                // this check is probably not needed, since DO should be registered as a device
15382                // admin on some user too. (Original bug for this: b/17657954)
15383                if (packageName.equals(deviceOwnerPackageName)) {
15384                    return true;
15385                }
15386                // Does it contain a device admin for any user?
15387                int[] users;
15388                if (userId == UserHandle.USER_ALL) {
15389                    users = sUserManager.getUserIds();
15390                } else {
15391                    users = new int[]{userId};
15392                }
15393                for (int i = 0; i < users.length; ++i) {
15394                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15395                        return true;
15396                    }
15397                }
15398            }
15399        } catch (RemoteException e) {
15400        }
15401        return false;
15402    }
15403
15404    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15405        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15406    }
15407
15408    /**
15409     *  This method is an internal method that could be get invoked either
15410     *  to delete an installed package or to clean up a failed installation.
15411     *  After deleting an installed package, a broadcast is sent to notify any
15412     *  listeners that the package has been removed. For cleaning up a failed
15413     *  installation, the broadcast is not necessary since the package's
15414     *  installation wouldn't have sent the initial broadcast either
15415     *  The key steps in deleting a package are
15416     *  deleting the package information in internal structures like mPackages,
15417     *  deleting the packages base directories through installd
15418     *  updating mSettings to reflect current status
15419     *  persisting settings for later use
15420     *  sending a broadcast if necessary
15421     */
15422    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15423        final PackageRemovedInfo info = new PackageRemovedInfo();
15424        final boolean res;
15425
15426        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15427                ? UserHandle.USER_ALL : userId;
15428
15429        if (isPackageDeviceAdmin(packageName, removeUser)) {
15430            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15431            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15432        }
15433
15434        PackageSetting uninstalledPs = null;
15435
15436        // for the uninstall-updates case and restricted profiles, remember the per-
15437        // user handle installed state
15438        int[] allUsers;
15439        synchronized (mPackages) {
15440            uninstalledPs = mSettings.mPackages.get(packageName);
15441            if (uninstalledPs == null) {
15442                Slog.w(TAG, "Not removing non-existent package " + packageName);
15443                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15444            }
15445            allUsers = sUserManager.getUserIds();
15446            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15447        }
15448
15449        final int freezeUser;
15450        if (isUpdatedSystemApp(uninstalledPs)
15451                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15452            // We're downgrading a system app, which will apply to all users, so
15453            // freeze them all during the downgrade
15454            freezeUser = UserHandle.USER_ALL;
15455        } else {
15456            freezeUser = removeUser;
15457        }
15458
15459        synchronized (mInstallLock) {
15460            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15461            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15462                    deleteFlags, "deletePackageX")) {
15463                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15464                        deleteFlags | REMOVE_CHATTY, info, true, null);
15465            }
15466            synchronized (mPackages) {
15467                if (res) {
15468                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15469                }
15470            }
15471        }
15472
15473        if (res) {
15474            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15475            info.sendPackageRemovedBroadcasts(killApp);
15476            info.sendSystemPackageUpdatedBroadcasts();
15477            info.sendSystemPackageAppearedBroadcasts();
15478        }
15479        // Force a gc here.
15480        Runtime.getRuntime().gc();
15481        // Delete the resources here after sending the broadcast to let
15482        // other processes clean up before deleting resources.
15483        if (info.args != null) {
15484            synchronized (mInstallLock) {
15485                info.args.doPostDeleteLI(true);
15486            }
15487        }
15488
15489        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15490    }
15491
15492    class PackageRemovedInfo {
15493        String removedPackage;
15494        int uid = -1;
15495        int removedAppId = -1;
15496        int[] origUsers;
15497        int[] removedUsers = null;
15498        boolean isRemovedPackageSystemUpdate = false;
15499        boolean isUpdate;
15500        boolean dataRemoved;
15501        boolean removedForAllUsers;
15502        // Clean up resources deleted packages.
15503        InstallArgs args = null;
15504        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15505        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15506
15507        void sendPackageRemovedBroadcasts(boolean killApp) {
15508            sendPackageRemovedBroadcastInternal(killApp);
15509            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15510            for (int i = 0; i < childCount; i++) {
15511                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15512                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15513            }
15514        }
15515
15516        void sendSystemPackageUpdatedBroadcasts() {
15517            if (isRemovedPackageSystemUpdate) {
15518                sendSystemPackageUpdatedBroadcastsInternal();
15519                final int childCount = (removedChildPackages != null)
15520                        ? removedChildPackages.size() : 0;
15521                for (int i = 0; i < childCount; i++) {
15522                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15523                    if (childInfo.isRemovedPackageSystemUpdate) {
15524                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15525                    }
15526                }
15527            }
15528        }
15529
15530        void sendSystemPackageAppearedBroadcasts() {
15531            final int packageCount = (appearedChildPackages != null)
15532                    ? appearedChildPackages.size() : 0;
15533            for (int i = 0; i < packageCount; i++) {
15534                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15535                for (int userId : installedInfo.newUsers) {
15536                    sendPackageAddedForUser(installedInfo.name, true,
15537                            UserHandle.getAppId(installedInfo.uid), userId);
15538                }
15539            }
15540        }
15541
15542        private void sendSystemPackageUpdatedBroadcastsInternal() {
15543            Bundle extras = new Bundle(2);
15544            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15545            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15546            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15547                    extras, 0, null, null, null);
15548            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15549                    extras, 0, null, null, null);
15550            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15551                    null, 0, removedPackage, null, null);
15552        }
15553
15554        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15555            Bundle extras = new Bundle(2);
15556            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15557            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15558            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15559            if (isUpdate || isRemovedPackageSystemUpdate) {
15560                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15561            }
15562            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15563            if (removedPackage != null) {
15564                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15565                        extras, 0, null, null, removedUsers);
15566                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15567                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15568                            removedPackage, extras, 0, null, null, removedUsers);
15569                }
15570            }
15571            if (removedAppId >= 0) {
15572                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15573                        removedUsers);
15574            }
15575        }
15576    }
15577
15578    /*
15579     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15580     * flag is not set, the data directory is removed as well.
15581     * make sure this flag is set for partially installed apps. If not its meaningless to
15582     * delete a partially installed application.
15583     */
15584    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15585            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15586        String packageName = ps.name;
15587        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15588        // Retrieve object to delete permissions for shared user later on
15589        final PackageParser.Package deletedPkg;
15590        final PackageSetting deletedPs;
15591        // reader
15592        synchronized (mPackages) {
15593            deletedPkg = mPackages.get(packageName);
15594            deletedPs = mSettings.mPackages.get(packageName);
15595            if (outInfo != null) {
15596                outInfo.removedPackage = packageName;
15597                outInfo.removedUsers = deletedPs != null
15598                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15599                        : null;
15600            }
15601        }
15602
15603        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15604
15605        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15606            final PackageParser.Package resolvedPkg;
15607            if (deletedPkg != null) {
15608                resolvedPkg = deletedPkg;
15609            } else {
15610                // We don't have a parsed package when it lives on an ejected
15611                // adopted storage device, so fake something together
15612                resolvedPkg = new PackageParser.Package(ps.name);
15613                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15614            }
15615            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15616                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15617            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15618            if (outInfo != null) {
15619                outInfo.dataRemoved = true;
15620            }
15621            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15622        }
15623
15624        // writer
15625        synchronized (mPackages) {
15626            if (deletedPs != null) {
15627                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15628                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15629                    clearDefaultBrowserIfNeeded(packageName);
15630                    if (outInfo != null) {
15631                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15632                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15633                    }
15634                    updatePermissionsLPw(deletedPs.name, null, 0);
15635                    if (deletedPs.sharedUser != null) {
15636                        // Remove permissions associated with package. Since runtime
15637                        // permissions are per user we have to kill the removed package
15638                        // or packages running under the shared user of the removed
15639                        // package if revoking the permissions requested only by the removed
15640                        // package is successful and this causes a change in gids.
15641                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15642                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15643                                    userId);
15644                            if (userIdToKill == UserHandle.USER_ALL
15645                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15646                                // If gids changed for this user, kill all affected packages.
15647                                mHandler.post(new Runnable() {
15648                                    @Override
15649                                    public void run() {
15650                                        // This has to happen with no lock held.
15651                                        killApplication(deletedPs.name, deletedPs.appId,
15652                                                KILL_APP_REASON_GIDS_CHANGED);
15653                                    }
15654                                });
15655                                break;
15656                            }
15657                        }
15658                    }
15659                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15660                }
15661                // make sure to preserve per-user disabled state if this removal was just
15662                // a downgrade of a system app to the factory package
15663                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15664                    if (DEBUG_REMOVE) {
15665                        Slog.d(TAG, "Propagating install state across downgrade");
15666                    }
15667                    for (int userId : allUserHandles) {
15668                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15669                        if (DEBUG_REMOVE) {
15670                            Slog.d(TAG, "    user " + userId + " => " + installed);
15671                        }
15672                        ps.setInstalled(installed, userId);
15673                    }
15674                }
15675            }
15676            // can downgrade to reader
15677            if (writeSettings) {
15678                // Save settings now
15679                mSettings.writeLPr();
15680            }
15681        }
15682        if (outInfo != null) {
15683            // A user ID was deleted here. Go through all users and remove it
15684            // from KeyStore.
15685            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15686        }
15687    }
15688
15689    static boolean locationIsPrivileged(File path) {
15690        try {
15691            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15692                    .getCanonicalPath();
15693            return path.getCanonicalPath().startsWith(privilegedAppDir);
15694        } catch (IOException e) {
15695            Slog.e(TAG, "Unable to access code path " + path);
15696        }
15697        return false;
15698    }
15699
15700    /*
15701     * Tries to delete system package.
15702     */
15703    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15704            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15705            boolean writeSettings) {
15706        if (deletedPs.parentPackageName != null) {
15707            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15708            return false;
15709        }
15710
15711        final boolean applyUserRestrictions
15712                = (allUserHandles != null) && (outInfo.origUsers != null);
15713        final PackageSetting disabledPs;
15714        // Confirm if the system package has been updated
15715        // An updated system app can be deleted. This will also have to restore
15716        // the system pkg from system partition
15717        // reader
15718        synchronized (mPackages) {
15719            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15720        }
15721
15722        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15723                + " disabledPs=" + disabledPs);
15724
15725        if (disabledPs == null) {
15726            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15727            return false;
15728        } else if (DEBUG_REMOVE) {
15729            Slog.d(TAG, "Deleting system pkg from data partition");
15730        }
15731
15732        if (DEBUG_REMOVE) {
15733            if (applyUserRestrictions) {
15734                Slog.d(TAG, "Remembering install states:");
15735                for (int userId : allUserHandles) {
15736                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15737                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15738                }
15739            }
15740        }
15741
15742        // Delete the updated package
15743        outInfo.isRemovedPackageSystemUpdate = true;
15744        if (outInfo.removedChildPackages != null) {
15745            final int childCount = (deletedPs.childPackageNames != null)
15746                    ? deletedPs.childPackageNames.size() : 0;
15747            for (int i = 0; i < childCount; i++) {
15748                String childPackageName = deletedPs.childPackageNames.get(i);
15749                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15750                        .contains(childPackageName)) {
15751                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15752                            childPackageName);
15753                    if (childInfo != null) {
15754                        childInfo.isRemovedPackageSystemUpdate = true;
15755                    }
15756                }
15757            }
15758        }
15759
15760        if (disabledPs.versionCode < deletedPs.versionCode) {
15761            // Delete data for downgrades
15762            flags &= ~PackageManager.DELETE_KEEP_DATA;
15763        } else {
15764            // Preserve data by setting flag
15765            flags |= PackageManager.DELETE_KEEP_DATA;
15766        }
15767
15768        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15769                outInfo, writeSettings, disabledPs.pkg);
15770        if (!ret) {
15771            return false;
15772        }
15773
15774        // writer
15775        synchronized (mPackages) {
15776            // Reinstate the old system package
15777            enableSystemPackageLPw(disabledPs.pkg);
15778            // Remove any native libraries from the upgraded package.
15779            removeNativeBinariesLI(deletedPs);
15780        }
15781
15782        // Install the system package
15783        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15784        int parseFlags = mDefParseFlags
15785                | PackageParser.PARSE_MUST_BE_APK
15786                | PackageParser.PARSE_IS_SYSTEM
15787                | PackageParser.PARSE_IS_SYSTEM_DIR;
15788        if (locationIsPrivileged(disabledPs.codePath)) {
15789            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15790        }
15791
15792        final PackageParser.Package newPkg;
15793        try {
15794            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15795        } catch (PackageManagerException e) {
15796            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15797                    + e.getMessage());
15798            return false;
15799        }
15800
15801        prepareAppDataAfterInstallLIF(newPkg);
15802
15803        // writer
15804        synchronized (mPackages) {
15805            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15806
15807            // Propagate the permissions state as we do not want to drop on the floor
15808            // runtime permissions. The update permissions method below will take
15809            // care of removing obsolete permissions and grant install permissions.
15810            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15811            updatePermissionsLPw(newPkg.packageName, newPkg,
15812                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15813
15814            if (applyUserRestrictions) {
15815                if (DEBUG_REMOVE) {
15816                    Slog.d(TAG, "Propagating install state across reinstall");
15817                }
15818                for (int userId : allUserHandles) {
15819                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15820                    if (DEBUG_REMOVE) {
15821                        Slog.d(TAG, "    user " + userId + " => " + installed);
15822                    }
15823                    ps.setInstalled(installed, userId);
15824
15825                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15826                }
15827                // Regardless of writeSettings we need to ensure that this restriction
15828                // state propagation is persisted
15829                mSettings.writeAllUsersPackageRestrictionsLPr();
15830            }
15831            // can downgrade to reader here
15832            if (writeSettings) {
15833                mSettings.writeLPr();
15834            }
15835        }
15836        return true;
15837    }
15838
15839    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15840            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15841            PackageRemovedInfo outInfo, boolean writeSettings,
15842            PackageParser.Package replacingPackage) {
15843        synchronized (mPackages) {
15844            if (outInfo != null) {
15845                outInfo.uid = ps.appId;
15846            }
15847
15848            if (outInfo != null && outInfo.removedChildPackages != null) {
15849                final int childCount = (ps.childPackageNames != null)
15850                        ? ps.childPackageNames.size() : 0;
15851                for (int i = 0; i < childCount; i++) {
15852                    String childPackageName = ps.childPackageNames.get(i);
15853                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15854                    if (childPs == null) {
15855                        return false;
15856                    }
15857                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15858                            childPackageName);
15859                    if (childInfo != null) {
15860                        childInfo.uid = childPs.appId;
15861                    }
15862                }
15863            }
15864        }
15865
15866        // Delete package data from internal structures and also remove data if flag is set
15867        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15868
15869        // Delete the child packages data
15870        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15871        for (int i = 0; i < childCount; i++) {
15872            PackageSetting childPs;
15873            synchronized (mPackages) {
15874                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15875            }
15876            if (childPs != null) {
15877                PackageRemovedInfo childOutInfo = (outInfo != null
15878                        && outInfo.removedChildPackages != null)
15879                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15880                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15881                        && (replacingPackage != null
15882                        && !replacingPackage.hasChildPackage(childPs.name))
15883                        ? flags & ~DELETE_KEEP_DATA : flags;
15884                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15885                        deleteFlags, writeSettings);
15886            }
15887        }
15888
15889        // Delete application code and resources only for parent packages
15890        if (ps.parentPackageName == null) {
15891            if (deleteCodeAndResources && (outInfo != null)) {
15892                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15893                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15894                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15895            }
15896        }
15897
15898        return true;
15899    }
15900
15901    @Override
15902    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15903            int userId) {
15904        mContext.enforceCallingOrSelfPermission(
15905                android.Manifest.permission.DELETE_PACKAGES, null);
15906        synchronized (mPackages) {
15907            PackageSetting ps = mSettings.mPackages.get(packageName);
15908            if (ps == null) {
15909                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15910                return false;
15911            }
15912            if (!ps.getInstalled(userId)) {
15913                // Can't block uninstall for an app that is not installed or enabled.
15914                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15915                return false;
15916            }
15917            ps.setBlockUninstall(blockUninstall, userId);
15918            mSettings.writePackageRestrictionsLPr(userId);
15919        }
15920        return true;
15921    }
15922
15923    @Override
15924    public boolean getBlockUninstallForUser(String packageName, int userId) {
15925        synchronized (mPackages) {
15926            PackageSetting ps = mSettings.mPackages.get(packageName);
15927            if (ps == null) {
15928                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15929                return false;
15930            }
15931            return ps.getBlockUninstall(userId);
15932        }
15933    }
15934
15935    @Override
15936    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15937        int callingUid = Binder.getCallingUid();
15938        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15939            throw new SecurityException(
15940                    "setRequiredForSystemUser can only be run by the system or root");
15941        }
15942        synchronized (mPackages) {
15943            PackageSetting ps = mSettings.mPackages.get(packageName);
15944            if (ps == null) {
15945                Log.w(TAG, "Package doesn't exist: " + packageName);
15946                return false;
15947            }
15948            if (systemUserApp) {
15949                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15950            } else {
15951                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15952            }
15953            mSettings.writeLPr();
15954        }
15955        return true;
15956    }
15957
15958    /*
15959     * This method handles package deletion in general
15960     */
15961    private boolean deletePackageLIF(String packageName, UserHandle user,
15962            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15963            PackageRemovedInfo outInfo, boolean writeSettings,
15964            PackageParser.Package replacingPackage) {
15965        if (packageName == null) {
15966            Slog.w(TAG, "Attempt to delete null packageName.");
15967            return false;
15968        }
15969
15970        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15971
15972        PackageSetting ps;
15973
15974        synchronized (mPackages) {
15975            ps = mSettings.mPackages.get(packageName);
15976            if (ps == null) {
15977                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15978                return false;
15979            }
15980
15981            if (ps.parentPackageName != null && (!isSystemApp(ps)
15982                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15983                if (DEBUG_REMOVE) {
15984                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15985                            + ((user == null) ? UserHandle.USER_ALL : user));
15986                }
15987                final int removedUserId = (user != null) ? user.getIdentifier()
15988                        : UserHandle.USER_ALL;
15989                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15990                    return false;
15991                }
15992                markPackageUninstalledForUserLPw(ps, user);
15993                scheduleWritePackageRestrictionsLocked(user);
15994                return true;
15995            }
15996        }
15997
15998        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15999                && user.getIdentifier() != UserHandle.USER_ALL)) {
16000            // The caller is asking that the package only be deleted for a single
16001            // user.  To do this, we just mark its uninstalled state and delete
16002            // its data. If this is a system app, we only allow this to happen if
16003            // they have set the special DELETE_SYSTEM_APP which requests different
16004            // semantics than normal for uninstalling system apps.
16005            markPackageUninstalledForUserLPw(ps, user);
16006
16007            if (!isSystemApp(ps)) {
16008                // Do not uninstall the APK if an app should be cached
16009                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16010                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16011                    // Other user still have this package installed, so all
16012                    // we need to do is clear this user's data and save that
16013                    // it is uninstalled.
16014                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16015                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16016                        return false;
16017                    }
16018                    scheduleWritePackageRestrictionsLocked(user);
16019                    return true;
16020                } else {
16021                    // We need to set it back to 'installed' so the uninstall
16022                    // broadcasts will be sent correctly.
16023                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16024                    ps.setInstalled(true, user.getIdentifier());
16025                }
16026            } else {
16027                // This is a system app, so we assume that the
16028                // other users still have this package installed, so all
16029                // we need to do is clear this user's data and save that
16030                // it is uninstalled.
16031                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16032                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16033                    return false;
16034                }
16035                scheduleWritePackageRestrictionsLocked(user);
16036                return true;
16037            }
16038        }
16039
16040        // If we are deleting a composite package for all users, keep track
16041        // of result for each child.
16042        if (ps.childPackageNames != null && outInfo != null) {
16043            synchronized (mPackages) {
16044                final int childCount = ps.childPackageNames.size();
16045                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16046                for (int i = 0; i < childCount; i++) {
16047                    String childPackageName = ps.childPackageNames.get(i);
16048                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16049                    childInfo.removedPackage = childPackageName;
16050                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16051                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16052                    if (childPs != null) {
16053                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16054                    }
16055                }
16056            }
16057        }
16058
16059        boolean ret = false;
16060        if (isSystemApp(ps)) {
16061            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16062            // When an updated system application is deleted we delete the existing resources
16063            // as well and fall back to existing code in system partition
16064            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16065        } else {
16066            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16067            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16068                    outInfo, writeSettings, replacingPackage);
16069        }
16070
16071        // Take a note whether we deleted the package for all users
16072        if (outInfo != null) {
16073            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16074            if (outInfo.removedChildPackages != null) {
16075                synchronized (mPackages) {
16076                    final int childCount = outInfo.removedChildPackages.size();
16077                    for (int i = 0; i < childCount; i++) {
16078                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16079                        if (childInfo != null) {
16080                            childInfo.removedForAllUsers = mPackages.get(
16081                                    childInfo.removedPackage) == null;
16082                        }
16083                    }
16084                }
16085            }
16086            // If we uninstalled an update to a system app there may be some
16087            // child packages that appeared as they are declared in the system
16088            // app but were not declared in the update.
16089            if (isSystemApp(ps)) {
16090                synchronized (mPackages) {
16091                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16092                    final int childCount = (updatedPs.childPackageNames != null)
16093                            ? updatedPs.childPackageNames.size() : 0;
16094                    for (int i = 0; i < childCount; i++) {
16095                        String childPackageName = updatedPs.childPackageNames.get(i);
16096                        if (outInfo.removedChildPackages == null
16097                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16098                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16099                            if (childPs == null) {
16100                                continue;
16101                            }
16102                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16103                            installRes.name = childPackageName;
16104                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16105                            installRes.pkg = mPackages.get(childPackageName);
16106                            installRes.uid = childPs.pkg.applicationInfo.uid;
16107                            if (outInfo.appearedChildPackages == null) {
16108                                outInfo.appearedChildPackages = new ArrayMap<>();
16109                            }
16110                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16111                        }
16112                    }
16113                }
16114            }
16115        }
16116
16117        return ret;
16118    }
16119
16120    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16121        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16122                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16123        for (int nextUserId : userIds) {
16124            if (DEBUG_REMOVE) {
16125                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16126            }
16127            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16128                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16129                    false /*hidden*/, false /*suspended*/, null, null, null,
16130                    false /*blockUninstall*/,
16131                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16132        }
16133    }
16134
16135    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16136            PackageRemovedInfo outInfo) {
16137        final PackageParser.Package pkg;
16138        synchronized (mPackages) {
16139            pkg = mPackages.get(ps.name);
16140        }
16141
16142        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16143                : new int[] {userId};
16144        for (int nextUserId : userIds) {
16145            if (DEBUG_REMOVE) {
16146                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16147                        + nextUserId);
16148            }
16149
16150            destroyAppDataLIF(pkg, userId,
16151                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16152            destroyAppProfilesLIF(pkg, userId);
16153            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16154            schedulePackageCleaning(ps.name, nextUserId, false);
16155            synchronized (mPackages) {
16156                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16157                    scheduleWritePackageRestrictionsLocked(nextUserId);
16158                }
16159                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16160            }
16161        }
16162
16163        if (outInfo != null) {
16164            outInfo.removedPackage = ps.name;
16165            outInfo.removedAppId = ps.appId;
16166            outInfo.removedUsers = userIds;
16167        }
16168
16169        return true;
16170    }
16171
16172    private final class ClearStorageConnection implements ServiceConnection {
16173        IMediaContainerService mContainerService;
16174
16175        @Override
16176        public void onServiceConnected(ComponentName name, IBinder service) {
16177            synchronized (this) {
16178                mContainerService = IMediaContainerService.Stub.asInterface(service);
16179                notifyAll();
16180            }
16181        }
16182
16183        @Override
16184        public void onServiceDisconnected(ComponentName name) {
16185        }
16186    }
16187
16188    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16189        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16190
16191        final boolean mounted;
16192        if (Environment.isExternalStorageEmulated()) {
16193            mounted = true;
16194        } else {
16195            final String status = Environment.getExternalStorageState();
16196
16197            mounted = status.equals(Environment.MEDIA_MOUNTED)
16198                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16199        }
16200
16201        if (!mounted) {
16202            return;
16203        }
16204
16205        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16206        int[] users;
16207        if (userId == UserHandle.USER_ALL) {
16208            users = sUserManager.getUserIds();
16209        } else {
16210            users = new int[] { userId };
16211        }
16212        final ClearStorageConnection conn = new ClearStorageConnection();
16213        if (mContext.bindServiceAsUser(
16214                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16215            try {
16216                for (int curUser : users) {
16217                    long timeout = SystemClock.uptimeMillis() + 5000;
16218                    synchronized (conn) {
16219                        long now;
16220                        while (conn.mContainerService == null &&
16221                                (now = SystemClock.uptimeMillis()) < timeout) {
16222                            try {
16223                                conn.wait(timeout - now);
16224                            } catch (InterruptedException e) {
16225                            }
16226                        }
16227                    }
16228                    if (conn.mContainerService == null) {
16229                        return;
16230                    }
16231
16232                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16233                    clearDirectory(conn.mContainerService,
16234                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16235                    if (allData) {
16236                        clearDirectory(conn.mContainerService,
16237                                userEnv.buildExternalStorageAppDataDirs(packageName));
16238                        clearDirectory(conn.mContainerService,
16239                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16240                    }
16241                }
16242            } finally {
16243                mContext.unbindService(conn);
16244            }
16245        }
16246    }
16247
16248    @Override
16249    public void clearApplicationProfileData(String packageName) {
16250        enforceSystemOrRoot("Only the system can clear all profile data");
16251
16252        final PackageParser.Package pkg;
16253        synchronized (mPackages) {
16254            pkg = mPackages.get(packageName);
16255        }
16256
16257        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16258            synchronized (mInstallLock) {
16259                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16260                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16261                        true /* removeBaseMarker */);
16262            }
16263        }
16264    }
16265
16266    @Override
16267    public void clearApplicationUserData(final String packageName,
16268            final IPackageDataObserver observer, final int userId) {
16269        mContext.enforceCallingOrSelfPermission(
16270                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16271
16272        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16273                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16274
16275        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16276            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16277        }
16278        // Queue up an async operation since the package deletion may take a little while.
16279        mHandler.post(new Runnable() {
16280            public void run() {
16281                mHandler.removeCallbacks(this);
16282                final boolean succeeded;
16283                try (PackageFreezer freezer = freezePackage(packageName,
16284                        "clearApplicationUserData")) {
16285                    synchronized (mInstallLock) {
16286                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16287                    }
16288                    clearExternalStorageDataSync(packageName, userId, true);
16289                }
16290                if (succeeded) {
16291                    // invoke DeviceStorageMonitor's update method to clear any notifications
16292                    DeviceStorageMonitorInternal dsm = LocalServices
16293                            .getService(DeviceStorageMonitorInternal.class);
16294                    if (dsm != null) {
16295                        dsm.checkMemory();
16296                    }
16297                }
16298                if(observer != null) {
16299                    try {
16300                        observer.onRemoveCompleted(packageName, succeeded);
16301                    } catch (RemoteException e) {
16302                        Log.i(TAG, "Observer no longer exists.");
16303                    }
16304                } //end if observer
16305            } //end run
16306        });
16307    }
16308
16309    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16310        if (packageName == null) {
16311            Slog.w(TAG, "Attempt to delete null packageName.");
16312            return false;
16313        }
16314
16315        // Try finding details about the requested package
16316        PackageParser.Package pkg;
16317        synchronized (mPackages) {
16318            pkg = mPackages.get(packageName);
16319            if (pkg == null) {
16320                final PackageSetting ps = mSettings.mPackages.get(packageName);
16321                if (ps != null) {
16322                    pkg = ps.pkg;
16323                }
16324            }
16325
16326            if (pkg == null) {
16327                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16328                return false;
16329            }
16330
16331            PackageSetting ps = (PackageSetting) pkg.mExtras;
16332            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16333        }
16334
16335        clearAppDataLIF(pkg, userId,
16336                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16337
16338        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16339        removeKeystoreDataIfNeeded(userId, appId);
16340
16341        UserManagerInternal umInternal = getUserManagerInternal();
16342        final int flags;
16343        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16344            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16345        } else if (umInternal.isUserRunning(userId)) {
16346            flags = StorageManager.FLAG_STORAGE_DE;
16347        } else {
16348            flags = 0;
16349        }
16350        prepareAppDataContentsLIF(pkg, userId, flags);
16351
16352        return true;
16353    }
16354
16355    /**
16356     * Reverts user permission state changes (permissions and flags) in
16357     * all packages for a given user.
16358     *
16359     * @param userId The device user for which to do a reset.
16360     */
16361    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16362        final int packageCount = mPackages.size();
16363        for (int i = 0; i < packageCount; i++) {
16364            PackageParser.Package pkg = mPackages.valueAt(i);
16365            PackageSetting ps = (PackageSetting) pkg.mExtras;
16366            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16367        }
16368    }
16369
16370    private void resetNetworkPolicies(int userId) {
16371        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16372    }
16373
16374    /**
16375     * Reverts user permission state changes (permissions and flags).
16376     *
16377     * @param ps The package for which to reset.
16378     * @param userId The device user for which to do a reset.
16379     */
16380    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16381            final PackageSetting ps, final int userId) {
16382        if (ps.pkg == null) {
16383            return;
16384        }
16385
16386        // These are flags that can change base on user actions.
16387        final int userSettableMask = FLAG_PERMISSION_USER_SET
16388                | FLAG_PERMISSION_USER_FIXED
16389                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16390                | FLAG_PERMISSION_REVIEW_REQUIRED;
16391
16392        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16393                | FLAG_PERMISSION_POLICY_FIXED;
16394
16395        boolean writeInstallPermissions = false;
16396        boolean writeRuntimePermissions = false;
16397
16398        final int permissionCount = ps.pkg.requestedPermissions.size();
16399        for (int i = 0; i < permissionCount; i++) {
16400            String permission = ps.pkg.requestedPermissions.get(i);
16401
16402            BasePermission bp = mSettings.mPermissions.get(permission);
16403            if (bp == null) {
16404                continue;
16405            }
16406
16407            // If shared user we just reset the state to which only this app contributed.
16408            if (ps.sharedUser != null) {
16409                boolean used = false;
16410                final int packageCount = ps.sharedUser.packages.size();
16411                for (int j = 0; j < packageCount; j++) {
16412                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16413                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16414                            && pkg.pkg.requestedPermissions.contains(permission)) {
16415                        used = true;
16416                        break;
16417                    }
16418                }
16419                if (used) {
16420                    continue;
16421                }
16422            }
16423
16424            PermissionsState permissionsState = ps.getPermissionsState();
16425
16426            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16427
16428            // Always clear the user settable flags.
16429            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16430                    bp.name) != null;
16431            // If permission review is enabled and this is a legacy app, mark the
16432            // permission as requiring a review as this is the initial state.
16433            int flags = 0;
16434            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16435                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16436                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16437            }
16438            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16439                if (hasInstallState) {
16440                    writeInstallPermissions = true;
16441                } else {
16442                    writeRuntimePermissions = true;
16443                }
16444            }
16445
16446            // Below is only runtime permission handling.
16447            if (!bp.isRuntime()) {
16448                continue;
16449            }
16450
16451            // Never clobber system or policy.
16452            if ((oldFlags & policyOrSystemFlags) != 0) {
16453                continue;
16454            }
16455
16456            // If this permission was granted by default, make sure it is.
16457            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16458                if (permissionsState.grantRuntimePermission(bp, userId)
16459                        != PERMISSION_OPERATION_FAILURE) {
16460                    writeRuntimePermissions = true;
16461                }
16462            // If permission review is enabled the permissions for a legacy apps
16463            // are represented as constantly granted runtime ones, so don't revoke.
16464            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16465                // Otherwise, reset the permission.
16466                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16467                switch (revokeResult) {
16468                    case PERMISSION_OPERATION_SUCCESS:
16469                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16470                        writeRuntimePermissions = true;
16471                        final int appId = ps.appId;
16472                        mHandler.post(new Runnable() {
16473                            @Override
16474                            public void run() {
16475                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16476                            }
16477                        });
16478                    } break;
16479                }
16480            }
16481        }
16482
16483        // Synchronously write as we are taking permissions away.
16484        if (writeRuntimePermissions) {
16485            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16486        }
16487
16488        // Synchronously write as we are taking permissions away.
16489        if (writeInstallPermissions) {
16490            mSettings.writeLPr();
16491        }
16492    }
16493
16494    /**
16495     * Remove entries from the keystore daemon. Will only remove it if the
16496     * {@code appId} is valid.
16497     */
16498    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16499        if (appId < 0) {
16500            return;
16501        }
16502
16503        final KeyStore keyStore = KeyStore.getInstance();
16504        if (keyStore != null) {
16505            if (userId == UserHandle.USER_ALL) {
16506                for (final int individual : sUserManager.getUserIds()) {
16507                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16508                }
16509            } else {
16510                keyStore.clearUid(UserHandle.getUid(userId, appId));
16511            }
16512        } else {
16513            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16514        }
16515    }
16516
16517    @Override
16518    public void deleteApplicationCacheFiles(final String packageName,
16519            final IPackageDataObserver observer) {
16520        final int userId = UserHandle.getCallingUserId();
16521        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16522    }
16523
16524    @Override
16525    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16526            final IPackageDataObserver observer) {
16527        mContext.enforceCallingOrSelfPermission(
16528                android.Manifest.permission.DELETE_CACHE_FILES, null);
16529        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16530                /* requireFullPermission= */ true, /* checkShell= */ false,
16531                "delete application cache files");
16532
16533        final PackageParser.Package pkg;
16534        synchronized (mPackages) {
16535            pkg = mPackages.get(packageName);
16536        }
16537
16538        // Queue up an async operation since the package deletion may take a little while.
16539        mHandler.post(new Runnable() {
16540            public void run() {
16541                synchronized (mInstallLock) {
16542                    final int flags = StorageManager.FLAG_STORAGE_DE
16543                            | StorageManager.FLAG_STORAGE_CE;
16544                    // We're only clearing cache files, so we don't care if the
16545                    // app is unfrozen and still able to run
16546                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16547                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16548                }
16549                clearExternalStorageDataSync(packageName, userId, false);
16550                if (observer != null) {
16551                    try {
16552                        observer.onRemoveCompleted(packageName, true);
16553                    } catch (RemoteException e) {
16554                        Log.i(TAG, "Observer no longer exists.");
16555                    }
16556                }
16557            }
16558        });
16559    }
16560
16561    @Override
16562    public void getPackageSizeInfo(final String packageName, int userHandle,
16563            final IPackageStatsObserver observer) {
16564        mContext.enforceCallingOrSelfPermission(
16565                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16566        if (packageName == null) {
16567            throw new IllegalArgumentException("Attempt to get size of null packageName");
16568        }
16569
16570        PackageStats stats = new PackageStats(packageName, userHandle);
16571
16572        /*
16573         * Queue up an async operation since the package measurement may take a
16574         * little while.
16575         */
16576        Message msg = mHandler.obtainMessage(INIT_COPY);
16577        msg.obj = new MeasureParams(stats, observer);
16578        mHandler.sendMessage(msg);
16579    }
16580
16581    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16582        final PackageSetting ps;
16583        synchronized (mPackages) {
16584            ps = mSettings.mPackages.get(packageName);
16585            if (ps == null) {
16586                Slog.w(TAG, "Failed to find settings for " + packageName);
16587                return false;
16588            }
16589        }
16590        try {
16591            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16592                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16593                    ps.getCeDataInode(userId), ps.codePathString, stats);
16594        } catch (InstallerException e) {
16595            Slog.w(TAG, String.valueOf(e));
16596            return false;
16597        }
16598
16599        // For now, ignore code size of packages on system partition
16600        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16601            stats.codeSize = 0;
16602        }
16603
16604        return true;
16605    }
16606
16607    private int getUidTargetSdkVersionLockedLPr(int uid) {
16608        Object obj = mSettings.getUserIdLPr(uid);
16609        if (obj instanceof SharedUserSetting) {
16610            final SharedUserSetting sus = (SharedUserSetting) obj;
16611            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16612            final Iterator<PackageSetting> it = sus.packages.iterator();
16613            while (it.hasNext()) {
16614                final PackageSetting ps = it.next();
16615                if (ps.pkg != null) {
16616                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16617                    if (v < vers) vers = v;
16618                }
16619            }
16620            return vers;
16621        } else if (obj instanceof PackageSetting) {
16622            final PackageSetting ps = (PackageSetting) obj;
16623            if (ps.pkg != null) {
16624                return ps.pkg.applicationInfo.targetSdkVersion;
16625            }
16626        }
16627        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16628    }
16629
16630    @Override
16631    public void addPreferredActivity(IntentFilter filter, int match,
16632            ComponentName[] set, ComponentName activity, int userId) {
16633        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16634                "Adding preferred");
16635    }
16636
16637    private void addPreferredActivityInternal(IntentFilter filter, int match,
16638            ComponentName[] set, ComponentName activity, boolean always, int userId,
16639            String opname) {
16640        // writer
16641        int callingUid = Binder.getCallingUid();
16642        enforceCrossUserPermission(callingUid, userId,
16643                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16644        if (filter.countActions() == 0) {
16645            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16646            return;
16647        }
16648        synchronized (mPackages) {
16649            if (mContext.checkCallingOrSelfPermission(
16650                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16651                    != PackageManager.PERMISSION_GRANTED) {
16652                if (getUidTargetSdkVersionLockedLPr(callingUid)
16653                        < Build.VERSION_CODES.FROYO) {
16654                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16655                            + callingUid);
16656                    return;
16657                }
16658                mContext.enforceCallingOrSelfPermission(
16659                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16660            }
16661
16662            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16663            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16664                    + userId + ":");
16665            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16666            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16667            scheduleWritePackageRestrictionsLocked(userId);
16668        }
16669    }
16670
16671    @Override
16672    public void replacePreferredActivity(IntentFilter filter, int match,
16673            ComponentName[] set, ComponentName activity, int userId) {
16674        if (filter.countActions() != 1) {
16675            throw new IllegalArgumentException(
16676                    "replacePreferredActivity expects filter to have only 1 action.");
16677        }
16678        if (filter.countDataAuthorities() != 0
16679                || filter.countDataPaths() != 0
16680                || filter.countDataSchemes() > 1
16681                || filter.countDataTypes() != 0) {
16682            throw new IllegalArgumentException(
16683                    "replacePreferredActivity expects filter to have no data authorities, " +
16684                    "paths, or types; and at most one scheme.");
16685        }
16686
16687        final int callingUid = Binder.getCallingUid();
16688        enforceCrossUserPermission(callingUid, userId,
16689                true /* requireFullPermission */, false /* checkShell */,
16690                "replace preferred activity");
16691        synchronized (mPackages) {
16692            if (mContext.checkCallingOrSelfPermission(
16693                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16694                    != PackageManager.PERMISSION_GRANTED) {
16695                if (getUidTargetSdkVersionLockedLPr(callingUid)
16696                        < Build.VERSION_CODES.FROYO) {
16697                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16698                            + Binder.getCallingUid());
16699                    return;
16700                }
16701                mContext.enforceCallingOrSelfPermission(
16702                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16703            }
16704
16705            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16706            if (pir != null) {
16707                // Get all of the existing entries that exactly match this filter.
16708                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16709                if (existing != null && existing.size() == 1) {
16710                    PreferredActivity cur = existing.get(0);
16711                    if (DEBUG_PREFERRED) {
16712                        Slog.i(TAG, "Checking replace of preferred:");
16713                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16714                        if (!cur.mPref.mAlways) {
16715                            Slog.i(TAG, "  -- CUR; not mAlways!");
16716                        } else {
16717                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16718                            Slog.i(TAG, "  -- CUR: mSet="
16719                                    + Arrays.toString(cur.mPref.mSetComponents));
16720                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16721                            Slog.i(TAG, "  -- NEW: mMatch="
16722                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16723                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16724                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16725                        }
16726                    }
16727                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16728                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16729                            && cur.mPref.sameSet(set)) {
16730                        // Setting the preferred activity to what it happens to be already
16731                        if (DEBUG_PREFERRED) {
16732                            Slog.i(TAG, "Replacing with same preferred activity "
16733                                    + cur.mPref.mShortComponent + " for user "
16734                                    + userId + ":");
16735                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16736                        }
16737                        return;
16738                    }
16739                }
16740
16741                if (existing != null) {
16742                    if (DEBUG_PREFERRED) {
16743                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16744                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16745                    }
16746                    for (int i = 0; i < existing.size(); i++) {
16747                        PreferredActivity pa = existing.get(i);
16748                        if (DEBUG_PREFERRED) {
16749                            Slog.i(TAG, "Removing existing preferred activity "
16750                                    + pa.mPref.mComponent + ":");
16751                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16752                        }
16753                        pir.removeFilter(pa);
16754                    }
16755                }
16756            }
16757            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16758                    "Replacing preferred");
16759        }
16760    }
16761
16762    @Override
16763    public void clearPackagePreferredActivities(String packageName) {
16764        final int uid = Binder.getCallingUid();
16765        // writer
16766        synchronized (mPackages) {
16767            PackageParser.Package pkg = mPackages.get(packageName);
16768            if (pkg == null || pkg.applicationInfo.uid != uid) {
16769                if (mContext.checkCallingOrSelfPermission(
16770                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16771                        != PackageManager.PERMISSION_GRANTED) {
16772                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16773                            < Build.VERSION_CODES.FROYO) {
16774                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16775                                + Binder.getCallingUid());
16776                        return;
16777                    }
16778                    mContext.enforceCallingOrSelfPermission(
16779                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16780                }
16781            }
16782
16783            int user = UserHandle.getCallingUserId();
16784            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16785                scheduleWritePackageRestrictionsLocked(user);
16786            }
16787        }
16788    }
16789
16790    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16791    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16792        ArrayList<PreferredActivity> removed = null;
16793        boolean changed = false;
16794        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16795            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16796            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16797            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16798                continue;
16799            }
16800            Iterator<PreferredActivity> it = pir.filterIterator();
16801            while (it.hasNext()) {
16802                PreferredActivity pa = it.next();
16803                // Mark entry for removal only if it matches the package name
16804                // and the entry is of type "always".
16805                if (packageName == null ||
16806                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16807                                && pa.mPref.mAlways)) {
16808                    if (removed == null) {
16809                        removed = new ArrayList<PreferredActivity>();
16810                    }
16811                    removed.add(pa);
16812                }
16813            }
16814            if (removed != null) {
16815                for (int j=0; j<removed.size(); j++) {
16816                    PreferredActivity pa = removed.get(j);
16817                    pir.removeFilter(pa);
16818                }
16819                changed = true;
16820            }
16821        }
16822        return changed;
16823    }
16824
16825    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16826    private void clearIntentFilterVerificationsLPw(int userId) {
16827        final int packageCount = mPackages.size();
16828        for (int i = 0; i < packageCount; i++) {
16829            PackageParser.Package pkg = mPackages.valueAt(i);
16830            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16831        }
16832    }
16833
16834    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16835    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16836        if (userId == UserHandle.USER_ALL) {
16837            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16838                    sUserManager.getUserIds())) {
16839                for (int oneUserId : sUserManager.getUserIds()) {
16840                    scheduleWritePackageRestrictionsLocked(oneUserId);
16841                }
16842            }
16843        } else {
16844            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16845                scheduleWritePackageRestrictionsLocked(userId);
16846            }
16847        }
16848    }
16849
16850    void clearDefaultBrowserIfNeeded(String packageName) {
16851        for (int oneUserId : sUserManager.getUserIds()) {
16852            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16853            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16854            if (packageName.equals(defaultBrowserPackageName)) {
16855                setDefaultBrowserPackageName(null, oneUserId);
16856            }
16857        }
16858    }
16859
16860    @Override
16861    public void resetApplicationPreferences(int userId) {
16862        mContext.enforceCallingOrSelfPermission(
16863                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16864        final long identity = Binder.clearCallingIdentity();
16865        // writer
16866        try {
16867            synchronized (mPackages) {
16868                clearPackagePreferredActivitiesLPw(null, userId);
16869                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16870                // TODO: We have to reset the default SMS and Phone. This requires
16871                // significant refactoring to keep all default apps in the package
16872                // manager (cleaner but more work) or have the services provide
16873                // callbacks to the package manager to request a default app reset.
16874                applyFactoryDefaultBrowserLPw(userId);
16875                clearIntentFilterVerificationsLPw(userId);
16876                primeDomainVerificationsLPw(userId);
16877                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16878                scheduleWritePackageRestrictionsLocked(userId);
16879            }
16880            resetNetworkPolicies(userId);
16881        } finally {
16882            Binder.restoreCallingIdentity(identity);
16883        }
16884    }
16885
16886    @Override
16887    public int getPreferredActivities(List<IntentFilter> outFilters,
16888            List<ComponentName> outActivities, String packageName) {
16889
16890        int num = 0;
16891        final int userId = UserHandle.getCallingUserId();
16892        // reader
16893        synchronized (mPackages) {
16894            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16895            if (pir != null) {
16896                final Iterator<PreferredActivity> it = pir.filterIterator();
16897                while (it.hasNext()) {
16898                    final PreferredActivity pa = it.next();
16899                    if (packageName == null
16900                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16901                                    && pa.mPref.mAlways)) {
16902                        if (outFilters != null) {
16903                            outFilters.add(new IntentFilter(pa));
16904                        }
16905                        if (outActivities != null) {
16906                            outActivities.add(pa.mPref.mComponent);
16907                        }
16908                    }
16909                }
16910            }
16911        }
16912
16913        return num;
16914    }
16915
16916    @Override
16917    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16918            int userId) {
16919        int callingUid = Binder.getCallingUid();
16920        if (callingUid != Process.SYSTEM_UID) {
16921            throw new SecurityException(
16922                    "addPersistentPreferredActivity can only be run by the system");
16923        }
16924        if (filter.countActions() == 0) {
16925            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16926            return;
16927        }
16928        synchronized (mPackages) {
16929            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16930                    ":");
16931            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16932            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16933                    new PersistentPreferredActivity(filter, activity));
16934            scheduleWritePackageRestrictionsLocked(userId);
16935        }
16936    }
16937
16938    @Override
16939    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16940        int callingUid = Binder.getCallingUid();
16941        if (callingUid != Process.SYSTEM_UID) {
16942            throw new SecurityException(
16943                    "clearPackagePersistentPreferredActivities can only be run by the system");
16944        }
16945        ArrayList<PersistentPreferredActivity> removed = null;
16946        boolean changed = false;
16947        synchronized (mPackages) {
16948            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16949                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16950                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16951                        .valueAt(i);
16952                if (userId != thisUserId) {
16953                    continue;
16954                }
16955                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16956                while (it.hasNext()) {
16957                    PersistentPreferredActivity ppa = it.next();
16958                    // Mark entry for removal only if it matches the package name.
16959                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16960                        if (removed == null) {
16961                            removed = new ArrayList<PersistentPreferredActivity>();
16962                        }
16963                        removed.add(ppa);
16964                    }
16965                }
16966                if (removed != null) {
16967                    for (int j=0; j<removed.size(); j++) {
16968                        PersistentPreferredActivity ppa = removed.get(j);
16969                        ppir.removeFilter(ppa);
16970                    }
16971                    changed = true;
16972                }
16973            }
16974
16975            if (changed) {
16976                scheduleWritePackageRestrictionsLocked(userId);
16977            }
16978        }
16979    }
16980
16981    /**
16982     * Common machinery for picking apart a restored XML blob and passing
16983     * it to a caller-supplied functor to be applied to the running system.
16984     */
16985    private void restoreFromXml(XmlPullParser parser, int userId,
16986            String expectedStartTag, BlobXmlRestorer functor)
16987            throws IOException, XmlPullParserException {
16988        int type;
16989        while ((type = parser.next()) != XmlPullParser.START_TAG
16990                && type != XmlPullParser.END_DOCUMENT) {
16991        }
16992        if (type != XmlPullParser.START_TAG) {
16993            // oops didn't find a start tag?!
16994            if (DEBUG_BACKUP) {
16995                Slog.e(TAG, "Didn't find start tag during restore");
16996            }
16997            return;
16998        }
16999Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17000        // this is supposed to be TAG_PREFERRED_BACKUP
17001        if (!expectedStartTag.equals(parser.getName())) {
17002            if (DEBUG_BACKUP) {
17003                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17004            }
17005            return;
17006        }
17007
17008        // skip interfering stuff, then we're aligned with the backing implementation
17009        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17010Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17011        functor.apply(parser, userId);
17012    }
17013
17014    private interface BlobXmlRestorer {
17015        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17016    }
17017
17018    /**
17019     * Non-Binder method, support for the backup/restore mechanism: write the
17020     * full set of preferred activities in its canonical XML format.  Returns the
17021     * XML output as a byte array, or null if there is none.
17022     */
17023    @Override
17024    public byte[] getPreferredActivityBackup(int userId) {
17025        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17026            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17027        }
17028
17029        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17030        try {
17031            final XmlSerializer serializer = new FastXmlSerializer();
17032            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17033            serializer.startDocument(null, true);
17034            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17035
17036            synchronized (mPackages) {
17037                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17038            }
17039
17040            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17041            serializer.endDocument();
17042            serializer.flush();
17043        } catch (Exception e) {
17044            if (DEBUG_BACKUP) {
17045                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17046            }
17047            return null;
17048        }
17049
17050        return dataStream.toByteArray();
17051    }
17052
17053    @Override
17054    public void restorePreferredActivities(byte[] backup, int userId) {
17055        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17056            throw new SecurityException("Only the system may call restorePreferredActivities()");
17057        }
17058
17059        try {
17060            final XmlPullParser parser = Xml.newPullParser();
17061            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17062            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17063                    new BlobXmlRestorer() {
17064                        @Override
17065                        public void apply(XmlPullParser parser, int userId)
17066                                throws XmlPullParserException, IOException {
17067                            synchronized (mPackages) {
17068                                mSettings.readPreferredActivitiesLPw(parser, userId);
17069                            }
17070                        }
17071                    } );
17072        } catch (Exception e) {
17073            if (DEBUG_BACKUP) {
17074                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17075            }
17076        }
17077    }
17078
17079    /**
17080     * Non-Binder method, support for the backup/restore mechanism: write the
17081     * default browser (etc) settings in its canonical XML format.  Returns the default
17082     * browser XML representation as a byte array, or null if there is none.
17083     */
17084    @Override
17085    public byte[] getDefaultAppsBackup(int userId) {
17086        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17087            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17088        }
17089
17090        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17091        try {
17092            final XmlSerializer serializer = new FastXmlSerializer();
17093            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17094            serializer.startDocument(null, true);
17095            serializer.startTag(null, TAG_DEFAULT_APPS);
17096
17097            synchronized (mPackages) {
17098                mSettings.writeDefaultAppsLPr(serializer, userId);
17099            }
17100
17101            serializer.endTag(null, TAG_DEFAULT_APPS);
17102            serializer.endDocument();
17103            serializer.flush();
17104        } catch (Exception e) {
17105            if (DEBUG_BACKUP) {
17106                Slog.e(TAG, "Unable to write default apps for backup", e);
17107            }
17108            return null;
17109        }
17110
17111        return dataStream.toByteArray();
17112    }
17113
17114    @Override
17115    public void restoreDefaultApps(byte[] backup, int userId) {
17116        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17117            throw new SecurityException("Only the system may call restoreDefaultApps()");
17118        }
17119
17120        try {
17121            final XmlPullParser parser = Xml.newPullParser();
17122            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17123            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17124                    new BlobXmlRestorer() {
17125                        @Override
17126                        public void apply(XmlPullParser parser, int userId)
17127                                throws XmlPullParserException, IOException {
17128                            synchronized (mPackages) {
17129                                mSettings.readDefaultAppsLPw(parser, userId);
17130                            }
17131                        }
17132                    } );
17133        } catch (Exception e) {
17134            if (DEBUG_BACKUP) {
17135                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17136            }
17137        }
17138    }
17139
17140    @Override
17141    public byte[] getIntentFilterVerificationBackup(int userId) {
17142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17143            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17144        }
17145
17146        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17147        try {
17148            final XmlSerializer serializer = new FastXmlSerializer();
17149            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17150            serializer.startDocument(null, true);
17151            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17152
17153            synchronized (mPackages) {
17154                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17155            }
17156
17157            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17158            serializer.endDocument();
17159            serializer.flush();
17160        } catch (Exception e) {
17161            if (DEBUG_BACKUP) {
17162                Slog.e(TAG, "Unable to write default apps for backup", e);
17163            }
17164            return null;
17165        }
17166
17167        return dataStream.toByteArray();
17168    }
17169
17170    @Override
17171    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17173            throw new SecurityException("Only the system may call restorePreferredActivities()");
17174        }
17175
17176        try {
17177            final XmlPullParser parser = Xml.newPullParser();
17178            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17179            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17180                    new BlobXmlRestorer() {
17181                        @Override
17182                        public void apply(XmlPullParser parser, int userId)
17183                                throws XmlPullParserException, IOException {
17184                            synchronized (mPackages) {
17185                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17186                                mSettings.writeLPr();
17187                            }
17188                        }
17189                    } );
17190        } catch (Exception e) {
17191            if (DEBUG_BACKUP) {
17192                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17193            }
17194        }
17195    }
17196
17197    @Override
17198    public byte[] getPermissionGrantBackup(int userId) {
17199        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17200            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17201        }
17202
17203        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17204        try {
17205            final XmlSerializer serializer = new FastXmlSerializer();
17206            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17207            serializer.startDocument(null, true);
17208            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17209
17210            synchronized (mPackages) {
17211                serializeRuntimePermissionGrantsLPr(serializer, userId);
17212            }
17213
17214            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17215            serializer.endDocument();
17216            serializer.flush();
17217        } catch (Exception e) {
17218            if (DEBUG_BACKUP) {
17219                Slog.e(TAG, "Unable to write default apps for backup", e);
17220            }
17221            return null;
17222        }
17223
17224        return dataStream.toByteArray();
17225    }
17226
17227    @Override
17228    public void restorePermissionGrants(byte[] backup, int userId) {
17229        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17230            throw new SecurityException("Only the system may call restorePermissionGrants()");
17231        }
17232
17233        try {
17234            final XmlPullParser parser = Xml.newPullParser();
17235            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17236            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17237                    new BlobXmlRestorer() {
17238                        @Override
17239                        public void apply(XmlPullParser parser, int userId)
17240                                throws XmlPullParserException, IOException {
17241                            synchronized (mPackages) {
17242                                processRestoredPermissionGrantsLPr(parser, userId);
17243                            }
17244                        }
17245                    } );
17246        } catch (Exception e) {
17247            if (DEBUG_BACKUP) {
17248                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17249            }
17250        }
17251    }
17252
17253    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17254            throws IOException {
17255        serializer.startTag(null, TAG_ALL_GRANTS);
17256
17257        final int N = mSettings.mPackages.size();
17258        for (int i = 0; i < N; i++) {
17259            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17260            boolean pkgGrantsKnown = false;
17261
17262            PermissionsState packagePerms = ps.getPermissionsState();
17263
17264            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17265                final int grantFlags = state.getFlags();
17266                // only look at grants that are not system/policy fixed
17267                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17268                    final boolean isGranted = state.isGranted();
17269                    // And only back up the user-twiddled state bits
17270                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17271                        final String packageName = mSettings.mPackages.keyAt(i);
17272                        if (!pkgGrantsKnown) {
17273                            serializer.startTag(null, TAG_GRANT);
17274                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17275                            pkgGrantsKnown = true;
17276                        }
17277
17278                        final boolean userSet =
17279                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17280                        final boolean userFixed =
17281                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17282                        final boolean revoke =
17283                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17284
17285                        serializer.startTag(null, TAG_PERMISSION);
17286                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17287                        if (isGranted) {
17288                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17289                        }
17290                        if (userSet) {
17291                            serializer.attribute(null, ATTR_USER_SET, "true");
17292                        }
17293                        if (userFixed) {
17294                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17295                        }
17296                        if (revoke) {
17297                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17298                        }
17299                        serializer.endTag(null, TAG_PERMISSION);
17300                    }
17301                }
17302            }
17303
17304            if (pkgGrantsKnown) {
17305                serializer.endTag(null, TAG_GRANT);
17306            }
17307        }
17308
17309        serializer.endTag(null, TAG_ALL_GRANTS);
17310    }
17311
17312    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17313            throws XmlPullParserException, IOException {
17314        String pkgName = null;
17315        int outerDepth = parser.getDepth();
17316        int type;
17317        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17318                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17319            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17320                continue;
17321            }
17322
17323            final String tagName = parser.getName();
17324            if (tagName.equals(TAG_GRANT)) {
17325                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17326                if (DEBUG_BACKUP) {
17327                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17328                }
17329            } else if (tagName.equals(TAG_PERMISSION)) {
17330
17331                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17332                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17333
17334                int newFlagSet = 0;
17335                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17336                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17337                }
17338                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17339                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17340                }
17341                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17342                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17343                }
17344                if (DEBUG_BACKUP) {
17345                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17346                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17347                }
17348                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17349                if (ps != null) {
17350                    // Already installed so we apply the grant immediately
17351                    if (DEBUG_BACKUP) {
17352                        Slog.v(TAG, "        + already installed; applying");
17353                    }
17354                    PermissionsState perms = ps.getPermissionsState();
17355                    BasePermission bp = mSettings.mPermissions.get(permName);
17356                    if (bp != null) {
17357                        if (isGranted) {
17358                            perms.grantRuntimePermission(bp, userId);
17359                        }
17360                        if (newFlagSet != 0) {
17361                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17362                        }
17363                    }
17364                } else {
17365                    // Need to wait for post-restore install to apply the grant
17366                    if (DEBUG_BACKUP) {
17367                        Slog.v(TAG, "        - not yet installed; saving for later");
17368                    }
17369                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17370                            isGranted, newFlagSet, userId);
17371                }
17372            } else {
17373                PackageManagerService.reportSettingsProblem(Log.WARN,
17374                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17375                XmlUtils.skipCurrentTag(parser);
17376            }
17377        }
17378
17379        scheduleWriteSettingsLocked();
17380        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17381    }
17382
17383    @Override
17384    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17385            int sourceUserId, int targetUserId, int flags) {
17386        mContext.enforceCallingOrSelfPermission(
17387                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17388        int callingUid = Binder.getCallingUid();
17389        enforceOwnerRights(ownerPackage, callingUid);
17390        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17391        if (intentFilter.countActions() == 0) {
17392            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17393            return;
17394        }
17395        synchronized (mPackages) {
17396            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17397                    ownerPackage, targetUserId, flags);
17398            CrossProfileIntentResolver resolver =
17399                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17400            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17401            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17402            if (existing != null) {
17403                int size = existing.size();
17404                for (int i = 0; i < size; i++) {
17405                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17406                        return;
17407                    }
17408                }
17409            }
17410            resolver.addFilter(newFilter);
17411            scheduleWritePackageRestrictionsLocked(sourceUserId);
17412        }
17413    }
17414
17415    @Override
17416    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17417        mContext.enforceCallingOrSelfPermission(
17418                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17419        int callingUid = Binder.getCallingUid();
17420        enforceOwnerRights(ownerPackage, callingUid);
17421        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17422        synchronized (mPackages) {
17423            CrossProfileIntentResolver resolver =
17424                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17425            ArraySet<CrossProfileIntentFilter> set =
17426                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17427            for (CrossProfileIntentFilter filter : set) {
17428                if (filter.getOwnerPackage().equals(ownerPackage)) {
17429                    resolver.removeFilter(filter);
17430                }
17431            }
17432            scheduleWritePackageRestrictionsLocked(sourceUserId);
17433        }
17434    }
17435
17436    // Enforcing that callingUid is owning pkg on userId
17437    private void enforceOwnerRights(String pkg, int callingUid) {
17438        // The system owns everything.
17439        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17440            return;
17441        }
17442        int callingUserId = UserHandle.getUserId(callingUid);
17443        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17444        if (pi == null) {
17445            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17446                    + callingUserId);
17447        }
17448        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17449            throw new SecurityException("Calling uid " + callingUid
17450                    + " does not own package " + pkg);
17451        }
17452    }
17453
17454    @Override
17455    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17456        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17457    }
17458
17459    private Intent getHomeIntent() {
17460        Intent intent = new Intent(Intent.ACTION_MAIN);
17461        intent.addCategory(Intent.CATEGORY_HOME);
17462        return intent;
17463    }
17464
17465    private IntentFilter getHomeFilter() {
17466        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17467        filter.addCategory(Intent.CATEGORY_HOME);
17468        filter.addCategory(Intent.CATEGORY_DEFAULT);
17469        return filter;
17470    }
17471
17472    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17473            int userId) {
17474        Intent intent  = getHomeIntent();
17475        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17476                PackageManager.GET_META_DATA, userId);
17477        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17478                true, false, false, userId);
17479
17480        allHomeCandidates.clear();
17481        if (list != null) {
17482            for (ResolveInfo ri : list) {
17483                allHomeCandidates.add(ri);
17484            }
17485        }
17486        return (preferred == null || preferred.activityInfo == null)
17487                ? null
17488                : new ComponentName(preferred.activityInfo.packageName,
17489                        preferred.activityInfo.name);
17490    }
17491
17492    @Override
17493    public void setHomeActivity(ComponentName comp, int userId) {
17494        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17495        getHomeActivitiesAsUser(homeActivities, userId);
17496
17497        boolean found = false;
17498
17499        final int size = homeActivities.size();
17500        final ComponentName[] set = new ComponentName[size];
17501        for (int i = 0; i < size; i++) {
17502            final ResolveInfo candidate = homeActivities.get(i);
17503            final ActivityInfo info = candidate.activityInfo;
17504            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17505            set[i] = activityName;
17506            if (!found && activityName.equals(comp)) {
17507                found = true;
17508            }
17509        }
17510        if (!found) {
17511            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17512                    + userId);
17513        }
17514        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17515                set, comp, userId);
17516    }
17517
17518    private @Nullable String getSetupWizardPackageName() {
17519        final Intent intent = new Intent(Intent.ACTION_MAIN);
17520        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17521
17522        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17523                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17524                        | MATCH_DISABLED_COMPONENTS,
17525                UserHandle.myUserId());
17526        if (matches.size() == 1) {
17527            return matches.get(0).getComponentInfo().packageName;
17528        } else {
17529            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17530                    + ": matches=" + matches);
17531            return null;
17532        }
17533    }
17534
17535    @Override
17536    public void setApplicationEnabledSetting(String appPackageName,
17537            int newState, int flags, int userId, String callingPackage) {
17538        if (!sUserManager.exists(userId)) return;
17539        if (callingPackage == null) {
17540            callingPackage = Integer.toString(Binder.getCallingUid());
17541        }
17542        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17543    }
17544
17545    @Override
17546    public void setComponentEnabledSetting(ComponentName componentName,
17547            int newState, int flags, int userId) {
17548        if (!sUserManager.exists(userId)) return;
17549        setEnabledSetting(componentName.getPackageName(),
17550                componentName.getClassName(), newState, flags, userId, null);
17551    }
17552
17553    private void setEnabledSetting(final String packageName, String className, int newState,
17554            final int flags, int userId, String callingPackage) {
17555        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17556              || newState == COMPONENT_ENABLED_STATE_ENABLED
17557              || newState == COMPONENT_ENABLED_STATE_DISABLED
17558              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17559              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17560            throw new IllegalArgumentException("Invalid new component state: "
17561                    + newState);
17562        }
17563        PackageSetting pkgSetting;
17564        final int uid = Binder.getCallingUid();
17565        final int permission;
17566        if (uid == Process.SYSTEM_UID) {
17567            permission = PackageManager.PERMISSION_GRANTED;
17568        } else {
17569            permission = mContext.checkCallingOrSelfPermission(
17570                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17571        }
17572        enforceCrossUserPermission(uid, userId,
17573                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17574        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17575        boolean sendNow = false;
17576        boolean isApp = (className == null);
17577        String componentName = isApp ? packageName : className;
17578        int packageUid = -1;
17579        ArrayList<String> components;
17580
17581        // writer
17582        synchronized (mPackages) {
17583            pkgSetting = mSettings.mPackages.get(packageName);
17584            if (pkgSetting == null) {
17585                if (className == null) {
17586                    throw new IllegalArgumentException("Unknown package: " + packageName);
17587                }
17588                throw new IllegalArgumentException(
17589                        "Unknown component: " + packageName + "/" + className);
17590            }
17591        }
17592
17593        // Limit who can change which apps
17594        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17595            // Don't allow apps that don't have permission to modify other apps
17596            if (!allowedByPermission) {
17597                throw new SecurityException(
17598                        "Permission Denial: attempt to change component state from pid="
17599                        + Binder.getCallingPid()
17600                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17601            }
17602            // Don't allow changing profile and device owners.
17603            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17604                throw new SecurityException("Cannot disable a device owner or a profile owner");
17605            }
17606        }
17607
17608        synchronized (mPackages) {
17609            if (uid == Process.SHELL_UID) {
17610                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17611                int oldState = pkgSetting.getEnabled(userId);
17612                if (className == null
17613                    &&
17614                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17615                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17616                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17617                    &&
17618                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17619                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17620                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17621                    // ok
17622                } else {
17623                    throw new SecurityException(
17624                            "Shell cannot change component state for " + packageName + "/"
17625                            + className + " to " + newState);
17626                }
17627            }
17628            if (className == null) {
17629                // We're dealing with an application/package level state change
17630                if (pkgSetting.getEnabled(userId) == newState) {
17631                    // Nothing to do
17632                    return;
17633                }
17634                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17635                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17636                    // Don't care about who enables an app.
17637                    callingPackage = null;
17638                }
17639                pkgSetting.setEnabled(newState, userId, callingPackage);
17640                // pkgSetting.pkg.mSetEnabled = newState;
17641            } else {
17642                // We're dealing with a component level state change
17643                // First, verify that this is a valid class name.
17644                PackageParser.Package pkg = pkgSetting.pkg;
17645                if (pkg == null || !pkg.hasComponentClassName(className)) {
17646                    if (pkg != null &&
17647                            pkg.applicationInfo.targetSdkVersion >=
17648                                    Build.VERSION_CODES.JELLY_BEAN) {
17649                        throw new IllegalArgumentException("Component class " + className
17650                                + " does not exist in " + packageName);
17651                    } else {
17652                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17653                                + className + " does not exist in " + packageName);
17654                    }
17655                }
17656                switch (newState) {
17657                case COMPONENT_ENABLED_STATE_ENABLED:
17658                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17659                        return;
17660                    }
17661                    break;
17662                case COMPONENT_ENABLED_STATE_DISABLED:
17663                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17664                        return;
17665                    }
17666                    break;
17667                case COMPONENT_ENABLED_STATE_DEFAULT:
17668                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17669                        return;
17670                    }
17671                    break;
17672                default:
17673                    Slog.e(TAG, "Invalid new component state: " + newState);
17674                    return;
17675                }
17676            }
17677            scheduleWritePackageRestrictionsLocked(userId);
17678            components = mPendingBroadcasts.get(userId, packageName);
17679            final boolean newPackage = components == null;
17680            if (newPackage) {
17681                components = new ArrayList<String>();
17682            }
17683            if (!components.contains(componentName)) {
17684                components.add(componentName);
17685            }
17686            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17687                sendNow = true;
17688                // Purge entry from pending broadcast list if another one exists already
17689                // since we are sending one right away.
17690                mPendingBroadcasts.remove(userId, packageName);
17691            } else {
17692                if (newPackage) {
17693                    mPendingBroadcasts.put(userId, packageName, components);
17694                }
17695                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17696                    // Schedule a message
17697                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17698                }
17699            }
17700        }
17701
17702        long callingId = Binder.clearCallingIdentity();
17703        try {
17704            if (sendNow) {
17705                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17706                sendPackageChangedBroadcast(packageName,
17707                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17708            }
17709        } finally {
17710            Binder.restoreCallingIdentity(callingId);
17711        }
17712    }
17713
17714    @Override
17715    public void flushPackageRestrictionsAsUser(int userId) {
17716        if (!sUserManager.exists(userId)) {
17717            return;
17718        }
17719        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17720                false /* checkShell */, "flushPackageRestrictions");
17721        synchronized (mPackages) {
17722            mSettings.writePackageRestrictionsLPr(userId);
17723            mDirtyUsers.remove(userId);
17724            if (mDirtyUsers.isEmpty()) {
17725                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17726            }
17727        }
17728    }
17729
17730    private void sendPackageChangedBroadcast(String packageName,
17731            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17732        if (DEBUG_INSTALL)
17733            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17734                    + componentNames);
17735        Bundle extras = new Bundle(4);
17736        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17737        String nameList[] = new String[componentNames.size()];
17738        componentNames.toArray(nameList);
17739        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17740        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17741        extras.putInt(Intent.EXTRA_UID, packageUid);
17742        // If this is not reporting a change of the overall package, then only send it
17743        // to registered receivers.  We don't want to launch a swath of apps for every
17744        // little component state change.
17745        final int flags = !componentNames.contains(packageName)
17746                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17747        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17748                new int[] {UserHandle.getUserId(packageUid)});
17749    }
17750
17751    @Override
17752    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17753        if (!sUserManager.exists(userId)) return;
17754        final int uid = Binder.getCallingUid();
17755        final int permission = mContext.checkCallingOrSelfPermission(
17756                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17757        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17758        enforceCrossUserPermission(uid, userId,
17759                true /* requireFullPermission */, true /* checkShell */, "stop package");
17760        // writer
17761        synchronized (mPackages) {
17762            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17763                    allowedByPermission, uid, userId)) {
17764                scheduleWritePackageRestrictionsLocked(userId);
17765            }
17766        }
17767    }
17768
17769    @Override
17770    public String getInstallerPackageName(String packageName) {
17771        // reader
17772        synchronized (mPackages) {
17773            return mSettings.getInstallerPackageNameLPr(packageName);
17774        }
17775    }
17776
17777    public boolean isOrphaned(String packageName) {
17778        // reader
17779        synchronized (mPackages) {
17780            return mSettings.isOrphaned(packageName);
17781        }
17782    }
17783
17784    @Override
17785    public int getApplicationEnabledSetting(String packageName, int userId) {
17786        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17787        int uid = Binder.getCallingUid();
17788        enforceCrossUserPermission(uid, userId,
17789                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17790        // reader
17791        synchronized (mPackages) {
17792            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17793        }
17794    }
17795
17796    @Override
17797    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17798        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17799        int uid = Binder.getCallingUid();
17800        enforceCrossUserPermission(uid, userId,
17801                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17802        // reader
17803        synchronized (mPackages) {
17804            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17805        }
17806    }
17807
17808    @Override
17809    public void enterSafeMode() {
17810        enforceSystemOrRoot("Only the system can request entering safe mode");
17811
17812        if (!mSystemReady) {
17813            mSafeMode = true;
17814        }
17815    }
17816
17817    @Override
17818    public void systemReady() {
17819        mSystemReady = true;
17820
17821        // Read the compatibilty setting when the system is ready.
17822        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17823                mContext.getContentResolver(),
17824                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17825        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17826        if (DEBUG_SETTINGS) {
17827            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17828        }
17829
17830        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17831
17832        synchronized (mPackages) {
17833            // Verify that all of the preferred activity components actually
17834            // exist.  It is possible for applications to be updated and at
17835            // that point remove a previously declared activity component that
17836            // had been set as a preferred activity.  We try to clean this up
17837            // the next time we encounter that preferred activity, but it is
17838            // possible for the user flow to never be able to return to that
17839            // situation so here we do a sanity check to make sure we haven't
17840            // left any junk around.
17841            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17842            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17843                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17844                removed.clear();
17845                for (PreferredActivity pa : pir.filterSet()) {
17846                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17847                        removed.add(pa);
17848                    }
17849                }
17850                if (removed.size() > 0) {
17851                    for (int r=0; r<removed.size(); r++) {
17852                        PreferredActivity pa = removed.get(r);
17853                        Slog.w(TAG, "Removing dangling preferred activity: "
17854                                + pa.mPref.mComponent);
17855                        pir.removeFilter(pa);
17856                    }
17857                    mSettings.writePackageRestrictionsLPr(
17858                            mSettings.mPreferredActivities.keyAt(i));
17859                }
17860            }
17861
17862            for (int userId : UserManagerService.getInstance().getUserIds()) {
17863                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17864                    grantPermissionsUserIds = ArrayUtils.appendInt(
17865                            grantPermissionsUserIds, userId);
17866                }
17867            }
17868        }
17869        sUserManager.systemReady();
17870
17871        // If we upgraded grant all default permissions before kicking off.
17872        for (int userId : grantPermissionsUserIds) {
17873            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17874        }
17875
17876        // Kick off any messages waiting for system ready
17877        if (mPostSystemReadyMessages != null) {
17878            for (Message msg : mPostSystemReadyMessages) {
17879                msg.sendToTarget();
17880            }
17881            mPostSystemReadyMessages = null;
17882        }
17883
17884        // Watch for external volumes that come and go over time
17885        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17886        storage.registerListener(mStorageListener);
17887
17888        mInstallerService.systemReady();
17889        mPackageDexOptimizer.systemReady();
17890
17891        MountServiceInternal mountServiceInternal = LocalServices.getService(
17892                MountServiceInternal.class);
17893        mountServiceInternal.addExternalStoragePolicy(
17894                new MountServiceInternal.ExternalStorageMountPolicy() {
17895            @Override
17896            public int getMountMode(int uid, String packageName) {
17897                if (Process.isIsolated(uid)) {
17898                    return Zygote.MOUNT_EXTERNAL_NONE;
17899                }
17900                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17901                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17902                }
17903                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17904                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17905                }
17906                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17907                    return Zygote.MOUNT_EXTERNAL_READ;
17908                }
17909                return Zygote.MOUNT_EXTERNAL_WRITE;
17910            }
17911
17912            @Override
17913            public boolean hasExternalStorage(int uid, String packageName) {
17914                return true;
17915            }
17916        });
17917
17918        // Now that we're mostly running, clean up stale users and apps
17919        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17920        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17921    }
17922
17923    @Override
17924    public boolean isSafeMode() {
17925        return mSafeMode;
17926    }
17927
17928    @Override
17929    public boolean hasSystemUidErrors() {
17930        return mHasSystemUidErrors;
17931    }
17932
17933    static String arrayToString(int[] array) {
17934        StringBuffer buf = new StringBuffer(128);
17935        buf.append('[');
17936        if (array != null) {
17937            for (int i=0; i<array.length; i++) {
17938                if (i > 0) buf.append(", ");
17939                buf.append(array[i]);
17940            }
17941        }
17942        buf.append(']');
17943        return buf.toString();
17944    }
17945
17946    static class DumpState {
17947        public static final int DUMP_LIBS = 1 << 0;
17948        public static final int DUMP_FEATURES = 1 << 1;
17949        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17950        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17951        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17952        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17953        public static final int DUMP_PERMISSIONS = 1 << 6;
17954        public static final int DUMP_PACKAGES = 1 << 7;
17955        public static final int DUMP_SHARED_USERS = 1 << 8;
17956        public static final int DUMP_MESSAGES = 1 << 9;
17957        public static final int DUMP_PROVIDERS = 1 << 10;
17958        public static final int DUMP_VERIFIERS = 1 << 11;
17959        public static final int DUMP_PREFERRED = 1 << 12;
17960        public static final int DUMP_PREFERRED_XML = 1 << 13;
17961        public static final int DUMP_KEYSETS = 1 << 14;
17962        public static final int DUMP_VERSION = 1 << 15;
17963        public static final int DUMP_INSTALLS = 1 << 16;
17964        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17965        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17966        public static final int DUMP_FROZEN = 1 << 19;
17967        public static final int DUMP_DEXOPT = 1 << 20;
17968        public static final int DUMP_COMPILER_STATS = 1 << 21;
17969
17970        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17971
17972        private int mTypes;
17973
17974        private int mOptions;
17975
17976        private boolean mTitlePrinted;
17977
17978        private SharedUserSetting mSharedUser;
17979
17980        public boolean isDumping(int type) {
17981            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17982                return true;
17983            }
17984
17985            return (mTypes & type) != 0;
17986        }
17987
17988        public void setDump(int type) {
17989            mTypes |= type;
17990        }
17991
17992        public boolean isOptionEnabled(int option) {
17993            return (mOptions & option) != 0;
17994        }
17995
17996        public void setOptionEnabled(int option) {
17997            mOptions |= option;
17998        }
17999
18000        public boolean onTitlePrinted() {
18001            final boolean printed = mTitlePrinted;
18002            mTitlePrinted = true;
18003            return printed;
18004        }
18005
18006        public boolean getTitlePrinted() {
18007            return mTitlePrinted;
18008        }
18009
18010        public void setTitlePrinted(boolean enabled) {
18011            mTitlePrinted = enabled;
18012        }
18013
18014        public SharedUserSetting getSharedUser() {
18015            return mSharedUser;
18016        }
18017
18018        public void setSharedUser(SharedUserSetting user) {
18019            mSharedUser = user;
18020        }
18021    }
18022
18023    @Override
18024    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18025            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18026        (new PackageManagerShellCommand(this)).exec(
18027                this, in, out, err, args, resultReceiver);
18028    }
18029
18030    @Override
18031    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18032        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18033                != PackageManager.PERMISSION_GRANTED) {
18034            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18035                    + Binder.getCallingPid()
18036                    + ", uid=" + Binder.getCallingUid()
18037                    + " without permission "
18038                    + android.Manifest.permission.DUMP);
18039            return;
18040        }
18041
18042        DumpState dumpState = new DumpState();
18043        boolean fullPreferred = false;
18044        boolean checkin = false;
18045
18046        String packageName = null;
18047        ArraySet<String> permissionNames = null;
18048
18049        int opti = 0;
18050        while (opti < args.length) {
18051            String opt = args[opti];
18052            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18053                break;
18054            }
18055            opti++;
18056
18057            if ("-a".equals(opt)) {
18058                // Right now we only know how to print all.
18059            } else if ("-h".equals(opt)) {
18060                pw.println("Package manager dump options:");
18061                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18062                pw.println("    --checkin: dump for a checkin");
18063                pw.println("    -f: print details of intent filters");
18064                pw.println("    -h: print this help");
18065                pw.println("  cmd may be one of:");
18066                pw.println("    l[ibraries]: list known shared libraries");
18067                pw.println("    f[eatures]: list device features");
18068                pw.println("    k[eysets]: print known keysets");
18069                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18070                pw.println("    perm[issions]: dump permissions");
18071                pw.println("    permission [name ...]: dump declaration and use of given permission");
18072                pw.println("    pref[erred]: print preferred package settings");
18073                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18074                pw.println("    prov[iders]: dump content providers");
18075                pw.println("    p[ackages]: dump installed packages");
18076                pw.println("    s[hared-users]: dump shared user IDs");
18077                pw.println("    m[essages]: print collected runtime messages");
18078                pw.println("    v[erifiers]: print package verifier info");
18079                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18080                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18081                pw.println("    version: print database version info");
18082                pw.println("    write: write current settings now");
18083                pw.println("    installs: details about install sessions");
18084                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18085                pw.println("    dexopt: dump dexopt state");
18086                pw.println("    compiler-stats: dump compiler statistics");
18087                pw.println("    <package.name>: info about given package");
18088                return;
18089            } else if ("--checkin".equals(opt)) {
18090                checkin = true;
18091            } else if ("-f".equals(opt)) {
18092                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18093            } else {
18094                pw.println("Unknown argument: " + opt + "; use -h for help");
18095            }
18096        }
18097
18098        // Is the caller requesting to dump a particular piece of data?
18099        if (opti < args.length) {
18100            String cmd = args[opti];
18101            opti++;
18102            // Is this a package name?
18103            if ("android".equals(cmd) || cmd.contains(".")) {
18104                packageName = cmd;
18105                // When dumping a single package, we always dump all of its
18106                // filter information since the amount of data will be reasonable.
18107                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18108            } else if ("check-permission".equals(cmd)) {
18109                if (opti >= args.length) {
18110                    pw.println("Error: check-permission missing permission argument");
18111                    return;
18112                }
18113                String perm = args[opti];
18114                opti++;
18115                if (opti >= args.length) {
18116                    pw.println("Error: check-permission missing package argument");
18117                    return;
18118                }
18119                String pkg = args[opti];
18120                opti++;
18121                int user = UserHandle.getUserId(Binder.getCallingUid());
18122                if (opti < args.length) {
18123                    try {
18124                        user = Integer.parseInt(args[opti]);
18125                    } catch (NumberFormatException e) {
18126                        pw.println("Error: check-permission user argument is not a number: "
18127                                + args[opti]);
18128                        return;
18129                    }
18130                }
18131                pw.println(checkPermission(perm, pkg, user));
18132                return;
18133            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18134                dumpState.setDump(DumpState.DUMP_LIBS);
18135            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18136                dumpState.setDump(DumpState.DUMP_FEATURES);
18137            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18138                if (opti >= args.length) {
18139                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18140                            | DumpState.DUMP_SERVICE_RESOLVERS
18141                            | DumpState.DUMP_RECEIVER_RESOLVERS
18142                            | DumpState.DUMP_CONTENT_RESOLVERS);
18143                } else {
18144                    while (opti < args.length) {
18145                        String name = args[opti];
18146                        if ("a".equals(name) || "activity".equals(name)) {
18147                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18148                        } else if ("s".equals(name) || "service".equals(name)) {
18149                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18150                        } else if ("r".equals(name) || "receiver".equals(name)) {
18151                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18152                        } else if ("c".equals(name) || "content".equals(name)) {
18153                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18154                        } else {
18155                            pw.println("Error: unknown resolver table type: " + name);
18156                            return;
18157                        }
18158                        opti++;
18159                    }
18160                }
18161            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18162                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18163            } else if ("permission".equals(cmd)) {
18164                if (opti >= args.length) {
18165                    pw.println("Error: permission requires permission name");
18166                    return;
18167                }
18168                permissionNames = new ArraySet<>();
18169                while (opti < args.length) {
18170                    permissionNames.add(args[opti]);
18171                    opti++;
18172                }
18173                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18174                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18175            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18176                dumpState.setDump(DumpState.DUMP_PREFERRED);
18177            } else if ("preferred-xml".equals(cmd)) {
18178                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18179                if (opti < args.length && "--full".equals(args[opti])) {
18180                    fullPreferred = true;
18181                    opti++;
18182                }
18183            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18184                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18185            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18186                dumpState.setDump(DumpState.DUMP_PACKAGES);
18187            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18188                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18189            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18190                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18191            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18192                dumpState.setDump(DumpState.DUMP_MESSAGES);
18193            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18194                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18195            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18196                    || "intent-filter-verifiers".equals(cmd)) {
18197                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18198            } else if ("version".equals(cmd)) {
18199                dumpState.setDump(DumpState.DUMP_VERSION);
18200            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18201                dumpState.setDump(DumpState.DUMP_KEYSETS);
18202            } else if ("installs".equals(cmd)) {
18203                dumpState.setDump(DumpState.DUMP_INSTALLS);
18204            } else if ("frozen".equals(cmd)) {
18205                dumpState.setDump(DumpState.DUMP_FROZEN);
18206            } else if ("dexopt".equals(cmd)) {
18207                dumpState.setDump(DumpState.DUMP_DEXOPT);
18208            } else if ("compiler-stats".equals(cmd)) {
18209                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18210            } else if ("write".equals(cmd)) {
18211                synchronized (mPackages) {
18212                    mSettings.writeLPr();
18213                    pw.println("Settings written.");
18214                    return;
18215                }
18216            }
18217        }
18218
18219        if (checkin) {
18220            pw.println("vers,1");
18221        }
18222
18223        // reader
18224        synchronized (mPackages) {
18225            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18226                if (!checkin) {
18227                    if (dumpState.onTitlePrinted())
18228                        pw.println();
18229                    pw.println("Database versions:");
18230                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18231                }
18232            }
18233
18234            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18235                if (!checkin) {
18236                    if (dumpState.onTitlePrinted())
18237                        pw.println();
18238                    pw.println("Verifiers:");
18239                    pw.print("  Required: ");
18240                    pw.print(mRequiredVerifierPackage);
18241                    pw.print(" (uid=");
18242                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18243                            UserHandle.USER_SYSTEM));
18244                    pw.println(")");
18245                } else if (mRequiredVerifierPackage != null) {
18246                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18247                    pw.print(",");
18248                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18249                            UserHandle.USER_SYSTEM));
18250                }
18251            }
18252
18253            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18254                    packageName == null) {
18255                if (mIntentFilterVerifierComponent != null) {
18256                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18257                    if (!checkin) {
18258                        if (dumpState.onTitlePrinted())
18259                            pw.println();
18260                        pw.println("Intent Filter Verifier:");
18261                        pw.print("  Using: ");
18262                        pw.print(verifierPackageName);
18263                        pw.print(" (uid=");
18264                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18265                                UserHandle.USER_SYSTEM));
18266                        pw.println(")");
18267                    } else if (verifierPackageName != null) {
18268                        pw.print("ifv,"); pw.print(verifierPackageName);
18269                        pw.print(",");
18270                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18271                                UserHandle.USER_SYSTEM));
18272                    }
18273                } else {
18274                    pw.println();
18275                    pw.println("No Intent Filter Verifier available!");
18276                }
18277            }
18278
18279            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18280                boolean printedHeader = false;
18281                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18282                while (it.hasNext()) {
18283                    String name = it.next();
18284                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18285                    if (!checkin) {
18286                        if (!printedHeader) {
18287                            if (dumpState.onTitlePrinted())
18288                                pw.println();
18289                            pw.println("Libraries:");
18290                            printedHeader = true;
18291                        }
18292                        pw.print("  ");
18293                    } else {
18294                        pw.print("lib,");
18295                    }
18296                    pw.print(name);
18297                    if (!checkin) {
18298                        pw.print(" -> ");
18299                    }
18300                    if (ent.path != null) {
18301                        if (!checkin) {
18302                            pw.print("(jar) ");
18303                            pw.print(ent.path);
18304                        } else {
18305                            pw.print(",jar,");
18306                            pw.print(ent.path);
18307                        }
18308                    } else {
18309                        if (!checkin) {
18310                            pw.print("(apk) ");
18311                            pw.print(ent.apk);
18312                        } else {
18313                            pw.print(",apk,");
18314                            pw.print(ent.apk);
18315                        }
18316                    }
18317                    pw.println();
18318                }
18319            }
18320
18321            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18322                if (dumpState.onTitlePrinted())
18323                    pw.println();
18324                if (!checkin) {
18325                    pw.println("Features:");
18326                }
18327
18328                for (FeatureInfo feat : mAvailableFeatures.values()) {
18329                    if (checkin) {
18330                        pw.print("feat,");
18331                        pw.print(feat.name);
18332                        pw.print(",");
18333                        pw.println(feat.version);
18334                    } else {
18335                        pw.print("  ");
18336                        pw.print(feat.name);
18337                        if (feat.version > 0) {
18338                            pw.print(" version=");
18339                            pw.print(feat.version);
18340                        }
18341                        pw.println();
18342                    }
18343                }
18344            }
18345
18346            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18347                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18348                        : "Activity Resolver Table:", "  ", packageName,
18349                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18350                    dumpState.setTitlePrinted(true);
18351                }
18352            }
18353            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18354                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18355                        : "Receiver Resolver Table:", "  ", packageName,
18356                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18357                    dumpState.setTitlePrinted(true);
18358                }
18359            }
18360            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18361                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18362                        : "Service Resolver Table:", "  ", packageName,
18363                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18364                    dumpState.setTitlePrinted(true);
18365                }
18366            }
18367            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18368                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18369                        : "Provider Resolver Table:", "  ", packageName,
18370                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18371                    dumpState.setTitlePrinted(true);
18372                }
18373            }
18374
18375            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18376                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18377                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18378                    int user = mSettings.mPreferredActivities.keyAt(i);
18379                    if (pir.dump(pw,
18380                            dumpState.getTitlePrinted()
18381                                ? "\nPreferred Activities User " + user + ":"
18382                                : "Preferred Activities User " + user + ":", "  ",
18383                            packageName, true, false)) {
18384                        dumpState.setTitlePrinted(true);
18385                    }
18386                }
18387            }
18388
18389            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18390                pw.flush();
18391                FileOutputStream fout = new FileOutputStream(fd);
18392                BufferedOutputStream str = new BufferedOutputStream(fout);
18393                XmlSerializer serializer = new FastXmlSerializer();
18394                try {
18395                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18396                    serializer.startDocument(null, true);
18397                    serializer.setFeature(
18398                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18399                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18400                    serializer.endDocument();
18401                    serializer.flush();
18402                } catch (IllegalArgumentException e) {
18403                    pw.println("Failed writing: " + e);
18404                } catch (IllegalStateException e) {
18405                    pw.println("Failed writing: " + e);
18406                } catch (IOException e) {
18407                    pw.println("Failed writing: " + e);
18408                }
18409            }
18410
18411            if (!checkin
18412                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18413                    && packageName == null) {
18414                pw.println();
18415                int count = mSettings.mPackages.size();
18416                if (count == 0) {
18417                    pw.println("No applications!");
18418                    pw.println();
18419                } else {
18420                    final String prefix = "  ";
18421                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18422                    if (allPackageSettings.size() == 0) {
18423                        pw.println("No domain preferred apps!");
18424                        pw.println();
18425                    } else {
18426                        pw.println("App verification status:");
18427                        pw.println();
18428                        count = 0;
18429                        for (PackageSetting ps : allPackageSettings) {
18430                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18431                            if (ivi == null || ivi.getPackageName() == null) continue;
18432                            pw.println(prefix + "Package: " + ivi.getPackageName());
18433                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18434                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18435                            pw.println();
18436                            count++;
18437                        }
18438                        if (count == 0) {
18439                            pw.println(prefix + "No app verification established.");
18440                            pw.println();
18441                        }
18442                        for (int userId : sUserManager.getUserIds()) {
18443                            pw.println("App linkages for user " + userId + ":");
18444                            pw.println();
18445                            count = 0;
18446                            for (PackageSetting ps : allPackageSettings) {
18447                                final long status = ps.getDomainVerificationStatusForUser(userId);
18448                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18449                                    continue;
18450                                }
18451                                pw.println(prefix + "Package: " + ps.name);
18452                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18453                                String statusStr = IntentFilterVerificationInfo.
18454                                        getStatusStringFromValue(status);
18455                                pw.println(prefix + "Status:  " + statusStr);
18456                                pw.println();
18457                                count++;
18458                            }
18459                            if (count == 0) {
18460                                pw.println(prefix + "No configured app linkages.");
18461                                pw.println();
18462                            }
18463                        }
18464                    }
18465                }
18466            }
18467
18468            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18469                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18470                if (packageName == null && permissionNames == null) {
18471                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18472                        if (iperm == 0) {
18473                            if (dumpState.onTitlePrinted())
18474                                pw.println();
18475                            pw.println("AppOp Permissions:");
18476                        }
18477                        pw.print("  AppOp Permission ");
18478                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18479                        pw.println(":");
18480                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18481                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18482                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18483                        }
18484                    }
18485                }
18486            }
18487
18488            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18489                boolean printedSomething = false;
18490                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18491                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18492                        continue;
18493                    }
18494                    if (!printedSomething) {
18495                        if (dumpState.onTitlePrinted())
18496                            pw.println();
18497                        pw.println("Registered ContentProviders:");
18498                        printedSomething = true;
18499                    }
18500                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18501                    pw.print("    "); pw.println(p.toString());
18502                }
18503                printedSomething = false;
18504                for (Map.Entry<String, PackageParser.Provider> entry :
18505                        mProvidersByAuthority.entrySet()) {
18506                    PackageParser.Provider p = entry.getValue();
18507                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18508                        continue;
18509                    }
18510                    if (!printedSomething) {
18511                        if (dumpState.onTitlePrinted())
18512                            pw.println();
18513                        pw.println("ContentProvider Authorities:");
18514                        printedSomething = true;
18515                    }
18516                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18517                    pw.print("    "); pw.println(p.toString());
18518                    if (p.info != null && p.info.applicationInfo != null) {
18519                        final String appInfo = p.info.applicationInfo.toString();
18520                        pw.print("      applicationInfo="); pw.println(appInfo);
18521                    }
18522                }
18523            }
18524
18525            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18526                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18527            }
18528
18529            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18530                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18531            }
18532
18533            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18534                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18535            }
18536
18537            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18538                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18539            }
18540
18541            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18542                // XXX should handle packageName != null by dumping only install data that
18543                // the given package is involved with.
18544                if (dumpState.onTitlePrinted()) pw.println();
18545                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18546            }
18547
18548            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18549                // XXX should handle packageName != null by dumping only install data that
18550                // the given package is involved with.
18551                if (dumpState.onTitlePrinted()) pw.println();
18552
18553                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18554                ipw.println();
18555                ipw.println("Frozen packages:");
18556                ipw.increaseIndent();
18557                if (mFrozenPackages.size() == 0) {
18558                    ipw.println("(none)");
18559                } else {
18560                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18561                        ipw.println(mFrozenPackages.valueAt(i));
18562                    }
18563                }
18564                ipw.decreaseIndent();
18565            }
18566
18567            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18568                if (dumpState.onTitlePrinted()) pw.println();
18569                dumpDexoptStateLPr(pw, packageName);
18570            }
18571
18572            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18573                if (dumpState.onTitlePrinted()) pw.println();
18574                dumpCompilerStatsLPr(pw, packageName);
18575            }
18576
18577            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18578                if (dumpState.onTitlePrinted()) pw.println();
18579                mSettings.dumpReadMessagesLPr(pw, dumpState);
18580
18581                pw.println();
18582                pw.println("Package warning messages:");
18583                BufferedReader in = null;
18584                String line = null;
18585                try {
18586                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18587                    while ((line = in.readLine()) != null) {
18588                        if (line.contains("ignored: updated version")) continue;
18589                        pw.println(line);
18590                    }
18591                } catch (IOException ignored) {
18592                } finally {
18593                    IoUtils.closeQuietly(in);
18594                }
18595            }
18596
18597            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18598                BufferedReader in = null;
18599                String line = null;
18600                try {
18601                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18602                    while ((line = in.readLine()) != null) {
18603                        if (line.contains("ignored: updated version")) continue;
18604                        pw.print("msg,");
18605                        pw.println(line);
18606                    }
18607                } catch (IOException ignored) {
18608                } finally {
18609                    IoUtils.closeQuietly(in);
18610                }
18611            }
18612        }
18613    }
18614
18615    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18616        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18617        ipw.println();
18618        ipw.println("Dexopt state:");
18619        ipw.increaseIndent();
18620        Collection<PackageParser.Package> packages = null;
18621        if (packageName != null) {
18622            PackageParser.Package targetPackage = mPackages.get(packageName);
18623            if (targetPackage != null) {
18624                packages = Collections.singletonList(targetPackage);
18625            } else {
18626                ipw.println("Unable to find package: " + packageName);
18627                return;
18628            }
18629        } else {
18630            packages = mPackages.values();
18631        }
18632
18633        for (PackageParser.Package pkg : packages) {
18634            ipw.println("[" + pkg.packageName + "]");
18635            ipw.increaseIndent();
18636            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18637            ipw.decreaseIndent();
18638        }
18639    }
18640
18641    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18642        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18643        ipw.println();
18644        ipw.println("Compiler stats:");
18645        ipw.increaseIndent();
18646        Collection<PackageParser.Package> packages = null;
18647        if (packageName != null) {
18648            PackageParser.Package targetPackage = mPackages.get(packageName);
18649            if (targetPackage != null) {
18650                packages = Collections.singletonList(targetPackage);
18651            } else {
18652                ipw.println("Unable to find package: " + packageName);
18653                return;
18654            }
18655        } else {
18656            packages = mPackages.values();
18657        }
18658
18659        for (PackageParser.Package pkg : packages) {
18660            ipw.println("[" + pkg.packageName + "]");
18661            ipw.increaseIndent();
18662
18663            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18664            if (stats == null) {
18665                ipw.println("(No recorded stats)");
18666            } else {
18667                stats.dump(ipw);
18668            }
18669            ipw.decreaseIndent();
18670        }
18671    }
18672
18673    private String dumpDomainString(String packageName) {
18674        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18675                .getList();
18676        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18677
18678        ArraySet<String> result = new ArraySet<>();
18679        if (iviList.size() > 0) {
18680            for (IntentFilterVerificationInfo ivi : iviList) {
18681                for (String host : ivi.getDomains()) {
18682                    result.add(host);
18683                }
18684            }
18685        }
18686        if (filters != null && filters.size() > 0) {
18687            for (IntentFilter filter : filters) {
18688                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18689                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18690                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18691                    result.addAll(filter.getHostsList());
18692                }
18693            }
18694        }
18695
18696        StringBuilder sb = new StringBuilder(result.size() * 16);
18697        for (String domain : result) {
18698            if (sb.length() > 0) sb.append(" ");
18699            sb.append(domain);
18700        }
18701        return sb.toString();
18702    }
18703
18704    // ------- apps on sdcard specific code -------
18705    static final boolean DEBUG_SD_INSTALL = false;
18706
18707    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18708
18709    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18710
18711    private boolean mMediaMounted = false;
18712
18713    static String getEncryptKey() {
18714        try {
18715            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18716                    SD_ENCRYPTION_KEYSTORE_NAME);
18717            if (sdEncKey == null) {
18718                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18719                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18720                if (sdEncKey == null) {
18721                    Slog.e(TAG, "Failed to create encryption keys");
18722                    return null;
18723                }
18724            }
18725            return sdEncKey;
18726        } catch (NoSuchAlgorithmException nsae) {
18727            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18728            return null;
18729        } catch (IOException ioe) {
18730            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18731            return null;
18732        }
18733    }
18734
18735    /*
18736     * Update media status on PackageManager.
18737     */
18738    @Override
18739    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18740        int callingUid = Binder.getCallingUid();
18741        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18742            throw new SecurityException("Media status can only be updated by the system");
18743        }
18744        // reader; this apparently protects mMediaMounted, but should probably
18745        // be a different lock in that case.
18746        synchronized (mPackages) {
18747            Log.i(TAG, "Updating external media status from "
18748                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18749                    + (mediaStatus ? "mounted" : "unmounted"));
18750            if (DEBUG_SD_INSTALL)
18751                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18752                        + ", mMediaMounted=" + mMediaMounted);
18753            if (mediaStatus == mMediaMounted) {
18754                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18755                        : 0, -1);
18756                mHandler.sendMessage(msg);
18757                return;
18758            }
18759            mMediaMounted = mediaStatus;
18760        }
18761        // Queue up an async operation since the package installation may take a
18762        // little while.
18763        mHandler.post(new Runnable() {
18764            public void run() {
18765                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18766            }
18767        });
18768    }
18769
18770    /**
18771     * Called by MountService when the initial ASECs to scan are available.
18772     * Should block until all the ASEC containers are finished being scanned.
18773     */
18774    public void scanAvailableAsecs() {
18775        updateExternalMediaStatusInner(true, false, false);
18776    }
18777
18778    /*
18779     * Collect information of applications on external media, map them against
18780     * existing containers and update information based on current mount status.
18781     * Please note that we always have to report status if reportStatus has been
18782     * set to true especially when unloading packages.
18783     */
18784    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18785            boolean externalStorage) {
18786        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18787        int[] uidArr = EmptyArray.INT;
18788
18789        final String[] list = PackageHelper.getSecureContainerList();
18790        if (ArrayUtils.isEmpty(list)) {
18791            Log.i(TAG, "No secure containers found");
18792        } else {
18793            // Process list of secure containers and categorize them
18794            // as active or stale based on their package internal state.
18795
18796            // reader
18797            synchronized (mPackages) {
18798                for (String cid : list) {
18799                    // Leave stages untouched for now; installer service owns them
18800                    if (PackageInstallerService.isStageName(cid)) continue;
18801
18802                    if (DEBUG_SD_INSTALL)
18803                        Log.i(TAG, "Processing container " + cid);
18804                    String pkgName = getAsecPackageName(cid);
18805                    if (pkgName == null) {
18806                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18807                        continue;
18808                    }
18809                    if (DEBUG_SD_INSTALL)
18810                        Log.i(TAG, "Looking for pkg : " + pkgName);
18811
18812                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18813                    if (ps == null) {
18814                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18815                        continue;
18816                    }
18817
18818                    /*
18819                     * Skip packages that are not external if we're unmounting
18820                     * external storage.
18821                     */
18822                    if (externalStorage && !isMounted && !isExternal(ps)) {
18823                        continue;
18824                    }
18825
18826                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18827                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18828                    // The package status is changed only if the code path
18829                    // matches between settings and the container id.
18830                    if (ps.codePathString != null
18831                            && ps.codePathString.startsWith(args.getCodePath())) {
18832                        if (DEBUG_SD_INSTALL) {
18833                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18834                                    + " at code path: " + ps.codePathString);
18835                        }
18836
18837                        // We do have a valid package installed on sdcard
18838                        processCids.put(args, ps.codePathString);
18839                        final int uid = ps.appId;
18840                        if (uid != -1) {
18841                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18842                        }
18843                    } else {
18844                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18845                                + ps.codePathString);
18846                    }
18847                }
18848            }
18849
18850            Arrays.sort(uidArr);
18851        }
18852
18853        // Process packages with valid entries.
18854        if (isMounted) {
18855            if (DEBUG_SD_INSTALL)
18856                Log.i(TAG, "Loading packages");
18857            loadMediaPackages(processCids, uidArr, externalStorage);
18858            startCleaningPackages();
18859            mInstallerService.onSecureContainersAvailable();
18860        } else {
18861            if (DEBUG_SD_INSTALL)
18862                Log.i(TAG, "Unloading packages");
18863            unloadMediaPackages(processCids, uidArr, reportStatus);
18864        }
18865    }
18866
18867    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18868            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18869        final int size = infos.size();
18870        final String[] packageNames = new String[size];
18871        final int[] packageUids = new int[size];
18872        for (int i = 0; i < size; i++) {
18873            final ApplicationInfo info = infos.get(i);
18874            packageNames[i] = info.packageName;
18875            packageUids[i] = info.uid;
18876        }
18877        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18878                finishedReceiver);
18879    }
18880
18881    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18882            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18883        sendResourcesChangedBroadcast(mediaStatus, replacing,
18884                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18885    }
18886
18887    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18888            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18889        int size = pkgList.length;
18890        if (size > 0) {
18891            // Send broadcasts here
18892            Bundle extras = new Bundle();
18893            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18894            if (uidArr != null) {
18895                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18896            }
18897            if (replacing) {
18898                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18899            }
18900            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18901                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18902            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18903        }
18904    }
18905
18906   /*
18907     * Look at potentially valid container ids from processCids If package
18908     * information doesn't match the one on record or package scanning fails,
18909     * the cid is added to list of removeCids. We currently don't delete stale
18910     * containers.
18911     */
18912    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18913            boolean externalStorage) {
18914        ArrayList<String> pkgList = new ArrayList<String>();
18915        Set<AsecInstallArgs> keys = processCids.keySet();
18916
18917        for (AsecInstallArgs args : keys) {
18918            String codePath = processCids.get(args);
18919            if (DEBUG_SD_INSTALL)
18920                Log.i(TAG, "Loading container : " + args.cid);
18921            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18922            try {
18923                // Make sure there are no container errors first.
18924                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18925                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18926                            + " when installing from sdcard");
18927                    continue;
18928                }
18929                // Check code path here.
18930                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18931                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18932                            + " does not match one in settings " + codePath);
18933                    continue;
18934                }
18935                // Parse package
18936                int parseFlags = mDefParseFlags;
18937                if (args.isExternalAsec()) {
18938                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18939                }
18940                if (args.isFwdLocked()) {
18941                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18942                }
18943
18944                synchronized (mInstallLock) {
18945                    PackageParser.Package pkg = null;
18946                    try {
18947                        // Sadly we don't know the package name yet to freeze it
18948                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18949                                SCAN_IGNORE_FROZEN, 0, null);
18950                    } catch (PackageManagerException e) {
18951                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18952                    }
18953                    // Scan the package
18954                    if (pkg != null) {
18955                        /*
18956                         * TODO why is the lock being held? doPostInstall is
18957                         * called in other places without the lock. This needs
18958                         * to be straightened out.
18959                         */
18960                        // writer
18961                        synchronized (mPackages) {
18962                            retCode = PackageManager.INSTALL_SUCCEEDED;
18963                            pkgList.add(pkg.packageName);
18964                            // Post process args
18965                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18966                                    pkg.applicationInfo.uid);
18967                        }
18968                    } else {
18969                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18970                    }
18971                }
18972
18973            } finally {
18974                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18975                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18976                }
18977            }
18978        }
18979        // writer
18980        synchronized (mPackages) {
18981            // If the platform SDK has changed since the last time we booted,
18982            // we need to re-grant app permission to catch any new ones that
18983            // appear. This is really a hack, and means that apps can in some
18984            // cases get permissions that the user didn't initially explicitly
18985            // allow... it would be nice to have some better way to handle
18986            // this situation.
18987            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18988                    : mSettings.getInternalVersion();
18989            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18990                    : StorageManager.UUID_PRIVATE_INTERNAL;
18991
18992            int updateFlags = UPDATE_PERMISSIONS_ALL;
18993            if (ver.sdkVersion != mSdkVersion) {
18994                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18995                        + mSdkVersion + "; regranting permissions for external");
18996                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18997            }
18998            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18999
19000            // Yay, everything is now upgraded
19001            ver.forceCurrent();
19002
19003            // can downgrade to reader
19004            // Persist settings
19005            mSettings.writeLPr();
19006        }
19007        // Send a broadcast to let everyone know we are done processing
19008        if (pkgList.size() > 0) {
19009            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19010        }
19011    }
19012
19013   /*
19014     * Utility method to unload a list of specified containers
19015     */
19016    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19017        // Just unmount all valid containers.
19018        for (AsecInstallArgs arg : cidArgs) {
19019            synchronized (mInstallLock) {
19020                arg.doPostDeleteLI(false);
19021           }
19022       }
19023   }
19024
19025    /*
19026     * Unload packages mounted on external media. This involves deleting package
19027     * data from internal structures, sending broadcasts about disabled packages,
19028     * gc'ing to free up references, unmounting all secure containers
19029     * corresponding to packages on external media, and posting a
19030     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19031     * that we always have to post this message if status has been requested no
19032     * matter what.
19033     */
19034    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19035            final boolean reportStatus) {
19036        if (DEBUG_SD_INSTALL)
19037            Log.i(TAG, "unloading media packages");
19038        ArrayList<String> pkgList = new ArrayList<String>();
19039        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19040        final Set<AsecInstallArgs> keys = processCids.keySet();
19041        for (AsecInstallArgs args : keys) {
19042            String pkgName = args.getPackageName();
19043            if (DEBUG_SD_INSTALL)
19044                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19045            // Delete package internally
19046            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19047            synchronized (mInstallLock) {
19048                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19049                final boolean res;
19050                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19051                        "unloadMediaPackages")) {
19052                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19053                            null);
19054                }
19055                if (res) {
19056                    pkgList.add(pkgName);
19057                } else {
19058                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19059                    failedList.add(args);
19060                }
19061            }
19062        }
19063
19064        // reader
19065        synchronized (mPackages) {
19066            // We didn't update the settings after removing each package;
19067            // write them now for all packages.
19068            mSettings.writeLPr();
19069        }
19070
19071        // We have to absolutely send UPDATED_MEDIA_STATUS only
19072        // after confirming that all the receivers processed the ordered
19073        // broadcast when packages get disabled, force a gc to clean things up.
19074        // and unload all the containers.
19075        if (pkgList.size() > 0) {
19076            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19077                    new IIntentReceiver.Stub() {
19078                public void performReceive(Intent intent, int resultCode, String data,
19079                        Bundle extras, boolean ordered, boolean sticky,
19080                        int sendingUser) throws RemoteException {
19081                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19082                            reportStatus ? 1 : 0, 1, keys);
19083                    mHandler.sendMessage(msg);
19084                }
19085            });
19086        } else {
19087            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19088                    keys);
19089            mHandler.sendMessage(msg);
19090        }
19091    }
19092
19093    private void loadPrivatePackages(final VolumeInfo vol) {
19094        mHandler.post(new Runnable() {
19095            @Override
19096            public void run() {
19097                loadPrivatePackagesInner(vol);
19098            }
19099        });
19100    }
19101
19102    private void loadPrivatePackagesInner(VolumeInfo vol) {
19103        final String volumeUuid = vol.fsUuid;
19104        if (TextUtils.isEmpty(volumeUuid)) {
19105            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19106            return;
19107        }
19108
19109        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19110        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19111        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19112
19113        final VersionInfo ver;
19114        final List<PackageSetting> packages;
19115        synchronized (mPackages) {
19116            ver = mSettings.findOrCreateVersion(volumeUuid);
19117            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19118        }
19119
19120        for (PackageSetting ps : packages) {
19121            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19122            synchronized (mInstallLock) {
19123                final PackageParser.Package pkg;
19124                try {
19125                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19126                    loaded.add(pkg.applicationInfo);
19127
19128                } catch (PackageManagerException e) {
19129                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19130                }
19131
19132                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19133                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19134                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19135                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19136                }
19137            }
19138        }
19139
19140        // Reconcile app data for all started/unlocked users
19141        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19142        final UserManager um = mContext.getSystemService(UserManager.class);
19143        UserManagerInternal umInternal = getUserManagerInternal();
19144        for (UserInfo user : um.getUsers()) {
19145            final int flags;
19146            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19147                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19148            } else if (umInternal.isUserRunning(user.id)) {
19149                flags = StorageManager.FLAG_STORAGE_DE;
19150            } else {
19151                continue;
19152            }
19153
19154            try {
19155                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19156                synchronized (mInstallLock) {
19157                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19158                }
19159            } catch (IllegalStateException e) {
19160                // Device was probably ejected, and we'll process that event momentarily
19161                Slog.w(TAG, "Failed to prepare storage: " + e);
19162            }
19163        }
19164
19165        synchronized (mPackages) {
19166            int updateFlags = UPDATE_PERMISSIONS_ALL;
19167            if (ver.sdkVersion != mSdkVersion) {
19168                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19169                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19170                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19171            }
19172            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19173
19174            // Yay, everything is now upgraded
19175            ver.forceCurrent();
19176
19177            mSettings.writeLPr();
19178        }
19179
19180        for (PackageFreezer freezer : freezers) {
19181            freezer.close();
19182        }
19183
19184        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19185        sendResourcesChangedBroadcast(true, false, loaded, null);
19186    }
19187
19188    private void unloadPrivatePackages(final VolumeInfo vol) {
19189        mHandler.post(new Runnable() {
19190            @Override
19191            public void run() {
19192                unloadPrivatePackagesInner(vol);
19193            }
19194        });
19195    }
19196
19197    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19198        final String volumeUuid = vol.fsUuid;
19199        if (TextUtils.isEmpty(volumeUuid)) {
19200            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19201            return;
19202        }
19203
19204        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19205        synchronized (mInstallLock) {
19206        synchronized (mPackages) {
19207            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19208            for (PackageSetting ps : packages) {
19209                if (ps.pkg == null) continue;
19210
19211                final ApplicationInfo info = ps.pkg.applicationInfo;
19212                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19213                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19214
19215                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19216                        "unloadPrivatePackagesInner")) {
19217                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19218                            false, null)) {
19219                        unloaded.add(info);
19220                    } else {
19221                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19222                    }
19223                }
19224
19225                // Try very hard to release any references to this package
19226                // so we don't risk the system server being killed due to
19227                // open FDs
19228                AttributeCache.instance().removePackage(ps.name);
19229            }
19230
19231            mSettings.writeLPr();
19232        }
19233        }
19234
19235        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19236        sendResourcesChangedBroadcast(false, false, unloaded, null);
19237
19238        // Try very hard to release any references to this path so we don't risk
19239        // the system server being killed due to open FDs
19240        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19241
19242        for (int i = 0; i < 3; i++) {
19243            System.gc();
19244            System.runFinalization();
19245        }
19246    }
19247
19248    /**
19249     * Prepare storage areas for given user on all mounted devices.
19250     */
19251    void prepareUserData(int userId, int userSerial, int flags) {
19252        synchronized (mInstallLock) {
19253            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19254            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19255                final String volumeUuid = vol.getFsUuid();
19256                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19257            }
19258        }
19259    }
19260
19261    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19262            boolean allowRecover) {
19263        // Prepare storage and verify that serial numbers are consistent; if
19264        // there's a mismatch we need to destroy to avoid leaking data
19265        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19266        try {
19267            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19268
19269            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19270                UserManagerService.enforceSerialNumber(
19271                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19272                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19273                    UserManagerService.enforceSerialNumber(
19274                            Environment.getDataSystemDeDirectory(userId), userSerial);
19275                }
19276            }
19277            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19278                UserManagerService.enforceSerialNumber(
19279                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19280                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19281                    UserManagerService.enforceSerialNumber(
19282                            Environment.getDataSystemCeDirectory(userId), userSerial);
19283                }
19284            }
19285
19286            synchronized (mInstallLock) {
19287                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19288            }
19289        } catch (Exception e) {
19290            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19291                    + " because we failed to prepare: " + e);
19292            destroyUserDataLI(volumeUuid, userId,
19293                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19294
19295            if (allowRecover) {
19296                // Try one last time; if we fail again we're really in trouble
19297                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19298            }
19299        }
19300    }
19301
19302    /**
19303     * Destroy storage areas for given user on all mounted devices.
19304     */
19305    void destroyUserData(int userId, int flags) {
19306        synchronized (mInstallLock) {
19307            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19308            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19309                final String volumeUuid = vol.getFsUuid();
19310                destroyUserDataLI(volumeUuid, userId, flags);
19311            }
19312        }
19313    }
19314
19315    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19316        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19317        try {
19318            // Clean up app data, profile data, and media data
19319            mInstaller.destroyUserData(volumeUuid, userId, flags);
19320
19321            // Clean up system data
19322            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19323                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19324                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19325                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19326                }
19327                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19328                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19329                }
19330            }
19331
19332            // Data with special labels is now gone, so finish the job
19333            storage.destroyUserStorage(volumeUuid, userId, flags);
19334
19335        } catch (Exception e) {
19336            logCriticalInfo(Log.WARN,
19337                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19338        }
19339    }
19340
19341    /**
19342     * Examine all users present on given mounted volume, and destroy data
19343     * belonging to users that are no longer valid, or whose user ID has been
19344     * recycled.
19345     */
19346    private void reconcileUsers(String volumeUuid) {
19347        final List<File> files = new ArrayList<>();
19348        Collections.addAll(files, FileUtils
19349                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19350        Collections.addAll(files, FileUtils
19351                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19352        Collections.addAll(files, FileUtils
19353                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19354        Collections.addAll(files, FileUtils
19355                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19356        for (File file : files) {
19357            if (!file.isDirectory()) continue;
19358
19359            final int userId;
19360            final UserInfo info;
19361            try {
19362                userId = Integer.parseInt(file.getName());
19363                info = sUserManager.getUserInfo(userId);
19364            } catch (NumberFormatException e) {
19365                Slog.w(TAG, "Invalid user directory " + file);
19366                continue;
19367            }
19368
19369            boolean destroyUser = false;
19370            if (info == null) {
19371                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19372                        + " because no matching user was found");
19373                destroyUser = true;
19374            } else if (!mOnlyCore) {
19375                try {
19376                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19377                } catch (IOException e) {
19378                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19379                            + " because we failed to enforce serial number: " + e);
19380                    destroyUser = true;
19381                }
19382            }
19383
19384            if (destroyUser) {
19385                synchronized (mInstallLock) {
19386                    destroyUserDataLI(volumeUuid, userId,
19387                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19388                }
19389            }
19390        }
19391    }
19392
19393    private void assertPackageKnown(String volumeUuid, String packageName)
19394            throws PackageManagerException {
19395        synchronized (mPackages) {
19396            final PackageSetting ps = mSettings.mPackages.get(packageName);
19397            if (ps == null) {
19398                throw new PackageManagerException("Package " + packageName + " is unknown");
19399            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19400                throw new PackageManagerException(
19401                        "Package " + packageName + " found on unknown volume " + volumeUuid
19402                                + "; expected volume " + ps.volumeUuid);
19403            }
19404        }
19405    }
19406
19407    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19408            throws PackageManagerException {
19409        synchronized (mPackages) {
19410            final PackageSetting ps = mSettings.mPackages.get(packageName);
19411            if (ps == null) {
19412                throw new PackageManagerException("Package " + packageName + " is unknown");
19413            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19414                throw new PackageManagerException(
19415                        "Package " + packageName + " found on unknown volume " + volumeUuid
19416                                + "; expected volume " + ps.volumeUuid);
19417            } else if (!ps.getInstalled(userId)) {
19418                throw new PackageManagerException(
19419                        "Package " + packageName + " not installed for user " + userId);
19420            }
19421        }
19422    }
19423
19424    /**
19425     * Examine all apps present on given mounted volume, and destroy apps that
19426     * aren't expected, either due to uninstallation or reinstallation on
19427     * another volume.
19428     */
19429    private void reconcileApps(String volumeUuid) {
19430        final File[] files = FileUtils
19431                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19432        for (File file : files) {
19433            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19434                    && !PackageInstallerService.isStageName(file.getName());
19435            if (!isPackage) {
19436                // Ignore entries which are not packages
19437                continue;
19438            }
19439
19440            try {
19441                final PackageLite pkg = PackageParser.parsePackageLite(file,
19442                        PackageParser.PARSE_MUST_BE_APK);
19443                assertPackageKnown(volumeUuid, pkg.packageName);
19444
19445            } catch (PackageParserException | PackageManagerException e) {
19446                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19447                synchronized (mInstallLock) {
19448                    removeCodePathLI(file);
19449                }
19450            }
19451        }
19452    }
19453
19454    /**
19455     * Reconcile all app data for the given user.
19456     * <p>
19457     * Verifies that directories exist and that ownership and labeling is
19458     * correct for all installed apps on all mounted volumes.
19459     */
19460    void reconcileAppsData(int userId, int flags) {
19461        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19462        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19463            final String volumeUuid = vol.getFsUuid();
19464            synchronized (mInstallLock) {
19465                reconcileAppsDataLI(volumeUuid, userId, flags);
19466            }
19467        }
19468    }
19469
19470    /**
19471     * Reconcile all app data on given mounted volume.
19472     * <p>
19473     * Destroys app data that isn't expected, either due to uninstallation or
19474     * reinstallation on another volume.
19475     * <p>
19476     * Verifies that directories exist and that ownership and labeling is
19477     * correct for all installed apps.
19478     */
19479    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19480        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19481                + Integer.toHexString(flags));
19482
19483        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19484        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19485
19486        boolean restoreconNeeded = false;
19487
19488        // First look for stale data that doesn't belong, and check if things
19489        // have changed since we did our last restorecon
19490        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19491            if (StorageManager.isFileEncryptedNativeOrEmulated()
19492                    && !StorageManager.isUserKeyUnlocked(userId)) {
19493                throw new RuntimeException(
19494                        "Yikes, someone asked us to reconcile CE storage while " + userId
19495                                + " was still locked; this would have caused massive data loss!");
19496            }
19497
19498            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19499
19500            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19501            for (File file : files) {
19502                final String packageName = file.getName();
19503                try {
19504                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19505                } catch (PackageManagerException e) {
19506                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19507                    try {
19508                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19509                                StorageManager.FLAG_STORAGE_CE, 0);
19510                    } catch (InstallerException e2) {
19511                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19512                    }
19513                }
19514            }
19515        }
19516        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19517            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19518
19519            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19520            for (File file : files) {
19521                final String packageName = file.getName();
19522                try {
19523                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19524                } catch (PackageManagerException e) {
19525                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19526                    try {
19527                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19528                                StorageManager.FLAG_STORAGE_DE, 0);
19529                    } catch (InstallerException e2) {
19530                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19531                    }
19532                }
19533            }
19534        }
19535
19536        // Ensure that data directories are ready to roll for all packages
19537        // installed for this volume and user
19538        final List<PackageSetting> packages;
19539        synchronized (mPackages) {
19540            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19541        }
19542        int preparedCount = 0;
19543        for (PackageSetting ps : packages) {
19544            final String packageName = ps.name;
19545            if (ps.pkg == null) {
19546                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19547                // TODO: might be due to legacy ASEC apps; we should circle back
19548                // and reconcile again once they're scanned
19549                continue;
19550            }
19551
19552            if (ps.getInstalled(userId)) {
19553                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19554
19555                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19556                    // We may have just shuffled around app data directories, so
19557                    // prepare them one more time
19558                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19559                }
19560
19561                preparedCount++;
19562            }
19563        }
19564
19565        if (restoreconNeeded) {
19566            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19567                SELinuxMMAC.setRestoreconDone(ceDir);
19568            }
19569            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19570                SELinuxMMAC.setRestoreconDone(deDir);
19571            }
19572        }
19573
19574        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19575                + " packages; restoreconNeeded was " + restoreconNeeded);
19576    }
19577
19578    /**
19579     * Prepare app data for the given app just after it was installed or
19580     * upgraded. This method carefully only touches users that it's installed
19581     * for, and it forces a restorecon to handle any seinfo changes.
19582     * <p>
19583     * Verifies that directories exist and that ownership and labeling is
19584     * correct for all installed apps. If there is an ownership mismatch, it
19585     * will try recovering system apps by wiping data; third-party app data is
19586     * left intact.
19587     * <p>
19588     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19589     */
19590    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19591        final PackageSetting ps;
19592        synchronized (mPackages) {
19593            ps = mSettings.mPackages.get(pkg.packageName);
19594            mSettings.writeKernelMappingLPr(ps);
19595        }
19596
19597        final UserManager um = mContext.getSystemService(UserManager.class);
19598        UserManagerInternal umInternal = getUserManagerInternal();
19599        for (UserInfo user : um.getUsers()) {
19600            final int flags;
19601            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19602                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19603            } else if (umInternal.isUserRunning(user.id)) {
19604                flags = StorageManager.FLAG_STORAGE_DE;
19605            } else {
19606                continue;
19607            }
19608
19609            if (ps.getInstalled(user.id)) {
19610                // Whenever an app changes, force a restorecon of its data
19611                // TODO: when user data is locked, mark that we're still dirty
19612                prepareAppDataLIF(pkg, user.id, flags, true);
19613            }
19614        }
19615    }
19616
19617    /**
19618     * Prepare app data for the given app.
19619     * <p>
19620     * Verifies that directories exist and that ownership and labeling is
19621     * correct for all installed apps. If there is an ownership mismatch, this
19622     * will try recovering system apps by wiping data; third-party app data is
19623     * left intact.
19624     */
19625    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19626            boolean restoreconNeeded) {
19627        if (pkg == null) {
19628            Slog.wtf(TAG, "Package was null!", new Throwable());
19629            return;
19630        }
19631        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19632        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19633        for (int i = 0; i < childCount; i++) {
19634            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19635        }
19636    }
19637
19638    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19639            boolean restoreconNeeded) {
19640        if (DEBUG_APP_DATA) {
19641            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19642                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19643        }
19644
19645        final String volumeUuid = pkg.volumeUuid;
19646        final String packageName = pkg.packageName;
19647        final ApplicationInfo app = pkg.applicationInfo;
19648        final int appId = UserHandle.getAppId(app.uid);
19649
19650        Preconditions.checkNotNull(app.seinfo);
19651
19652        try {
19653            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19654                    appId, app.seinfo, app.targetSdkVersion);
19655        } catch (InstallerException e) {
19656            if (app.isSystemApp()) {
19657                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19658                        + ", but trying to recover: " + e);
19659                destroyAppDataLeafLIF(pkg, userId, flags);
19660                try {
19661                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19662                            appId, app.seinfo, app.targetSdkVersion);
19663                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19664                } catch (InstallerException e2) {
19665                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19666                }
19667            } else {
19668                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19669            }
19670        }
19671
19672        if (restoreconNeeded) {
19673            try {
19674                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19675                        app.seinfo);
19676            } catch (InstallerException e) {
19677                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19678            }
19679        }
19680
19681        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19682            try {
19683                // CE storage is unlocked right now, so read out the inode and
19684                // remember for use later when it's locked
19685                // TODO: mark this structure as dirty so we persist it!
19686                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19687                        StorageManager.FLAG_STORAGE_CE);
19688                synchronized (mPackages) {
19689                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19690                    if (ps != null) {
19691                        ps.setCeDataInode(ceDataInode, userId);
19692                    }
19693                }
19694            } catch (InstallerException e) {
19695                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19696            }
19697        }
19698
19699        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19700    }
19701
19702    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19703        if (pkg == null) {
19704            Slog.wtf(TAG, "Package was null!", new Throwable());
19705            return;
19706        }
19707        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19708        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19709        for (int i = 0; i < childCount; i++) {
19710            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19711        }
19712    }
19713
19714    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19715        final String volumeUuid = pkg.volumeUuid;
19716        final String packageName = pkg.packageName;
19717        final ApplicationInfo app = pkg.applicationInfo;
19718
19719        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19720            // Create a native library symlink only if we have native libraries
19721            // and if the native libraries are 32 bit libraries. We do not provide
19722            // this symlink for 64 bit libraries.
19723            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19724                final String nativeLibPath = app.nativeLibraryDir;
19725                try {
19726                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19727                            nativeLibPath, userId);
19728                } catch (InstallerException e) {
19729                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19730                }
19731            }
19732        }
19733    }
19734
19735    /**
19736     * For system apps on non-FBE devices, this method migrates any existing
19737     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19738     * requested by the app.
19739     */
19740    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19741        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19742                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19743            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19744                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19745            try {
19746                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19747                        storageTarget);
19748            } catch (InstallerException e) {
19749                logCriticalInfo(Log.WARN,
19750                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19751            }
19752            return true;
19753        } else {
19754            return false;
19755        }
19756    }
19757
19758    public PackageFreezer freezePackage(String packageName, String killReason) {
19759        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19760    }
19761
19762    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19763        return new PackageFreezer(packageName, userId, killReason);
19764    }
19765
19766    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19767            String killReason) {
19768        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19769    }
19770
19771    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19772            String killReason) {
19773        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19774            return new PackageFreezer();
19775        } else {
19776            return freezePackage(packageName, userId, killReason);
19777        }
19778    }
19779
19780    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19781            String killReason) {
19782        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19783    }
19784
19785    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19786            String killReason) {
19787        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19788            return new PackageFreezer();
19789        } else {
19790            return freezePackage(packageName, userId, killReason);
19791        }
19792    }
19793
19794    /**
19795     * Class that freezes and kills the given package upon creation, and
19796     * unfreezes it upon closing. This is typically used when doing surgery on
19797     * app code/data to prevent the app from running while you're working.
19798     */
19799    private class PackageFreezer implements AutoCloseable {
19800        private final String mPackageName;
19801        private final PackageFreezer[] mChildren;
19802
19803        private final boolean mWeFroze;
19804
19805        private final AtomicBoolean mClosed = new AtomicBoolean();
19806        private final CloseGuard mCloseGuard = CloseGuard.get();
19807
19808        /**
19809         * Create and return a stub freezer that doesn't actually do anything,
19810         * typically used when someone requested
19811         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19812         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19813         */
19814        public PackageFreezer() {
19815            mPackageName = null;
19816            mChildren = null;
19817            mWeFroze = false;
19818            mCloseGuard.open("close");
19819        }
19820
19821        public PackageFreezer(String packageName, int userId, String killReason) {
19822            synchronized (mPackages) {
19823                mPackageName = packageName;
19824                mWeFroze = mFrozenPackages.add(mPackageName);
19825
19826                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19827                if (ps != null) {
19828                    killApplication(ps.name, ps.appId, userId, killReason);
19829                }
19830
19831                final PackageParser.Package p = mPackages.get(packageName);
19832                if (p != null && p.childPackages != null) {
19833                    final int N = p.childPackages.size();
19834                    mChildren = new PackageFreezer[N];
19835                    for (int i = 0; i < N; i++) {
19836                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19837                                userId, killReason);
19838                    }
19839                } else {
19840                    mChildren = null;
19841                }
19842            }
19843            mCloseGuard.open("close");
19844        }
19845
19846        @Override
19847        protected void finalize() throws Throwable {
19848            try {
19849                mCloseGuard.warnIfOpen();
19850                close();
19851            } finally {
19852                super.finalize();
19853            }
19854        }
19855
19856        @Override
19857        public void close() {
19858            mCloseGuard.close();
19859            if (mClosed.compareAndSet(false, true)) {
19860                synchronized (mPackages) {
19861                    if (mWeFroze) {
19862                        mFrozenPackages.remove(mPackageName);
19863                    }
19864
19865                    if (mChildren != null) {
19866                        for (PackageFreezer freezer : mChildren) {
19867                            freezer.close();
19868                        }
19869                    }
19870                }
19871            }
19872        }
19873    }
19874
19875    /**
19876     * Verify that given package is currently frozen.
19877     */
19878    private void checkPackageFrozen(String packageName) {
19879        synchronized (mPackages) {
19880            if (!mFrozenPackages.contains(packageName)) {
19881                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19882            }
19883        }
19884    }
19885
19886    @Override
19887    public int movePackage(final String packageName, final String volumeUuid) {
19888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19889
19890        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19891        final int moveId = mNextMoveId.getAndIncrement();
19892        mHandler.post(new Runnable() {
19893            @Override
19894            public void run() {
19895                try {
19896                    movePackageInternal(packageName, volumeUuid, moveId, user);
19897                } catch (PackageManagerException e) {
19898                    Slog.w(TAG, "Failed to move " + packageName, e);
19899                    mMoveCallbacks.notifyStatusChanged(moveId,
19900                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19901                }
19902            }
19903        });
19904        return moveId;
19905    }
19906
19907    private void movePackageInternal(final String packageName, final String volumeUuid,
19908            final int moveId, UserHandle user) throws PackageManagerException {
19909        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19910        final PackageManager pm = mContext.getPackageManager();
19911
19912        final boolean currentAsec;
19913        final String currentVolumeUuid;
19914        final File codeFile;
19915        final String installerPackageName;
19916        final String packageAbiOverride;
19917        final int appId;
19918        final String seinfo;
19919        final String label;
19920        final int targetSdkVersion;
19921        final PackageFreezer freezer;
19922        final int[] installedUserIds;
19923
19924        // reader
19925        synchronized (mPackages) {
19926            final PackageParser.Package pkg = mPackages.get(packageName);
19927            final PackageSetting ps = mSettings.mPackages.get(packageName);
19928            if (pkg == null || ps == null) {
19929                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19930            }
19931
19932            if (pkg.applicationInfo.isSystemApp()) {
19933                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19934                        "Cannot move system application");
19935            }
19936
19937            if (pkg.applicationInfo.isExternalAsec()) {
19938                currentAsec = true;
19939                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19940            } else if (pkg.applicationInfo.isForwardLocked()) {
19941                currentAsec = true;
19942                currentVolumeUuid = "forward_locked";
19943            } else {
19944                currentAsec = false;
19945                currentVolumeUuid = ps.volumeUuid;
19946
19947                final File probe = new File(pkg.codePath);
19948                final File probeOat = new File(probe, "oat");
19949                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19950                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19951                            "Move only supported for modern cluster style installs");
19952                }
19953            }
19954
19955            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19956                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19957                        "Package already moved to " + volumeUuid);
19958            }
19959            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19960                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19961                        "Device admin cannot be moved");
19962            }
19963
19964            if (mFrozenPackages.contains(packageName)) {
19965                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19966                        "Failed to move already frozen package");
19967            }
19968
19969            codeFile = new File(pkg.codePath);
19970            installerPackageName = ps.installerPackageName;
19971            packageAbiOverride = ps.cpuAbiOverrideString;
19972            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19973            seinfo = pkg.applicationInfo.seinfo;
19974            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19975            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19976            freezer = freezePackage(packageName, "movePackageInternal");
19977            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19978        }
19979
19980        final Bundle extras = new Bundle();
19981        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19982        extras.putString(Intent.EXTRA_TITLE, label);
19983        mMoveCallbacks.notifyCreated(moveId, extras);
19984
19985        int installFlags;
19986        final boolean moveCompleteApp;
19987        final File measurePath;
19988
19989        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19990            installFlags = INSTALL_INTERNAL;
19991            moveCompleteApp = !currentAsec;
19992            measurePath = Environment.getDataAppDirectory(volumeUuid);
19993        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19994            installFlags = INSTALL_EXTERNAL;
19995            moveCompleteApp = false;
19996            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19997        } else {
19998            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19999            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20000                    || !volume.isMountedWritable()) {
20001                freezer.close();
20002                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20003                        "Move location not mounted private volume");
20004            }
20005
20006            Preconditions.checkState(!currentAsec);
20007
20008            installFlags = INSTALL_INTERNAL;
20009            moveCompleteApp = true;
20010            measurePath = Environment.getDataAppDirectory(volumeUuid);
20011        }
20012
20013        final PackageStats stats = new PackageStats(null, -1);
20014        synchronized (mInstaller) {
20015            for (int userId : installedUserIds) {
20016                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20017                    freezer.close();
20018                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20019                            "Failed to measure package size");
20020                }
20021            }
20022        }
20023
20024        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20025                + stats.dataSize);
20026
20027        final long startFreeBytes = measurePath.getFreeSpace();
20028        final long sizeBytes;
20029        if (moveCompleteApp) {
20030            sizeBytes = stats.codeSize + stats.dataSize;
20031        } else {
20032            sizeBytes = stats.codeSize;
20033        }
20034
20035        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20036            freezer.close();
20037            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20038                    "Not enough free space to move");
20039        }
20040
20041        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20042
20043        final CountDownLatch installedLatch = new CountDownLatch(1);
20044        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20045            @Override
20046            public void onUserActionRequired(Intent intent) throws RemoteException {
20047                throw new IllegalStateException();
20048            }
20049
20050            @Override
20051            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20052                    Bundle extras) throws RemoteException {
20053                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20054                        + PackageManager.installStatusToString(returnCode, msg));
20055
20056                installedLatch.countDown();
20057                freezer.close();
20058
20059                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20060                switch (status) {
20061                    case PackageInstaller.STATUS_SUCCESS:
20062                        mMoveCallbacks.notifyStatusChanged(moveId,
20063                                PackageManager.MOVE_SUCCEEDED);
20064                        break;
20065                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20066                        mMoveCallbacks.notifyStatusChanged(moveId,
20067                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20068                        break;
20069                    default:
20070                        mMoveCallbacks.notifyStatusChanged(moveId,
20071                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20072                        break;
20073                }
20074            }
20075        };
20076
20077        final MoveInfo move;
20078        if (moveCompleteApp) {
20079            // Kick off a thread to report progress estimates
20080            new Thread() {
20081                @Override
20082                public void run() {
20083                    while (true) {
20084                        try {
20085                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20086                                break;
20087                            }
20088                        } catch (InterruptedException ignored) {
20089                        }
20090
20091                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20092                        final int progress = 10 + (int) MathUtils.constrain(
20093                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20094                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20095                    }
20096                }
20097            }.start();
20098
20099            final String dataAppName = codeFile.getName();
20100            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20101                    dataAppName, appId, seinfo, targetSdkVersion);
20102        } else {
20103            move = null;
20104        }
20105
20106        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20107
20108        final Message msg = mHandler.obtainMessage(INIT_COPY);
20109        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20110        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20111                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20112                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20113        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20114        msg.obj = params;
20115
20116        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20117                System.identityHashCode(msg.obj));
20118        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20119                System.identityHashCode(msg.obj));
20120
20121        mHandler.sendMessage(msg);
20122    }
20123
20124    @Override
20125    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20126        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20127
20128        final int realMoveId = mNextMoveId.getAndIncrement();
20129        final Bundle extras = new Bundle();
20130        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20131        mMoveCallbacks.notifyCreated(realMoveId, extras);
20132
20133        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20134            @Override
20135            public void onCreated(int moveId, Bundle extras) {
20136                // Ignored
20137            }
20138
20139            @Override
20140            public void onStatusChanged(int moveId, int status, long estMillis) {
20141                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20142            }
20143        };
20144
20145        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20146        storage.setPrimaryStorageUuid(volumeUuid, callback);
20147        return realMoveId;
20148    }
20149
20150    @Override
20151    public int getMoveStatus(int moveId) {
20152        mContext.enforceCallingOrSelfPermission(
20153                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20154        return mMoveCallbacks.mLastStatus.get(moveId);
20155    }
20156
20157    @Override
20158    public void registerMoveCallback(IPackageMoveObserver callback) {
20159        mContext.enforceCallingOrSelfPermission(
20160                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20161        mMoveCallbacks.register(callback);
20162    }
20163
20164    @Override
20165    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20166        mContext.enforceCallingOrSelfPermission(
20167                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20168        mMoveCallbacks.unregister(callback);
20169    }
20170
20171    @Override
20172    public boolean setInstallLocation(int loc) {
20173        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20174                null);
20175        if (getInstallLocation() == loc) {
20176            return true;
20177        }
20178        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20179                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20180            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20181                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20182            return true;
20183        }
20184        return false;
20185   }
20186
20187    @Override
20188    public int getInstallLocation() {
20189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20190                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20191                PackageHelper.APP_INSTALL_AUTO);
20192    }
20193
20194    /** Called by UserManagerService */
20195    void cleanUpUser(UserManagerService userManager, int userHandle) {
20196        synchronized (mPackages) {
20197            mDirtyUsers.remove(userHandle);
20198            mUserNeedsBadging.delete(userHandle);
20199            mSettings.removeUserLPw(userHandle);
20200            mPendingBroadcasts.remove(userHandle);
20201            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20202            removeUnusedPackagesLPw(userManager, userHandle);
20203        }
20204    }
20205
20206    /**
20207     * We're removing userHandle and would like to remove any downloaded packages
20208     * that are no longer in use by any other user.
20209     * @param userHandle the user being removed
20210     */
20211    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20212        final boolean DEBUG_CLEAN_APKS = false;
20213        int [] users = userManager.getUserIds();
20214        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20215        while (psit.hasNext()) {
20216            PackageSetting ps = psit.next();
20217            if (ps.pkg == null) {
20218                continue;
20219            }
20220            final String packageName = ps.pkg.packageName;
20221            // Skip over if system app
20222            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20223                continue;
20224            }
20225            if (DEBUG_CLEAN_APKS) {
20226                Slog.i(TAG, "Checking package " + packageName);
20227            }
20228            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20229            if (keep) {
20230                if (DEBUG_CLEAN_APKS) {
20231                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20232                }
20233            } else {
20234                for (int i = 0; i < users.length; i++) {
20235                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20236                        keep = true;
20237                        if (DEBUG_CLEAN_APKS) {
20238                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20239                                    + users[i]);
20240                        }
20241                        break;
20242                    }
20243                }
20244            }
20245            if (!keep) {
20246                if (DEBUG_CLEAN_APKS) {
20247                    Slog.i(TAG, "  Removing package " + packageName);
20248                }
20249                mHandler.post(new Runnable() {
20250                    public void run() {
20251                        deletePackageX(packageName, userHandle, 0);
20252                    } //end run
20253                });
20254            }
20255        }
20256    }
20257
20258    /** Called by UserManagerService */
20259    void createNewUser(int userId) {
20260        synchronized (mInstallLock) {
20261            mSettings.createNewUserLI(this, mInstaller, userId);
20262        }
20263        synchronized (mPackages) {
20264            scheduleWritePackageRestrictionsLocked(userId);
20265            scheduleWritePackageListLocked(userId);
20266            applyFactoryDefaultBrowserLPw(userId);
20267            primeDomainVerificationsLPw(userId);
20268        }
20269    }
20270
20271    void onBeforeUserStartUninitialized(final int userId) {
20272        synchronized (mPackages) {
20273            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20274                return;
20275            }
20276        }
20277        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20278        // If permission review for legacy apps is required, we represent
20279        // dagerous permissions for such apps as always granted runtime
20280        // permissions to keep per user flag state whether review is needed.
20281        // Hence, if a new user is added we have to propagate dangerous
20282        // permission grants for these legacy apps.
20283        if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20284            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20285                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20286        }
20287    }
20288
20289    @Override
20290    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20291        mContext.enforceCallingOrSelfPermission(
20292                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20293                "Only package verification agents can read the verifier device identity");
20294
20295        synchronized (mPackages) {
20296            return mSettings.getVerifierDeviceIdentityLPw();
20297        }
20298    }
20299
20300    @Override
20301    public void setPermissionEnforced(String permission, boolean enforced) {
20302        // TODO: Now that we no longer change GID for storage, this should to away.
20303        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20304                "setPermissionEnforced");
20305        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20306            synchronized (mPackages) {
20307                if (mSettings.mReadExternalStorageEnforced == null
20308                        || mSettings.mReadExternalStorageEnforced != enforced) {
20309                    mSettings.mReadExternalStorageEnforced = enforced;
20310                    mSettings.writeLPr();
20311                }
20312            }
20313            // kill any non-foreground processes so we restart them and
20314            // grant/revoke the GID.
20315            final IActivityManager am = ActivityManagerNative.getDefault();
20316            if (am != null) {
20317                final long token = Binder.clearCallingIdentity();
20318                try {
20319                    am.killProcessesBelowForeground("setPermissionEnforcement");
20320                } catch (RemoteException e) {
20321                } finally {
20322                    Binder.restoreCallingIdentity(token);
20323                }
20324            }
20325        } else {
20326            throw new IllegalArgumentException("No selective enforcement for " + permission);
20327        }
20328    }
20329
20330    @Override
20331    @Deprecated
20332    public boolean isPermissionEnforced(String permission) {
20333        return true;
20334    }
20335
20336    @Override
20337    public boolean isStorageLow() {
20338        final long token = Binder.clearCallingIdentity();
20339        try {
20340            final DeviceStorageMonitorInternal
20341                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20342            if (dsm != null) {
20343                return dsm.isMemoryLow();
20344            } else {
20345                return false;
20346            }
20347        } finally {
20348            Binder.restoreCallingIdentity(token);
20349        }
20350    }
20351
20352    @Override
20353    public IPackageInstaller getPackageInstaller() {
20354        return mInstallerService;
20355    }
20356
20357    private boolean userNeedsBadging(int userId) {
20358        int index = mUserNeedsBadging.indexOfKey(userId);
20359        if (index < 0) {
20360            final UserInfo userInfo;
20361            final long token = Binder.clearCallingIdentity();
20362            try {
20363                userInfo = sUserManager.getUserInfo(userId);
20364            } finally {
20365                Binder.restoreCallingIdentity(token);
20366            }
20367            final boolean b;
20368            if (userInfo != null && userInfo.isManagedProfile()) {
20369                b = true;
20370            } else {
20371                b = false;
20372            }
20373            mUserNeedsBadging.put(userId, b);
20374            return b;
20375        }
20376        return mUserNeedsBadging.valueAt(index);
20377    }
20378
20379    @Override
20380    public KeySet getKeySetByAlias(String packageName, String alias) {
20381        if (packageName == null || alias == null) {
20382            return null;
20383        }
20384        synchronized(mPackages) {
20385            final PackageParser.Package pkg = mPackages.get(packageName);
20386            if (pkg == null) {
20387                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20388                throw new IllegalArgumentException("Unknown package: " + packageName);
20389            }
20390            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20391            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20392        }
20393    }
20394
20395    @Override
20396    public KeySet getSigningKeySet(String packageName) {
20397        if (packageName == null) {
20398            return null;
20399        }
20400        synchronized(mPackages) {
20401            final PackageParser.Package pkg = mPackages.get(packageName);
20402            if (pkg == null) {
20403                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20404                throw new IllegalArgumentException("Unknown package: " + packageName);
20405            }
20406            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20407                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20408                throw new SecurityException("May not access signing KeySet of other apps.");
20409            }
20410            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20411            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20412        }
20413    }
20414
20415    @Override
20416    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20417        if (packageName == null || ks == null) {
20418            return false;
20419        }
20420        synchronized(mPackages) {
20421            final PackageParser.Package pkg = mPackages.get(packageName);
20422            if (pkg == null) {
20423                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20424                throw new IllegalArgumentException("Unknown package: " + packageName);
20425            }
20426            IBinder ksh = ks.getToken();
20427            if (ksh instanceof KeySetHandle) {
20428                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20429                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20430            }
20431            return false;
20432        }
20433    }
20434
20435    @Override
20436    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20437        if (packageName == null || ks == null) {
20438            return false;
20439        }
20440        synchronized(mPackages) {
20441            final PackageParser.Package pkg = mPackages.get(packageName);
20442            if (pkg == null) {
20443                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20444                throw new IllegalArgumentException("Unknown package: " + packageName);
20445            }
20446            IBinder ksh = ks.getToken();
20447            if (ksh instanceof KeySetHandle) {
20448                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20449                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20450            }
20451            return false;
20452        }
20453    }
20454
20455    private void deletePackageIfUnusedLPr(final String packageName) {
20456        PackageSetting ps = mSettings.mPackages.get(packageName);
20457        if (ps == null) {
20458            return;
20459        }
20460        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20461            // TODO Implement atomic delete if package is unused
20462            // It is currently possible that the package will be deleted even if it is installed
20463            // after this method returns.
20464            mHandler.post(new Runnable() {
20465                public void run() {
20466                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20467                }
20468            });
20469        }
20470    }
20471
20472    /**
20473     * Check and throw if the given before/after packages would be considered a
20474     * downgrade.
20475     */
20476    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20477            throws PackageManagerException {
20478        if (after.versionCode < before.mVersionCode) {
20479            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20480                    "Update version code " + after.versionCode + " is older than current "
20481                    + before.mVersionCode);
20482        } else if (after.versionCode == before.mVersionCode) {
20483            if (after.baseRevisionCode < before.baseRevisionCode) {
20484                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20485                        "Update base revision code " + after.baseRevisionCode
20486                        + " is older than current " + before.baseRevisionCode);
20487            }
20488
20489            if (!ArrayUtils.isEmpty(after.splitNames)) {
20490                for (int i = 0; i < after.splitNames.length; i++) {
20491                    final String splitName = after.splitNames[i];
20492                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20493                    if (j != -1) {
20494                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20495                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20496                                    "Update split " + splitName + " revision code "
20497                                    + after.splitRevisionCodes[i] + " is older than current "
20498                                    + before.splitRevisionCodes[j]);
20499                        }
20500                    }
20501                }
20502            }
20503        }
20504    }
20505
20506    private static class MoveCallbacks extends Handler {
20507        private static final int MSG_CREATED = 1;
20508        private static final int MSG_STATUS_CHANGED = 2;
20509
20510        private final RemoteCallbackList<IPackageMoveObserver>
20511                mCallbacks = new RemoteCallbackList<>();
20512
20513        private final SparseIntArray mLastStatus = new SparseIntArray();
20514
20515        public MoveCallbacks(Looper looper) {
20516            super(looper);
20517        }
20518
20519        public void register(IPackageMoveObserver callback) {
20520            mCallbacks.register(callback);
20521        }
20522
20523        public void unregister(IPackageMoveObserver callback) {
20524            mCallbacks.unregister(callback);
20525        }
20526
20527        @Override
20528        public void handleMessage(Message msg) {
20529            final SomeArgs args = (SomeArgs) msg.obj;
20530            final int n = mCallbacks.beginBroadcast();
20531            for (int i = 0; i < n; i++) {
20532                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20533                try {
20534                    invokeCallback(callback, msg.what, args);
20535                } catch (RemoteException ignored) {
20536                }
20537            }
20538            mCallbacks.finishBroadcast();
20539            args.recycle();
20540        }
20541
20542        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20543                throws RemoteException {
20544            switch (what) {
20545                case MSG_CREATED: {
20546                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20547                    break;
20548                }
20549                case MSG_STATUS_CHANGED: {
20550                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20551                    break;
20552                }
20553            }
20554        }
20555
20556        private void notifyCreated(int moveId, Bundle extras) {
20557            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20558
20559            final SomeArgs args = SomeArgs.obtain();
20560            args.argi1 = moveId;
20561            args.arg2 = extras;
20562            obtainMessage(MSG_CREATED, args).sendToTarget();
20563        }
20564
20565        private void notifyStatusChanged(int moveId, int status) {
20566            notifyStatusChanged(moveId, status, -1);
20567        }
20568
20569        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20570            Slog.v(TAG, "Move " + moveId + " status " + status);
20571
20572            final SomeArgs args = SomeArgs.obtain();
20573            args.argi1 = moveId;
20574            args.argi2 = status;
20575            args.arg3 = estMillis;
20576            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20577
20578            synchronized (mLastStatus) {
20579                mLastStatus.put(moveId, status);
20580            }
20581        }
20582    }
20583
20584    private final static class OnPermissionChangeListeners extends Handler {
20585        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20586
20587        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20588                new RemoteCallbackList<>();
20589
20590        public OnPermissionChangeListeners(Looper looper) {
20591            super(looper);
20592        }
20593
20594        @Override
20595        public void handleMessage(Message msg) {
20596            switch (msg.what) {
20597                case MSG_ON_PERMISSIONS_CHANGED: {
20598                    final int uid = msg.arg1;
20599                    handleOnPermissionsChanged(uid);
20600                } break;
20601            }
20602        }
20603
20604        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20605            mPermissionListeners.register(listener);
20606
20607        }
20608
20609        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20610            mPermissionListeners.unregister(listener);
20611        }
20612
20613        public void onPermissionsChanged(int uid) {
20614            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20615                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20616            }
20617        }
20618
20619        private void handleOnPermissionsChanged(int uid) {
20620            final int count = mPermissionListeners.beginBroadcast();
20621            try {
20622                for (int i = 0; i < count; i++) {
20623                    IOnPermissionsChangeListener callback = mPermissionListeners
20624                            .getBroadcastItem(i);
20625                    try {
20626                        callback.onPermissionsChanged(uid);
20627                    } catch (RemoteException e) {
20628                        Log.e(TAG, "Permission listener is dead", e);
20629                    }
20630                }
20631            } finally {
20632                mPermissionListeners.finishBroadcast();
20633            }
20634        }
20635    }
20636
20637    private class PackageManagerInternalImpl extends PackageManagerInternal {
20638        @Override
20639        public void setLocationPackagesProvider(PackagesProvider provider) {
20640            synchronized (mPackages) {
20641                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20642            }
20643        }
20644
20645        @Override
20646        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20647            synchronized (mPackages) {
20648                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20649            }
20650        }
20651
20652        @Override
20653        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20654            synchronized (mPackages) {
20655                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20656            }
20657        }
20658
20659        @Override
20660        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20661            synchronized (mPackages) {
20662                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20663            }
20664        }
20665
20666        @Override
20667        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20668            synchronized (mPackages) {
20669                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20670            }
20671        }
20672
20673        @Override
20674        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20675            synchronized (mPackages) {
20676                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20677            }
20678        }
20679
20680        @Override
20681        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20682            synchronized (mPackages) {
20683                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20684                        packageName, userId);
20685            }
20686        }
20687
20688        @Override
20689        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20690            synchronized (mPackages) {
20691                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20692                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20693                        packageName, userId);
20694            }
20695        }
20696
20697        @Override
20698        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20699            synchronized (mPackages) {
20700                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20701                        packageName, userId);
20702            }
20703        }
20704
20705        @Override
20706        public void setKeepUninstalledPackages(final List<String> packageList) {
20707            Preconditions.checkNotNull(packageList);
20708            List<String> removedFromList = null;
20709            synchronized (mPackages) {
20710                if (mKeepUninstalledPackages != null) {
20711                    final int packagesCount = mKeepUninstalledPackages.size();
20712                    for (int i = 0; i < packagesCount; i++) {
20713                        String oldPackage = mKeepUninstalledPackages.get(i);
20714                        if (packageList != null && packageList.contains(oldPackage)) {
20715                            continue;
20716                        }
20717                        if (removedFromList == null) {
20718                            removedFromList = new ArrayList<>();
20719                        }
20720                        removedFromList.add(oldPackage);
20721                    }
20722                }
20723                mKeepUninstalledPackages = new ArrayList<>(packageList);
20724                if (removedFromList != null) {
20725                    final int removedCount = removedFromList.size();
20726                    for (int i = 0; i < removedCount; i++) {
20727                        deletePackageIfUnusedLPr(removedFromList.get(i));
20728                    }
20729                }
20730            }
20731        }
20732
20733        @Override
20734        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20735            synchronized (mPackages) {
20736                // If we do not support permission review, done.
20737                if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
20738                    return false;
20739                }
20740
20741                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20742                if (packageSetting == null) {
20743                    return false;
20744                }
20745
20746                // Permission review applies only to apps not supporting the new permission model.
20747                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20748                    return false;
20749                }
20750
20751                // Legacy apps have the permission and get user consent on launch.
20752                PermissionsState permissionsState = packageSetting.getPermissionsState();
20753                return permissionsState.isPermissionReviewRequired(userId);
20754            }
20755        }
20756
20757        @Override
20758        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20759            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20760        }
20761
20762        @Override
20763        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20764                int userId) {
20765            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20766        }
20767
20768        @Override
20769        public void setDeviceAndProfileOwnerPackages(
20770                int deviceOwnerUserId, String deviceOwnerPackage,
20771                SparseArray<String> profileOwnerPackages) {
20772            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20773                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20774        }
20775
20776        @Override
20777        public boolean canPackageBeWiped(int userId, String packageName) {
20778            return mProtectedPackages.canPackageBeWiped(userId,
20779                    packageName);
20780        }
20781    }
20782
20783    @Override
20784    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20785        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20786        synchronized (mPackages) {
20787            final long identity = Binder.clearCallingIdentity();
20788            try {
20789                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20790                        packageNames, userId);
20791            } finally {
20792                Binder.restoreCallingIdentity(identity);
20793            }
20794        }
20795    }
20796
20797    private static void enforceSystemOrPhoneCaller(String tag) {
20798        int callingUid = Binder.getCallingUid();
20799        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20800            throw new SecurityException(
20801                    "Cannot call " + tag + " from UID " + callingUid);
20802        }
20803    }
20804
20805    boolean isHistoricalPackageUsageAvailable() {
20806        return mPackageUsage.isHistoricalPackageUsageAvailable();
20807    }
20808
20809    /**
20810     * Return a <b>copy</b> of the collection of packages known to the package manager.
20811     * @return A copy of the values of mPackages.
20812     */
20813    Collection<PackageParser.Package> getPackages() {
20814        synchronized (mPackages) {
20815            return new ArrayList<>(mPackages.values());
20816        }
20817    }
20818
20819    /**
20820     * Logs process start information (including base APK hash) to the security log.
20821     * @hide
20822     */
20823    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20824            String apkFile, int pid) {
20825        if (!SecurityLog.isLoggingEnabled()) {
20826            return;
20827        }
20828        Bundle data = new Bundle();
20829        data.putLong("startTimestamp", System.currentTimeMillis());
20830        data.putString("processName", processName);
20831        data.putInt("uid", uid);
20832        data.putString("seinfo", seinfo);
20833        data.putString("apkFile", apkFile);
20834        data.putInt("pid", pid);
20835        Message msg = mProcessLoggingHandler.obtainMessage(
20836                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20837        msg.setData(data);
20838        mProcessLoggingHandler.sendMessage(msg);
20839    }
20840
20841    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20842        return mCompilerStats.getPackageStats(pkgName);
20843    }
20844
20845    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20846        return getOrCreateCompilerPackageStats(pkg.packageName);
20847    }
20848
20849    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20850        return mCompilerStats.getOrCreatePackageStats(pkgName);
20851    }
20852
20853    public void deleteCompilerPackageStats(String pkgName) {
20854        mCompilerStats.deletePackageStats(pkgName);
20855    }
20856}
20857