PackageManagerService.java revision a5111bfda47f0d6c044c2bdbe6ae8a1c099849d7
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.EphemeralDigest;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
369
370    private static final int RADIO_UID = Process.PHONE_UID;
371    private static final int LOG_UID = Process.LOG_UID;
372    private static final int NFC_UID = Process.NFC_UID;
373    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
374    private static final int SHELL_UID = Process.SHELL_UID;
375
376    // Cap the size of permission trees that 3rd party apps can define
377    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
378
379    // Suffix used during package installation when copying/moving
380    // package apks to install directory.
381    private static final String INSTALL_PACKAGE_SUFFIX = "-";
382
383    static final int SCAN_NO_DEX = 1<<1;
384    static final int SCAN_FORCE_DEX = 1<<2;
385    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
386    static final int SCAN_NEW_INSTALL = 1<<4;
387    static final int SCAN_NO_PATHS = 1<<5;
388    static final int SCAN_UPDATE_TIME = 1<<6;
389    static final int SCAN_DEFER_DEX = 1<<7;
390    static final int SCAN_BOOTING = 1<<8;
391    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
392    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
393    static final int SCAN_REPLACING = 1<<11;
394    static final int SCAN_REQUIRE_KNOWN = 1<<12;
395    static final int SCAN_MOVE = 1<<13;
396    static final int SCAN_INITIAL = 1<<14;
397    static final int SCAN_CHECK_ONLY = 1<<15;
398    static final int SCAN_DONT_KILL_APP = 1<<17;
399    static final int SCAN_IGNORE_FROZEN = 1<<18;
400
401    static final int REMOVE_CHATTY = 1<<16;
402
403    private static final int[] EMPTY_INT_ARRAY = new int[0];
404
405    /**
406     * Timeout (in milliseconds) after which the watchdog should declare that
407     * our handler thread is wedged.  The usual default for such things is one
408     * minute but we sometimes do very lengthy I/O operations on this thread,
409     * such as installing multi-gigabyte applications, so ours needs to be longer.
410     */
411    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
412
413    /**
414     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
415     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
416     * settings entry if available, otherwise we use the hardcoded default.  If it's been
417     * more than this long since the last fstrim, we force one during the boot sequence.
418     *
419     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
420     * one gets run at the next available charging+idle time.  This final mandatory
421     * no-fstrim check kicks in only of the other scheduling criteria is never met.
422     */
423    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
424
425    /**
426     * Whether verification is enabled by default.
427     */
428    private static final boolean DEFAULT_VERIFY_ENABLE = true;
429
430    /**
431     * The default maximum time to wait for the verification agent to return in
432     * milliseconds.
433     */
434    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
435
436    /**
437     * The default response for package verification timeout.
438     *
439     * This can be either PackageManager.VERIFICATION_ALLOW or
440     * PackageManager.VERIFICATION_REJECT.
441     */
442    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
443
444    static final String PLATFORM_PACKAGE_NAME = "android";
445
446    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
447
448    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
449            DEFAULT_CONTAINER_PACKAGE,
450            "com.android.defcontainer.DefaultContainerService");
451
452    private static final String KILL_APP_REASON_GIDS_CHANGED =
453            "permission grant or revoke changed gids";
454
455    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
456            "permissions revoked";
457
458    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    final ProtectedPackages mProtectedPackages;
626
627    boolean mFirstBoot;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128    private final CompilerStats mCompilerStats = new CompilerStats();
1129
1130    class PackageHandler extends Handler {
1131        private boolean mBound = false;
1132        final ArrayList<HandlerParams> mPendingInstalls =
1133            new ArrayList<HandlerParams>();
1134
1135        private boolean connectToService() {
1136            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1137                    " DefaultContainerService");
1138            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1140            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1141                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1142                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                mBound = true;
1144                return true;
1145            }
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147            return false;
1148        }
1149
1150        private void disconnectService() {
1151            mContainerService = null;
1152            mBound = false;
1153            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1154            mContext.unbindService(mDefContainerConn);
1155            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1156        }
1157
1158        PackageHandler(Looper looper) {
1159            super(looper);
1160        }
1161
1162        public void handleMessage(Message msg) {
1163            try {
1164                doHandleMessage(msg);
1165            } finally {
1166                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1167            }
1168        }
1169
1170        void doHandleMessage(Message msg) {
1171            switch (msg.what) {
1172                case INIT_COPY: {
1173                    HandlerParams params = (HandlerParams) msg.obj;
1174                    int idx = mPendingInstalls.size();
1175                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1176                    // If a bind was already initiated we dont really
1177                    // need to do anything. The pending install
1178                    // will be processed later on.
1179                    if (!mBound) {
1180                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1181                                System.identityHashCode(mHandler));
1182                        // If this is the only one pending we might
1183                        // have to bind to the service again.
1184                        if (!connectToService()) {
1185                            Slog.e(TAG, "Failed to bind to media container service");
1186                            params.serviceError();
1187                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1188                                    System.identityHashCode(mHandler));
1189                            if (params.traceMethod != null) {
1190                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1191                                        params.traceCookie);
1192                            }
1193                            return;
1194                        } else {
1195                            // Once we bind to the service, the first
1196                            // pending request will be processed.
1197                            mPendingInstalls.add(idx, params);
1198                        }
1199                    } else {
1200                        mPendingInstalls.add(idx, params);
1201                        // Already bound to the service. Just make
1202                        // sure we trigger off processing the first request.
1203                        if (idx == 0) {
1204                            mHandler.sendEmptyMessage(MCS_BOUND);
1205                        }
1206                    }
1207                    break;
1208                }
1209                case MCS_BOUND: {
1210                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1211                    if (msg.obj != null) {
1212                        mContainerService = (IMediaContainerService) msg.obj;
1213                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1214                                System.identityHashCode(mHandler));
1215                    }
1216                    if (mContainerService == null) {
1217                        if (!mBound) {
1218                            // Something seriously wrong since we are not bound and we are not
1219                            // waiting for connection. Bail out.
1220                            Slog.e(TAG, "Cannot bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1225                                        System.identityHashCode(params));
1226                                if (params.traceMethod != null) {
1227                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1228                                            params.traceMethod, params.traceCookie);
1229                                }
1230                                return;
1231                            }
1232                            mPendingInstalls.clear();
1233                        } else {
1234                            Slog.w(TAG, "Waiting to connect to media container service");
1235                        }
1236                    } else if (mPendingInstalls.size() > 0) {
1237                        HandlerParams params = mPendingInstalls.get(0);
1238                        if (params != null) {
1239                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1240                                    System.identityHashCode(params));
1241                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1242                            if (params.startCopy()) {
1243                                // We are done...  look for more work or to
1244                                // go idle.
1245                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1246                                        "Checking for more work or unbind...");
1247                                // Delete pending install
1248                                if (mPendingInstalls.size() > 0) {
1249                                    mPendingInstalls.remove(0);
1250                                }
1251                                if (mPendingInstalls.size() == 0) {
1252                                    if (mBound) {
1253                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1254                                                "Posting delayed MCS_UNBIND");
1255                                        removeMessages(MCS_UNBIND);
1256                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1257                                        // Unbind after a little delay, to avoid
1258                                        // continual thrashing.
1259                                        sendMessageDelayed(ubmsg, 10000);
1260                                    }
1261                                } else {
1262                                    // There are more pending requests in queue.
1263                                    // Just post MCS_BOUND message to trigger processing
1264                                    // of next pending install.
1265                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1266                                            "Posting MCS_BOUND for next work");
1267                                    mHandler.sendEmptyMessage(MCS_BOUND);
1268                                }
1269                            }
1270                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1271                        }
1272                    } else {
1273                        // Should never happen ideally.
1274                        Slog.w(TAG, "Empty queue");
1275                    }
1276                    break;
1277                }
1278                case MCS_RECONNECT: {
1279                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1280                    if (mPendingInstalls.size() > 0) {
1281                        if (mBound) {
1282                            disconnectService();
1283                        }
1284                        if (!connectToService()) {
1285                            Slog.e(TAG, "Failed to bind to media container service");
1286                            for (HandlerParams params : mPendingInstalls) {
1287                                // Indicate service bind error
1288                                params.serviceError();
1289                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                                        System.identityHashCode(params));
1291                            }
1292                            mPendingInstalls.clear();
1293                        }
1294                    }
1295                    break;
1296                }
1297                case MCS_UNBIND: {
1298                    // If there is no actual work left, then time to unbind.
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1300
1301                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1302                        if (mBound) {
1303                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1304
1305                            disconnectService();
1306                        }
1307                    } else if (mPendingInstalls.size() > 0) {
1308                        // There are more pending requests in queue.
1309                        // Just post MCS_BOUND message to trigger processing
1310                        // of next pending install.
1311                        mHandler.sendEmptyMessage(MCS_BOUND);
1312                    }
1313
1314                    break;
1315                }
1316                case MCS_GIVE_UP: {
1317                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1318                    HandlerParams params = mPendingInstalls.remove(0);
1319                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                            System.identityHashCode(params));
1321                    break;
1322                }
1323                case SEND_PENDING_BROADCAST: {
1324                    String packages[];
1325                    ArrayList<String> components[];
1326                    int size = 0;
1327                    int uids[];
1328                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1329                    synchronized (mPackages) {
1330                        if (mPendingBroadcasts == null) {
1331                            return;
1332                        }
1333                        size = mPendingBroadcasts.size();
1334                        if (size <= 0) {
1335                            // Nothing to be done. Just return
1336                            return;
1337                        }
1338                        packages = new String[size];
1339                        components = new ArrayList[size];
1340                        uids = new int[size];
1341                        int i = 0;  // filling out the above arrays
1342
1343                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1344                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1345                            Iterator<Map.Entry<String, ArrayList<String>>> it
1346                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1347                                            .entrySet().iterator();
1348                            while (it.hasNext() && i < size) {
1349                                Map.Entry<String, ArrayList<String>> ent = it.next();
1350                                packages[i] = ent.getKey();
1351                                components[i] = ent.getValue();
1352                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1353                                uids[i] = (ps != null)
1354                                        ? UserHandle.getUid(packageUserId, ps.appId)
1355                                        : -1;
1356                                i++;
1357                            }
1358                        }
1359                        size = i;
1360                        mPendingBroadcasts.clear();
1361                    }
1362                    // Send broadcasts
1363                    for (int i = 0; i < size; i++) {
1364                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1365                    }
1366                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1367                    break;
1368                }
1369                case START_CLEANING_PACKAGE: {
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1371                    final String packageName = (String)msg.obj;
1372                    final int userId = msg.arg1;
1373                    final boolean andCode = msg.arg2 != 0;
1374                    synchronized (mPackages) {
1375                        if (userId == UserHandle.USER_ALL) {
1376                            int[] users = sUserManager.getUserIds();
1377                            for (int user : users) {
1378                                mSettings.addPackageToCleanLPw(
1379                                        new PackageCleanItem(user, packageName, andCode));
1380                            }
1381                        } else {
1382                            mSettings.addPackageToCleanLPw(
1383                                    new PackageCleanItem(userId, packageName, andCode));
1384                        }
1385                    }
1386                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                    startCleaningPackages();
1388                } break;
1389                case POST_INSTALL: {
1390                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1391
1392                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1393                    final boolean didRestore = (msg.arg2 != 0);
1394                    mRunningInstalls.delete(msg.arg1);
1395
1396                    if (data != null) {
1397                        InstallArgs args = data.args;
1398                        PackageInstalledInfo parentRes = data.res;
1399
1400                        final boolean grantPermissions = (args.installFlags
1401                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1402                        final boolean killApp = (args.installFlags
1403                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1404                        final String[] grantedPermissions = args.installGrantPermissions;
1405
1406                        // Handle the parent package
1407                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1408                                grantedPermissions, didRestore, args.installerPackageName,
1409                                args.observer);
1410
1411                        // Handle the child packages
1412                        final int childCount = (parentRes.addedChildPackages != null)
1413                                ? parentRes.addedChildPackages.size() : 0;
1414                        for (int i = 0; i < childCount; i++) {
1415                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1416                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1417                                    grantedPermissions, false, args.installerPackageName,
1418                                    args.observer);
1419                        }
1420
1421                        // Log tracing if needed
1422                        if (args.traceMethod != null) {
1423                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1424                                    args.traceCookie);
1425                        }
1426                    } else {
1427                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1428                    }
1429
1430                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1431                } break;
1432                case UPDATED_MEDIA_STATUS: {
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1434                    boolean reportStatus = msg.arg1 == 1;
1435                    boolean doGc = msg.arg2 == 1;
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1437                    if (doGc) {
1438                        // Force a gc to clear up stale containers.
1439                        Runtime.getRuntime().gc();
1440                    }
1441                    if (msg.obj != null) {
1442                        @SuppressWarnings("unchecked")
1443                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1444                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1445                        // Unload containers
1446                        unloadAllContainers(args);
1447                    }
1448                    if (reportStatus) {
1449                        try {
1450                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1451                            PackageHelper.getMountService().finishMediaUpdate();
1452                        } catch (RemoteException e) {
1453                            Log.e(TAG, "MountService not running?");
1454                        }
1455                    }
1456                } break;
1457                case WRITE_SETTINGS: {
1458                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1459                    synchronized (mPackages) {
1460                        removeMessages(WRITE_SETTINGS);
1461                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1462                        mSettings.writeLPr();
1463                        mDirtyUsers.clear();
1464                    }
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1466                } break;
1467                case WRITE_PACKAGE_RESTRICTIONS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        for (int userId : mDirtyUsers) {
1472                            mSettings.writePackageRestrictionsLPr(userId);
1473                        }
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case WRITE_PACKAGE_LIST: {
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480                    synchronized (mPackages) {
1481                        removeMessages(WRITE_PACKAGE_LIST);
1482                        mSettings.writePackageListLPr(msg.arg1);
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case CHECK_PENDING_VERIFICATION: {
1487                    final int verificationId = msg.arg1;
1488                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1489
1490                    if ((state != null) && !state.timeoutExtended()) {
1491                        final InstallArgs args = state.getInstallArgs();
1492                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1493
1494                        Slog.i(TAG, "Verification timed out for " + originUri);
1495                        mPendingVerification.remove(verificationId);
1496
1497                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1498
1499                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1500                            Slog.i(TAG, "Continuing with installation of " + originUri);
1501                            state.setVerifierResponse(Binder.getCallingUid(),
1502                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1503                            broadcastPackageVerified(verificationId, originUri,
1504                                    PackageManager.VERIFICATION_ALLOW,
1505                                    state.getInstallArgs().getUser());
1506                            try {
1507                                ret = args.copyApk(mContainerService, true);
1508                            } catch (RemoteException e) {
1509                                Slog.e(TAG, "Could not contact the ContainerService");
1510                            }
1511                        } else {
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_REJECT,
1514                                    state.getInstallArgs().getUser());
1515                        }
1516
1517                        Trace.asyncTraceEnd(
1518                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1519
1520                        processPendingInstall(args, ret);
1521                        mHandler.sendEmptyMessage(MCS_UNBIND);
1522                    }
1523                    break;
1524                }
1525                case PACKAGE_VERIFIED: {
1526                    final int verificationId = msg.arg1;
1527
1528                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1529                    if (state == null) {
1530                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1531                        break;
1532                    }
1533
1534                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1535
1536                    state.setVerifierResponse(response.callerUid, response.code);
1537
1538                    if (state.isVerificationComplete()) {
1539                        mPendingVerification.remove(verificationId);
1540
1541                        final InstallArgs args = state.getInstallArgs();
1542                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1543
1544                        int ret;
1545                        if (state.isInstallAllowed()) {
1546                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1547                            broadcastPackageVerified(verificationId, originUri,
1548                                    response.code, state.getInstallArgs().getUser());
1549                            try {
1550                                ret = args.copyApk(mContainerService, true);
1551                            } catch (RemoteException e) {
1552                                Slog.e(TAG, "Could not contact the ContainerService");
1553                            }
1554                        } else {
1555                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1556                        }
1557
1558                        Trace.asyncTraceEnd(
1559                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1560
1561                        processPendingInstall(args, ret);
1562                        mHandler.sendEmptyMessage(MCS_UNBIND);
1563                    }
1564
1565                    break;
1566                }
1567                case START_INTENT_FILTER_VERIFICATIONS: {
1568                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1569                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1570                            params.replacing, params.pkg);
1571                    break;
1572                }
1573                case INTENT_FILTER_VERIFIED: {
1574                    final int verificationId = msg.arg1;
1575
1576                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1577                            verificationId);
1578                    if (state == null) {
1579                        Slog.w(TAG, "Invalid IntentFilter verification token "
1580                                + verificationId + " received");
1581                        break;
1582                    }
1583
1584                    final int userId = state.getUserId();
1585
1586                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1587                            "Processing IntentFilter verification with token:"
1588                            + verificationId + " and userId:" + userId);
1589
1590                    final IntentFilterVerificationResponse response =
1591                            (IntentFilterVerificationResponse) msg.obj;
1592
1593                    state.setVerifierResponse(response.callerUid, response.code);
1594
1595                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1596                            "IntentFilter verification with token:" + verificationId
1597                            + " and userId:" + userId
1598                            + " is settings verifier response with response code:"
1599                            + response.code);
1600
1601                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1602                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1603                                + response.getFailedDomainsString());
1604                    }
1605
1606                    if (state.isVerificationComplete()) {
1607                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1608                    } else {
1609                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                                "IntentFilter verification with token:" + verificationId
1611                                + " was not said to be complete");
1612                    }
1613
1614                    break;
1615                }
1616            }
1617        }
1618    }
1619
1620    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1621            boolean killApp, String[] grantedPermissions,
1622            boolean launchedForRestore, String installerPackage,
1623            IPackageInstallObserver2 installObserver) {
1624        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1625            // Send the removed broadcasts
1626            if (res.removedInfo != null) {
1627                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1628            }
1629
1630            // Now that we successfully installed the package, grant runtime
1631            // permissions if requested before broadcasting the install.
1632            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1633                    >= Build.VERSION_CODES.M) {
1634                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1635            }
1636
1637            final boolean update = res.removedInfo != null
1638                    && res.removedInfo.removedPackage != null;
1639
1640            // If this is the first time we have child packages for a disabled privileged
1641            // app that had no children, we grant requested runtime permissions to the new
1642            // children if the parent on the system image had them already granted.
1643            if (res.pkg.parentPackage != null) {
1644                synchronized (mPackages) {
1645                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1646                }
1647            }
1648
1649            synchronized (mPackages) {
1650                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1651            }
1652
1653            final String packageName = res.pkg.applicationInfo.packageName;
1654            Bundle extras = new Bundle(1);
1655            extras.putInt(Intent.EXTRA_UID, res.uid);
1656
1657            // Determine the set of users who are adding this package for
1658            // the first time vs. those who are seeing an update.
1659            int[] firstUsers = EMPTY_INT_ARRAY;
1660            int[] updateUsers = EMPTY_INT_ARRAY;
1661            if (res.origUsers == null || res.origUsers.length == 0) {
1662                firstUsers = res.newUsers;
1663            } else {
1664                for (int newUser : res.newUsers) {
1665                    boolean isNew = true;
1666                    for (int origUser : res.origUsers) {
1667                        if (origUser == newUser) {
1668                            isNew = false;
1669                            break;
1670                        }
1671                    }
1672                    if (isNew) {
1673                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1674                    } else {
1675                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1676                    }
1677                }
1678            }
1679
1680            // Send installed broadcasts if the install/update is not ephemeral
1681            if (!isEphemeral(res.pkg)) {
1682                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1683
1684                // Send added for users that see the package for the first time
1685                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1686                        extras, 0 /*flags*/, null /*targetPackage*/,
1687                        null /*finishedReceiver*/, firstUsers);
1688
1689                // Send added for users that don't see the package for the first time
1690                if (update) {
1691                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1692                }
1693                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1694                        extras, 0 /*flags*/, null /*targetPackage*/,
1695                        null /*finishedReceiver*/, updateUsers);
1696
1697                // Send replaced for users that don't see the package for the first time
1698                if (update) {
1699                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1700                            packageName, extras, 0 /*flags*/,
1701                            null /*targetPackage*/, null /*finishedReceiver*/,
1702                            updateUsers);
1703                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1704                            null /*package*/, null /*extras*/, 0 /*flags*/,
1705                            packageName /*targetPackage*/,
1706                            null /*finishedReceiver*/, updateUsers);
1707                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1708                    // First-install and we did a restore, so we're responsible for the
1709                    // first-launch broadcast.
1710                    if (DEBUG_BACKUP) {
1711                        Slog.i(TAG, "Post-restore of " + packageName
1712                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1713                    }
1714                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1715                }
1716
1717                // Send broadcast package appeared if forward locked/external for all users
1718                // treat asec-hosted packages like removable media on upgrade
1719                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1720                    if (DEBUG_INSTALL) {
1721                        Slog.i(TAG, "upgrading pkg " + res.pkg
1722                                + " is ASEC-hosted -> AVAILABLE");
1723                    }
1724                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1725                    ArrayList<String> pkgList = new ArrayList<>(1);
1726                    pkgList.add(packageName);
1727                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1728                }
1729            }
1730
1731            // Work that needs to happen on first install within each user
1732            if (firstUsers != null && firstUsers.length > 0) {
1733                synchronized (mPackages) {
1734                    for (int userId : firstUsers) {
1735                        // If this app is a browser and it's newly-installed for some
1736                        // users, clear any default-browser state in those users. The
1737                        // app's nature doesn't depend on the user, so we can just check
1738                        // its browser nature in any user and generalize.
1739                        if (packageIsBrowser(packageName, userId)) {
1740                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1741                        }
1742
1743                        // We may also need to apply pending (restored) runtime
1744                        // permission grants within these users.
1745                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1746                    }
1747                }
1748            }
1749
1750            // Log current value of "unknown sources" setting
1751            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1752                    getUnknownSourcesSettings());
1753
1754            // Force a gc to clear up things
1755            Runtime.getRuntime().gc();
1756
1757            // Remove the replaced package's older resources safely now
1758            // We delete after a gc for applications  on sdcard.
1759            if (res.removedInfo != null && res.removedInfo.args != null) {
1760                synchronized (mInstallLock) {
1761                    res.removedInfo.args.doPostDeleteLI(true);
1762                }
1763            }
1764        }
1765
1766        // If someone is watching installs - notify them
1767        if (installObserver != null) {
1768            try {
1769                Bundle extras = extrasForInstallResult(res);
1770                installObserver.onPackageInstalled(res.name, res.returnCode,
1771                        res.returnMsg, extras);
1772            } catch (RemoteException e) {
1773                Slog.i(TAG, "Observer no longer exists.");
1774            }
1775        }
1776    }
1777
1778    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1779            PackageParser.Package pkg) {
1780        if (pkg.parentPackage == null) {
1781            return;
1782        }
1783        if (pkg.requestedPermissions == null) {
1784            return;
1785        }
1786        final PackageSetting disabledSysParentPs = mSettings
1787                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1788        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1789                || !disabledSysParentPs.isPrivileged()
1790                || (disabledSysParentPs.childPackageNames != null
1791                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1792            return;
1793        }
1794        final int[] allUserIds = sUserManager.getUserIds();
1795        final int permCount = pkg.requestedPermissions.size();
1796        for (int i = 0; i < permCount; i++) {
1797            String permission = pkg.requestedPermissions.get(i);
1798            BasePermission bp = mSettings.mPermissions.get(permission);
1799            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1800                continue;
1801            }
1802            for (int userId : allUserIds) {
1803                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1804                        permission, userId)) {
1805                    grantRuntimePermission(pkg.packageName, permission, userId);
1806                }
1807            }
1808        }
1809    }
1810
1811    private StorageEventListener mStorageListener = new StorageEventListener() {
1812        @Override
1813        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1814            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1815                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1816                    final String volumeUuid = vol.getFsUuid();
1817
1818                    // Clean up any users or apps that were removed or recreated
1819                    // while this volume was missing
1820                    reconcileUsers(volumeUuid);
1821                    reconcileApps(volumeUuid);
1822
1823                    // Clean up any install sessions that expired or were
1824                    // cancelled while this volume was missing
1825                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1826
1827                    loadPrivatePackages(vol);
1828
1829                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1830                    unloadPrivatePackages(vol);
1831                }
1832            }
1833
1834            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1835                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836                    updateExternalMediaStatus(true, false);
1837                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1838                    updateExternalMediaStatus(false, false);
1839                }
1840            }
1841        }
1842
1843        @Override
1844        public void onVolumeForgotten(String fsUuid) {
1845            if (TextUtils.isEmpty(fsUuid)) {
1846                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1847                return;
1848            }
1849
1850            // Remove any apps installed on the forgotten volume
1851            synchronized (mPackages) {
1852                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1853                for (PackageSetting ps : packages) {
1854                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1855                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1856                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1857                }
1858
1859                mSettings.onVolumeForgotten(fsUuid);
1860                mSettings.writeLPr();
1861            }
1862        }
1863    };
1864
1865    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1866            String[] grantedPermissions) {
1867        for (int userId : userIds) {
1868            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1869        }
1870
1871        // We could have touched GID membership, so flush out packages.list
1872        synchronized (mPackages) {
1873            mSettings.writePackageListLPr();
1874        }
1875    }
1876
1877    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1878            String[] grantedPermissions) {
1879        SettingBase sb = (SettingBase) pkg.mExtras;
1880        if (sb == null) {
1881            return;
1882        }
1883
1884        PermissionsState permissionsState = sb.getPermissionsState();
1885
1886        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1887                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1888
1889        for (String permission : pkg.requestedPermissions) {
1890            final BasePermission bp;
1891            synchronized (mPackages) {
1892                bp = mSettings.mPermissions.get(permission);
1893            }
1894            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1895                    && (grantedPermissions == null
1896                           || ArrayUtils.contains(grantedPermissions, permission))) {
1897                final int flags = permissionsState.getPermissionFlags(permission, userId);
1898                // Installer cannot change immutable permissions.
1899                if ((flags & immutableFlags) == 0) {
1900                    grantRuntimePermission(pkg.packageName, permission, userId);
1901                }
1902            }
1903        }
1904    }
1905
1906    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1907        Bundle extras = null;
1908        switch (res.returnCode) {
1909            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1910                extras = new Bundle();
1911                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1912                        res.origPermission);
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1914                        res.origPackage);
1915                break;
1916            }
1917            case PackageManager.INSTALL_SUCCEEDED: {
1918                extras = new Bundle();
1919                extras.putBoolean(Intent.EXTRA_REPLACING,
1920                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1921                break;
1922            }
1923        }
1924        return extras;
1925    }
1926
1927    void scheduleWriteSettingsLocked() {
1928        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1929            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1930        }
1931    }
1932
1933    void scheduleWritePackageListLocked(int userId) {
1934        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1935            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1936            msg.arg1 = userId;
1937            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1938        }
1939    }
1940
1941    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1942        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1943        scheduleWritePackageRestrictionsLocked(userId);
1944    }
1945
1946    void scheduleWritePackageRestrictionsLocked(int userId) {
1947        final int[] userIds = (userId == UserHandle.USER_ALL)
1948                ? sUserManager.getUserIds() : new int[]{userId};
1949        for (int nextUserId : userIds) {
1950            if (!sUserManager.exists(nextUserId)) return;
1951            mDirtyUsers.add(nextUserId);
1952            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1953                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1954            }
1955        }
1956    }
1957
1958    public static PackageManagerService main(Context context, Installer installer,
1959            boolean factoryTest, boolean onlyCore) {
1960        // Self-check for initial settings.
1961        PackageManagerServiceCompilerMapping.checkProperties();
1962
1963        PackageManagerService m = new PackageManagerService(context, installer,
1964                factoryTest, onlyCore);
1965        m.enableSystemUserPackages();
1966        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
1967        // disabled after already being started.
1968        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
1969                UserHandle.USER_SYSTEM);
1970        ServiceManager.addService("package", m);
1971        return m;
1972    }
1973
1974    private void enableSystemUserPackages() {
1975        if (!UserManager.isSplitSystemUser()) {
1976            return;
1977        }
1978        // For system user, enable apps based on the following conditions:
1979        // - app is whitelisted or belong to one of these groups:
1980        //   -- system app which has no launcher icons
1981        //   -- system app which has INTERACT_ACROSS_USERS permission
1982        //   -- system IME app
1983        // - app is not in the blacklist
1984        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1985        Set<String> enableApps = new ArraySet<>();
1986        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1987                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1988                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1989        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1990        enableApps.addAll(wlApps);
1991        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1992                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1993        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1994        enableApps.removeAll(blApps);
1995        Log.i(TAG, "Applications installed for system user: " + enableApps);
1996        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1997                UserHandle.SYSTEM);
1998        final int allAppsSize = allAps.size();
1999        synchronized (mPackages) {
2000            for (int i = 0; i < allAppsSize; i++) {
2001                String pName = allAps.get(i);
2002                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2003                // Should not happen, but we shouldn't be failing if it does
2004                if (pkgSetting == null) {
2005                    continue;
2006                }
2007                boolean install = enableApps.contains(pName);
2008                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2009                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2010                            + " for system user");
2011                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2012                }
2013            }
2014        }
2015    }
2016
2017    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2018        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2019                Context.DISPLAY_SERVICE);
2020        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2021    }
2022
2023    /**
2024     * Requests that files preopted on a secondary system partition be copied to the data partition
2025     * if possible.  Note that the actual copying of the files is accomplished by init for security
2026     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2027     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2028     */
2029    private static void requestCopyPreoptedFiles() {
2030        final int WAIT_TIME_MS = 100;
2031        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2032        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2033            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2034            // We will wait for up to 100 seconds.
2035            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2036            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2037                try {
2038                    Thread.sleep(WAIT_TIME_MS);
2039                } catch (InterruptedException e) {
2040                    // Do nothing
2041                }
2042                if (SystemClock.uptimeMillis() > timeEnd) {
2043                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2044                    Slog.wtf(TAG, "cppreopt did not finish!");
2045                    break;
2046                }
2047            }
2048        }
2049    }
2050
2051    public PackageManagerService(Context context, Installer installer,
2052            boolean factoryTest, boolean onlyCore) {
2053        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2054                SystemClock.uptimeMillis());
2055
2056        if (mSdkVersion <= 0) {
2057            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2058        }
2059
2060        mContext = context;
2061        mFactoryTest = factoryTest;
2062        mOnlyCore = onlyCore;
2063        mMetrics = new DisplayMetrics();
2064        mSettings = new Settings(mPackages);
2065        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2066                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2067        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2068                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2069        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2076                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2077
2078        String separateProcesses = SystemProperties.get("debug.separate_processes");
2079        if (separateProcesses != null && separateProcesses.length() > 0) {
2080            if ("*".equals(separateProcesses)) {
2081                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2082                mSeparateProcesses = null;
2083                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2084            } else {
2085                mDefParseFlags = 0;
2086                mSeparateProcesses = separateProcesses.split(",");
2087                Slog.w(TAG, "Running with debug.separate_processes: "
2088                        + separateProcesses);
2089            }
2090        } else {
2091            mDefParseFlags = 0;
2092            mSeparateProcesses = null;
2093        }
2094
2095        mInstaller = installer;
2096        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2097                "*dexopt*");
2098        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2099
2100        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2101                FgThread.get().getLooper());
2102
2103        getDefaultDisplayMetrics(context, mMetrics);
2104
2105        SystemConfig systemConfig = SystemConfig.getInstance();
2106        mGlobalGids = systemConfig.getGlobalGids();
2107        mSystemPermissions = systemConfig.getSystemPermissions();
2108        mAvailableFeatures = systemConfig.getAvailableFeatures();
2109
2110        mProtectedPackages = new ProtectedPackages(mContext);
2111
2112        synchronized (mInstallLock) {
2113        // writer
2114        synchronized (mPackages) {
2115            mHandlerThread = new ServiceThread(TAG,
2116                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2117            mHandlerThread.start();
2118            mHandler = new PackageHandler(mHandlerThread.getLooper());
2119            mProcessLoggingHandler = new ProcessLoggingHandler();
2120            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2121
2122            File dataDir = Environment.getDataDirectory();
2123            mAppInstallDir = new File(dataDir, "app");
2124            mAppLib32InstallDir = new File(dataDir, "app-lib");
2125            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2126            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2127            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2128
2129            sUserManager = new UserManagerService(context, this, mPackages);
2130
2131            // Propagate permission configuration in to package manager.
2132            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2133                    = systemConfig.getPermissions();
2134            for (int i=0; i<permConfig.size(); i++) {
2135                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2136                BasePermission bp = mSettings.mPermissions.get(perm.name);
2137                if (bp == null) {
2138                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2139                    mSettings.mPermissions.put(perm.name, bp);
2140                }
2141                if (perm.gids != null) {
2142                    bp.setGids(perm.gids, perm.perUser);
2143                }
2144            }
2145
2146            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2147            for (int i=0; i<libConfig.size(); i++) {
2148                mSharedLibraries.put(libConfig.keyAt(i),
2149                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2150            }
2151
2152            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2153
2154            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2155
2156            if (mFirstBoot) {
2157                requestCopyPreoptedFiles();
2158            }
2159
2160            String customResolverActivity = Resources.getSystem().getString(
2161                    R.string.config_customResolverActivity);
2162            if (TextUtils.isEmpty(customResolverActivity)) {
2163                customResolverActivity = null;
2164            } else {
2165                mCustomResolverComponentName = ComponentName.unflattenFromString(
2166                        customResolverActivity);
2167            }
2168
2169            long startTime = SystemClock.uptimeMillis();
2170
2171            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2172                    startTime);
2173
2174            // Set flag to monitor and not change apk file paths when
2175            // scanning install directories.
2176            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2177
2178            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2179            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2180
2181            if (bootClassPath == null) {
2182                Slog.w(TAG, "No BOOTCLASSPATH found!");
2183            }
2184
2185            if (systemServerClassPath == null) {
2186                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2187            }
2188
2189            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2190            final String[] dexCodeInstructionSets =
2191                    getDexCodeInstructionSets(
2192                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2193
2194            /**
2195             * Ensure all external libraries have had dexopt run on them.
2196             */
2197            if (mSharedLibraries.size() > 0) {
2198                // NOTE: For now, we're compiling these system "shared libraries"
2199                // (and framework jars) into all available architectures. It's possible
2200                // to compile them only when we come across an app that uses them (there's
2201                // already logic for that in scanPackageLI) but that adds some complexity.
2202                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2203                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2204                        final String lib = libEntry.path;
2205                        if (lib == null) {
2206                            continue;
2207                        }
2208
2209                        try {
2210                            // Shared libraries do not have profiles so we perform a full
2211                            // AOT compilation (if needed).
2212                            int dexoptNeeded = DexFile.getDexOptNeeded(
2213                                    lib, dexCodeInstructionSet,
2214                                    getCompilerFilterForReason(REASON_SHARED_APK),
2215                                    false /* newProfile */);
2216                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2217                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2218                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2219                                        getCompilerFilterForReason(REASON_SHARED_APK),
2220                                        StorageManager.UUID_PRIVATE_INTERNAL,
2221                                        SKIP_SHARED_LIBRARY_CHECK);
2222                            }
2223                        } catch (FileNotFoundException e) {
2224                            Slog.w(TAG, "Library not found: " + lib);
2225                        } catch (IOException | InstallerException e) {
2226                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2227                                    + e.getMessage());
2228                        }
2229                    }
2230                }
2231            }
2232
2233            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2234
2235            final VersionInfo ver = mSettings.getInternalVersion();
2236            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2237
2238            // when upgrading from pre-M, promote system app permissions from install to runtime
2239            mPromoteSystemApps =
2240                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2241
2242            // When upgrading from pre-N, we need to handle package extraction like first boot,
2243            // as there is no profiling data available.
2244            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2245
2246            // save off the names of pre-existing system packages prior to scanning; we don't
2247            // want to automatically grant runtime permissions for new system apps
2248            if (mPromoteSystemApps) {
2249                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2250                while (pkgSettingIter.hasNext()) {
2251                    PackageSetting ps = pkgSettingIter.next();
2252                    if (isSystemApp(ps)) {
2253                        mExistingSystemPackages.add(ps.name);
2254                    }
2255                }
2256            }
2257
2258            // Collect vendor overlay packages.
2259            // (Do this before scanning any apps.)
2260            // For security and version matching reason, only consider
2261            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2262            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2263            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2264                    | PackageParser.PARSE_IS_SYSTEM
2265                    | PackageParser.PARSE_IS_SYSTEM_DIR
2266                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2267
2268            // Find base frameworks (resource packages without code).
2269            scanDirTracedLI(frameworkDir, mDefParseFlags
2270                    | PackageParser.PARSE_IS_SYSTEM
2271                    | PackageParser.PARSE_IS_SYSTEM_DIR
2272                    | PackageParser.PARSE_IS_PRIVILEGED,
2273                    scanFlags | SCAN_NO_DEX, 0);
2274
2275            // Collected privileged system packages.
2276            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2277            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2278                    | PackageParser.PARSE_IS_SYSTEM
2279                    | PackageParser.PARSE_IS_SYSTEM_DIR
2280                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2281
2282            // Collect ordinary system packages.
2283            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2284            scanDirTracedLI(systemAppDir, mDefParseFlags
2285                    | PackageParser.PARSE_IS_SYSTEM
2286                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2287
2288            // Collect all vendor packages.
2289            File vendorAppDir = new File("/vendor/app");
2290            try {
2291                vendorAppDir = vendorAppDir.getCanonicalFile();
2292            } catch (IOException e) {
2293                // failed to look up canonical path, continue with original one
2294            }
2295            scanDirTracedLI(vendorAppDir, mDefParseFlags
2296                    | PackageParser.PARSE_IS_SYSTEM
2297                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2298
2299            // Collect all OEM packages.
2300            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2301            scanDirTracedLI(oemAppDir, mDefParseFlags
2302                    | PackageParser.PARSE_IS_SYSTEM
2303                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2304
2305            // Prune any system packages that no longer exist.
2306            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2307            if (!mOnlyCore) {
2308                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2309                while (psit.hasNext()) {
2310                    PackageSetting ps = psit.next();
2311
2312                    /*
2313                     * If this is not a system app, it can't be a
2314                     * disable system app.
2315                     */
2316                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2317                        continue;
2318                    }
2319
2320                    /*
2321                     * If the package is scanned, it's not erased.
2322                     */
2323                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2324                    if (scannedPkg != null) {
2325                        /*
2326                         * If the system app is both scanned and in the
2327                         * disabled packages list, then it must have been
2328                         * added via OTA. Remove it from the currently
2329                         * scanned package so the previously user-installed
2330                         * application can be scanned.
2331                         */
2332                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2333                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2334                                    + ps.name + "; removing system app.  Last known codePath="
2335                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2336                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2337                                    + scannedPkg.mVersionCode);
2338                            removePackageLI(scannedPkg, true);
2339                            mExpectingBetter.put(ps.name, ps.codePath);
2340                        }
2341
2342                        continue;
2343                    }
2344
2345                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2346                        psit.remove();
2347                        logCriticalInfo(Log.WARN, "System package " + ps.name
2348                                + " no longer exists; it's data will be wiped");
2349                        // Actual deletion of code and data will be handled by later
2350                        // reconciliation step
2351                    } else {
2352                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2353                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2354                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2355                        }
2356                    }
2357                }
2358            }
2359
2360            //look for any incomplete package installations
2361            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2362            for (int i = 0; i < deletePkgsList.size(); i++) {
2363                // Actual deletion of code and data will be handled by later
2364                // reconciliation step
2365                final String packageName = deletePkgsList.get(i).name;
2366                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2367                synchronized (mPackages) {
2368                    mSettings.removePackageLPw(packageName);
2369                }
2370            }
2371
2372            //delete tmp files
2373            deleteTempPackageFiles();
2374
2375            // Remove any shared userIDs that have no associated packages
2376            mSettings.pruneSharedUsersLPw();
2377
2378            if (!mOnlyCore) {
2379                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2380                        SystemClock.uptimeMillis());
2381                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2382
2383                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2384                        | PackageParser.PARSE_FORWARD_LOCK,
2385                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2386
2387                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2388                        | PackageParser.PARSE_IS_EPHEMERAL,
2389                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2390
2391                /**
2392                 * Remove disable package settings for any updated system
2393                 * apps that were removed via an OTA. If they're not a
2394                 * previously-updated app, remove them completely.
2395                 * Otherwise, just revoke their system-level permissions.
2396                 */
2397                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2398                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2399                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2400
2401                    String msg;
2402                    if (deletedPkg == null) {
2403                        msg = "Updated system package " + deletedAppName
2404                                + " no longer exists; it's data will be wiped";
2405                        // Actual deletion of code and data will be handled by later
2406                        // reconciliation step
2407                    } else {
2408                        msg = "Updated system app + " + deletedAppName
2409                                + " no longer present; removing system privileges for "
2410                                + deletedAppName;
2411
2412                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2413
2414                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2415                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2416                    }
2417                    logCriticalInfo(Log.WARN, msg);
2418                }
2419
2420                /**
2421                 * Make sure all system apps that we expected to appear on
2422                 * the userdata partition actually showed up. If they never
2423                 * appeared, crawl back and revive the system version.
2424                 */
2425                for (int i = 0; i < mExpectingBetter.size(); i++) {
2426                    final String packageName = mExpectingBetter.keyAt(i);
2427                    if (!mPackages.containsKey(packageName)) {
2428                        final File scanFile = mExpectingBetter.valueAt(i);
2429
2430                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2431                                + " but never showed up; reverting to system");
2432
2433                        int reparseFlags = mDefParseFlags;
2434                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2435                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2436                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2437                                    | PackageParser.PARSE_IS_PRIVILEGED;
2438                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2439                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2440                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2441                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2442                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2443                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2444                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2445                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2446                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2447                        } else {
2448                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2449                            continue;
2450                        }
2451
2452                        mSettings.enableSystemPackageLPw(packageName);
2453
2454                        try {
2455                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2456                        } catch (PackageManagerException e) {
2457                            Slog.e(TAG, "Failed to parse original system package: "
2458                                    + e.getMessage());
2459                        }
2460                    }
2461                }
2462            }
2463            mExpectingBetter.clear();
2464
2465            // Resolve protected action filters. Only the setup wizard is allowed to
2466            // have a high priority filter for these actions.
2467            mSetupWizardPackage = getSetupWizardPackageName();
2468            if (mProtectedFilters.size() > 0) {
2469                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2470                    Slog.i(TAG, "No setup wizard;"
2471                        + " All protected intents capped to priority 0");
2472                }
2473                for (ActivityIntentInfo filter : mProtectedFilters) {
2474                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2475                        if (DEBUG_FILTERS) {
2476                            Slog.i(TAG, "Found setup wizard;"
2477                                + " allow priority " + filter.getPriority() + ";"
2478                                + " package: " + filter.activity.info.packageName
2479                                + " activity: " + filter.activity.className
2480                                + " priority: " + filter.getPriority());
2481                        }
2482                        // skip setup wizard; allow it to keep the high priority filter
2483                        continue;
2484                    }
2485                    Slog.w(TAG, "Protected action; cap priority to 0;"
2486                            + " package: " + filter.activity.info.packageName
2487                            + " activity: " + filter.activity.className
2488                            + " origPrio: " + filter.getPriority());
2489                    filter.setPriority(0);
2490                }
2491            }
2492            mDeferProtectedFilters = false;
2493            mProtectedFilters.clear();
2494
2495            // Now that we know all of the shared libraries, update all clients to have
2496            // the correct library paths.
2497            updateAllSharedLibrariesLPw();
2498
2499            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2500                // NOTE: We ignore potential failures here during a system scan (like
2501                // the rest of the commands above) because there's precious little we
2502                // can do about it. A settings error is reported, though.
2503                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2504                        false /* boot complete */);
2505            }
2506
2507            // Now that we know all the packages we are keeping,
2508            // read and update their last usage times.
2509            mPackageUsage.read(mPackages);
2510            mCompilerStats.read();
2511
2512            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2513                    SystemClock.uptimeMillis());
2514            Slog.i(TAG, "Time to scan packages: "
2515                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2516                    + " seconds");
2517
2518            // If the platform SDK has changed since the last time we booted,
2519            // we need to re-grant app permission to catch any new ones that
2520            // appear.  This is really a hack, and means that apps can in some
2521            // cases get permissions that the user didn't initially explicitly
2522            // allow...  it would be nice to have some better way to handle
2523            // this situation.
2524            int updateFlags = UPDATE_PERMISSIONS_ALL;
2525            if (ver.sdkVersion != mSdkVersion) {
2526                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2527                        + mSdkVersion + "; regranting permissions for internal storage");
2528                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2529            }
2530            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2531            ver.sdkVersion = mSdkVersion;
2532
2533            // If this is the first boot or an update from pre-M, and it is a normal
2534            // boot, then we need to initialize the default preferred apps across
2535            // all defined users.
2536            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2537                for (UserInfo user : sUserManager.getUsers(true)) {
2538                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2539                    applyFactoryDefaultBrowserLPw(user.id);
2540                    primeDomainVerificationsLPw(user.id);
2541                }
2542            }
2543
2544            // Prepare storage for system user really early during boot,
2545            // since core system apps like SettingsProvider and SystemUI
2546            // can't wait for user to start
2547            final int storageFlags;
2548            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2549                storageFlags = StorageManager.FLAG_STORAGE_DE;
2550            } else {
2551                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2552            }
2553            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2554                    storageFlags);
2555
2556            // If this is first boot after an OTA, and a normal boot, then
2557            // we need to clear code cache directories.
2558            // Note that we do *not* clear the application profiles. These remain valid
2559            // across OTAs and are used to drive profile verification (post OTA) and
2560            // profile compilation (without waiting to collect a fresh set of profiles).
2561            if (mIsUpgrade && !onlyCore) {
2562                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2563                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2564                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2565                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2566                        // No apps are running this early, so no need to freeze
2567                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2568                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2569                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2570                    }
2571                }
2572                ver.fingerprint = Build.FINGERPRINT;
2573            }
2574
2575            checkDefaultBrowser();
2576
2577            // clear only after permissions and other defaults have been updated
2578            mExistingSystemPackages.clear();
2579            mPromoteSystemApps = false;
2580
2581            // All the changes are done during package scanning.
2582            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2583
2584            // can downgrade to reader
2585            mSettings.writeLPr();
2586
2587            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2588            // early on (before the package manager declares itself as early) because other
2589            // components in the system server might ask for package contexts for these apps.
2590            //
2591            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2592            // (i.e, that the data partition is unavailable).
2593            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2594                long start = System.nanoTime();
2595                List<PackageParser.Package> coreApps = new ArrayList<>();
2596                for (PackageParser.Package pkg : mPackages.values()) {
2597                    if (pkg.coreApp) {
2598                        coreApps.add(pkg);
2599                    }
2600                }
2601
2602                int[] stats = performDexOptUpgrade(coreApps, false,
2603                        getCompilerFilterForReason(REASON_CORE_APP));
2604
2605                final int elapsedTimeSeconds =
2606                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2607                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2608
2609                if (DEBUG_DEXOPT) {
2610                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2611                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2612                }
2613
2614
2615                // TODO: Should we log these stats to tron too ?
2616                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2617                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2618                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2619                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2620            }
2621
2622            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2623                    SystemClock.uptimeMillis());
2624
2625            if (!mOnlyCore) {
2626                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2627                mRequiredInstallerPackage = getRequiredInstallerLPr();
2628                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2629                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2630                        mIntentFilterVerifierComponent);
2631                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2632                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2633                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2634                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2635            } else {
2636                mRequiredVerifierPackage = null;
2637                mRequiredInstallerPackage = null;
2638                mIntentFilterVerifierComponent = null;
2639                mIntentFilterVerifier = null;
2640                mServicesSystemSharedLibraryPackageName = null;
2641                mSharedSystemSharedLibraryPackageName = null;
2642            }
2643
2644            mInstallerService = new PackageInstallerService(context, this);
2645
2646            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2647            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2648            // both the installer and resolver must be present to enable ephemeral
2649            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2650                if (DEBUG_EPHEMERAL) {
2651                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2652                            + " installer:" + ephemeralInstallerComponent);
2653                }
2654                mEphemeralResolverComponent = ephemeralResolverComponent;
2655                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2656                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2657                mEphemeralResolverConnection =
2658                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2659            } else {
2660                if (DEBUG_EPHEMERAL) {
2661                    final String missingComponent =
2662                            (ephemeralResolverComponent == null)
2663                            ? (ephemeralInstallerComponent == null)
2664                                    ? "resolver and installer"
2665                                    : "resolver"
2666                            : "installer";
2667                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2668                }
2669                mEphemeralResolverComponent = null;
2670                mEphemeralInstallerComponent = null;
2671                mEphemeralResolverConnection = null;
2672            }
2673
2674            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2675        } // synchronized (mPackages)
2676        } // synchronized (mInstallLock)
2677
2678        // Now after opening every single application zip, make sure they
2679        // are all flushed.  Not really needed, but keeps things nice and
2680        // tidy.
2681        Runtime.getRuntime().gc();
2682
2683        // The initial scanning above does many calls into installd while
2684        // holding the mPackages lock, but we're mostly interested in yelling
2685        // once we have a booted system.
2686        mInstaller.setWarnIfHeld(mPackages);
2687
2688        // Expose private service for system components to use.
2689        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2690    }
2691
2692    @Override
2693    public boolean isFirstBoot() {
2694        return mFirstBoot;
2695    }
2696
2697    @Override
2698    public boolean isOnlyCoreApps() {
2699        return mOnlyCore;
2700    }
2701
2702    @Override
2703    public boolean isUpgrade() {
2704        return mIsUpgrade;
2705    }
2706
2707    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2708        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2709
2710        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2711                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2712                UserHandle.USER_SYSTEM);
2713        if (matches.size() == 1) {
2714            return matches.get(0).getComponentInfo().packageName;
2715        } else {
2716            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2717            return null;
2718        }
2719    }
2720
2721    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2722        synchronized (mPackages) {
2723            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2724            if (libraryEntry == null) {
2725                throw new IllegalStateException("Missing required shared library:" + libraryName);
2726            }
2727            return libraryEntry.apk;
2728        }
2729    }
2730
2731    private @NonNull String getRequiredInstallerLPr() {
2732        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2733        intent.addCategory(Intent.CATEGORY_DEFAULT);
2734        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2735
2736        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2737                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2738                UserHandle.USER_SYSTEM);
2739        if (matches.size() == 1) {
2740            ResolveInfo resolveInfo = matches.get(0);
2741            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2742                throw new RuntimeException("The installer must be a privileged app");
2743            }
2744            return matches.get(0).getComponentInfo().packageName;
2745        } else {
2746            throw new RuntimeException("There must be exactly one installer; found " + matches);
2747        }
2748    }
2749
2750    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2751        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2752
2753        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2754                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2755                UserHandle.USER_SYSTEM);
2756        ResolveInfo best = null;
2757        final int N = matches.size();
2758        for (int i = 0; i < N; i++) {
2759            final ResolveInfo cur = matches.get(i);
2760            final String packageName = cur.getComponentInfo().packageName;
2761            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2762                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2763                continue;
2764            }
2765
2766            if (best == null || cur.priority > best.priority) {
2767                best = cur;
2768            }
2769        }
2770
2771        if (best != null) {
2772            return best.getComponentInfo().getComponentName();
2773        } else {
2774            throw new RuntimeException("There must be at least one intent filter verifier");
2775        }
2776    }
2777
2778    private @Nullable ComponentName getEphemeralResolverLPr() {
2779        final String[] packageArray =
2780                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2781        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2782            if (DEBUG_EPHEMERAL) {
2783                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2784            }
2785            return null;
2786        }
2787
2788        final int resolveFlags =
2789                MATCH_DIRECT_BOOT_AWARE
2790                | MATCH_DIRECT_BOOT_UNAWARE
2791                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2792        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2793        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2794                resolveFlags, UserHandle.USER_SYSTEM);
2795
2796        final int N = resolvers.size();
2797        if (N == 0) {
2798            if (DEBUG_EPHEMERAL) {
2799                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2800            }
2801            return null;
2802        }
2803
2804        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2805        for (int i = 0; i < N; i++) {
2806            final ResolveInfo info = resolvers.get(i);
2807
2808            if (info.serviceInfo == null) {
2809                continue;
2810            }
2811
2812            final String packageName = info.serviceInfo.packageName;
2813            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2814                if (DEBUG_EPHEMERAL) {
2815                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2816                            + " pkg: " + packageName + ", info:" + info);
2817                }
2818                continue;
2819            }
2820
2821            if (DEBUG_EPHEMERAL) {
2822                Slog.v(TAG, "Ephemeral resolver found;"
2823                        + " pkg: " + packageName + ", info:" + info);
2824            }
2825            return new ComponentName(packageName, info.serviceInfo.name);
2826        }
2827        if (DEBUG_EPHEMERAL) {
2828            Slog.v(TAG, "Ephemeral resolver NOT found");
2829        }
2830        return null;
2831    }
2832
2833    private @Nullable ComponentName getEphemeralInstallerLPr() {
2834        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2835        intent.addCategory(Intent.CATEGORY_DEFAULT);
2836        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2837
2838        final int resolveFlags =
2839                MATCH_DIRECT_BOOT_AWARE
2840                | MATCH_DIRECT_BOOT_UNAWARE
2841                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2842        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2843                resolveFlags, UserHandle.USER_SYSTEM);
2844        if (matches.size() == 0) {
2845            return null;
2846        } else if (matches.size() == 1) {
2847            return matches.get(0).getComponentInfo().getComponentName();
2848        } else {
2849            throw new RuntimeException(
2850                    "There must be at most one ephemeral installer; found " + matches);
2851        }
2852    }
2853
2854    private void primeDomainVerificationsLPw(int userId) {
2855        if (DEBUG_DOMAIN_VERIFICATION) {
2856            Slog.d(TAG, "Priming domain verifications in user " + userId);
2857        }
2858
2859        SystemConfig systemConfig = SystemConfig.getInstance();
2860        ArraySet<String> packages = systemConfig.getLinkedApps();
2861        ArraySet<String> domains = new ArraySet<String>();
2862
2863        for (String packageName : packages) {
2864            PackageParser.Package pkg = mPackages.get(packageName);
2865            if (pkg != null) {
2866                if (!pkg.isSystemApp()) {
2867                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2868                    continue;
2869                }
2870
2871                domains.clear();
2872                for (PackageParser.Activity a : pkg.activities) {
2873                    for (ActivityIntentInfo filter : a.intents) {
2874                        if (hasValidDomains(filter)) {
2875                            domains.addAll(filter.getHostsList());
2876                        }
2877                    }
2878                }
2879
2880                if (domains.size() > 0) {
2881                    if (DEBUG_DOMAIN_VERIFICATION) {
2882                        Slog.v(TAG, "      + " + packageName);
2883                    }
2884                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2885                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2886                    // and then 'always' in the per-user state actually used for intent resolution.
2887                    final IntentFilterVerificationInfo ivi;
2888                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2889                            new ArrayList<String>(domains));
2890                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2891                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2892                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2893                } else {
2894                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2895                            + "' does not handle web links");
2896                }
2897            } else {
2898                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2899            }
2900        }
2901
2902        scheduleWritePackageRestrictionsLocked(userId);
2903        scheduleWriteSettingsLocked();
2904    }
2905
2906    private void applyFactoryDefaultBrowserLPw(int userId) {
2907        // The default browser app's package name is stored in a string resource,
2908        // with a product-specific overlay used for vendor customization.
2909        String browserPkg = mContext.getResources().getString(
2910                com.android.internal.R.string.default_browser);
2911        if (!TextUtils.isEmpty(browserPkg)) {
2912            // non-empty string => required to be a known package
2913            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2914            if (ps == null) {
2915                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2916                browserPkg = null;
2917            } else {
2918                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2919            }
2920        }
2921
2922        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2923        // default.  If there's more than one, just leave everything alone.
2924        if (browserPkg == null) {
2925            calculateDefaultBrowserLPw(userId);
2926        }
2927    }
2928
2929    private void calculateDefaultBrowserLPw(int userId) {
2930        List<String> allBrowsers = resolveAllBrowserApps(userId);
2931        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2932        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2933    }
2934
2935    private List<String> resolveAllBrowserApps(int userId) {
2936        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2937        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2938                PackageManager.MATCH_ALL, userId);
2939
2940        final int count = list.size();
2941        List<String> result = new ArrayList<String>(count);
2942        for (int i=0; i<count; i++) {
2943            ResolveInfo info = list.get(i);
2944            if (info.activityInfo == null
2945                    || !info.handleAllWebDataURI
2946                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2947                    || result.contains(info.activityInfo.packageName)) {
2948                continue;
2949            }
2950            result.add(info.activityInfo.packageName);
2951        }
2952
2953        return result;
2954    }
2955
2956    private boolean packageIsBrowser(String packageName, int userId) {
2957        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2958                PackageManager.MATCH_ALL, userId);
2959        final int N = list.size();
2960        for (int i = 0; i < N; i++) {
2961            ResolveInfo info = list.get(i);
2962            if (packageName.equals(info.activityInfo.packageName)) {
2963                return true;
2964            }
2965        }
2966        return false;
2967    }
2968
2969    private void checkDefaultBrowser() {
2970        final int myUserId = UserHandle.myUserId();
2971        final String packageName = getDefaultBrowserPackageName(myUserId);
2972        if (packageName != null) {
2973            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2974            if (info == null) {
2975                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2976                synchronized (mPackages) {
2977                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2978                }
2979            }
2980        }
2981    }
2982
2983    @Override
2984    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2985            throws RemoteException {
2986        try {
2987            return super.onTransact(code, data, reply, flags);
2988        } catch (RuntimeException e) {
2989            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2990                Slog.wtf(TAG, "Package Manager Crash", e);
2991            }
2992            throw e;
2993        }
2994    }
2995
2996    static int[] appendInts(int[] cur, int[] add) {
2997        if (add == null) return cur;
2998        if (cur == null) return add;
2999        final int N = add.length;
3000        for (int i=0; i<N; i++) {
3001            cur = appendInt(cur, add[i]);
3002        }
3003        return cur;
3004    }
3005
3006    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3007        if (!sUserManager.exists(userId)) return null;
3008        if (ps == null) {
3009            return null;
3010        }
3011        final PackageParser.Package p = ps.pkg;
3012        if (p == null) {
3013            return null;
3014        }
3015
3016        final PermissionsState permissionsState = ps.getPermissionsState();
3017
3018        // Compute GIDs only if requested
3019        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3020                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3021        // Compute granted permissions only if package has requested permissions
3022        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3023                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3024        final PackageUserState state = ps.readUserState(userId);
3025
3026        return PackageParser.generatePackageInfo(p, gids, flags,
3027                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3028    }
3029
3030    @Override
3031    public void checkPackageStartable(String packageName, int userId) {
3032        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3033
3034        synchronized (mPackages) {
3035            final PackageSetting ps = mSettings.mPackages.get(packageName);
3036            if (ps == null) {
3037                throw new SecurityException("Package " + packageName + " was not found!");
3038            }
3039
3040            if (!ps.getInstalled(userId)) {
3041                throw new SecurityException(
3042                        "Package " + packageName + " was not installed for user " + userId + "!");
3043            }
3044
3045            if (mSafeMode && !ps.isSystem()) {
3046                throw new SecurityException("Package " + packageName + " not a system app!");
3047            }
3048
3049            if (mFrozenPackages.contains(packageName)) {
3050                throw new SecurityException("Package " + packageName + " is currently frozen!");
3051            }
3052
3053            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3054                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3055                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3056            }
3057        }
3058    }
3059
3060    @Override
3061    public boolean isPackageAvailable(String packageName, int userId) {
3062        if (!sUserManager.exists(userId)) return false;
3063        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3064                false /* requireFullPermission */, false /* checkShell */, "is package available");
3065        synchronized (mPackages) {
3066            PackageParser.Package p = mPackages.get(packageName);
3067            if (p != null) {
3068                final PackageSetting ps = (PackageSetting) p.mExtras;
3069                if (ps != null) {
3070                    final PackageUserState state = ps.readUserState(userId);
3071                    if (state != null) {
3072                        return PackageParser.isAvailable(state);
3073                    }
3074                }
3075            }
3076        }
3077        return false;
3078    }
3079
3080    @Override
3081    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3082        if (!sUserManager.exists(userId)) return null;
3083        flags = updateFlagsForPackage(flags, userId, packageName);
3084        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3085                false /* requireFullPermission */, false /* checkShell */, "get package info");
3086        // reader
3087        synchronized (mPackages) {
3088            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3089            PackageParser.Package p = null;
3090            if (matchFactoryOnly) {
3091                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3092                if (ps != null) {
3093                    return generatePackageInfo(ps, flags, userId);
3094                }
3095            }
3096            if (p == null) {
3097                p = mPackages.get(packageName);
3098                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3099                    return null;
3100                }
3101            }
3102            if (DEBUG_PACKAGE_INFO)
3103                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3104            if (p != null) {
3105                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3106            }
3107            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3108                final PackageSetting ps = mSettings.mPackages.get(packageName);
3109                return generatePackageInfo(ps, flags, userId);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public String[] currentToCanonicalPackageNames(String[] names) {
3117        String[] out = new String[names.length];
3118        // reader
3119        synchronized (mPackages) {
3120            for (int i=names.length-1; i>=0; i--) {
3121                PackageSetting ps = mSettings.mPackages.get(names[i]);
3122                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3123            }
3124        }
3125        return out;
3126    }
3127
3128    @Override
3129    public String[] canonicalToCurrentPackageNames(String[] names) {
3130        String[] out = new String[names.length];
3131        // reader
3132        synchronized (mPackages) {
3133            for (int i=names.length-1; i>=0; i--) {
3134                String cur = mSettings.mRenamedPackages.get(names[i]);
3135                out[i] = cur != null ? cur : names[i];
3136            }
3137        }
3138        return out;
3139    }
3140
3141    @Override
3142    public int getPackageUid(String packageName, int flags, int userId) {
3143        if (!sUserManager.exists(userId)) return -1;
3144        flags = updateFlagsForPackage(flags, userId, packageName);
3145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3146                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3147
3148        // reader
3149        synchronized (mPackages) {
3150            final PackageParser.Package p = mPackages.get(packageName);
3151            if (p != null && p.isMatch(flags)) {
3152                return UserHandle.getUid(userId, p.applicationInfo.uid);
3153            }
3154            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3155                final PackageSetting ps = mSettings.mPackages.get(packageName);
3156                if (ps != null && ps.isMatch(flags)) {
3157                    return UserHandle.getUid(userId, ps.appId);
3158                }
3159            }
3160        }
3161
3162        return -1;
3163    }
3164
3165    @Override
3166    public int[] getPackageGids(String packageName, int flags, int userId) {
3167        if (!sUserManager.exists(userId)) return null;
3168        flags = updateFlagsForPackage(flags, userId, packageName);
3169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3170                false /* requireFullPermission */, false /* checkShell */,
3171                "getPackageGids");
3172
3173        // reader
3174        synchronized (mPackages) {
3175            final PackageParser.Package p = mPackages.get(packageName);
3176            if (p != null && p.isMatch(flags)) {
3177                PackageSetting ps = (PackageSetting) p.mExtras;
3178                return ps.getPermissionsState().computeGids(userId);
3179            }
3180            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3181                final PackageSetting ps = mSettings.mPackages.get(packageName);
3182                if (ps != null && ps.isMatch(flags)) {
3183                    return ps.getPermissionsState().computeGids(userId);
3184                }
3185            }
3186        }
3187
3188        return null;
3189    }
3190
3191    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3192        if (bp.perm != null) {
3193            return PackageParser.generatePermissionInfo(bp.perm, flags);
3194        }
3195        PermissionInfo pi = new PermissionInfo();
3196        pi.name = bp.name;
3197        pi.packageName = bp.sourcePackage;
3198        pi.nonLocalizedLabel = bp.name;
3199        pi.protectionLevel = bp.protectionLevel;
3200        return pi;
3201    }
3202
3203    @Override
3204    public PermissionInfo getPermissionInfo(String name, int flags) {
3205        // reader
3206        synchronized (mPackages) {
3207            final BasePermission p = mSettings.mPermissions.get(name);
3208            if (p != null) {
3209                return generatePermissionInfo(p, flags);
3210            }
3211            return null;
3212        }
3213    }
3214
3215    @Override
3216    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3217            int flags) {
3218        // reader
3219        synchronized (mPackages) {
3220            if (group != null && !mPermissionGroups.containsKey(group)) {
3221                // This is thrown as NameNotFoundException
3222                return null;
3223            }
3224
3225            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3226            for (BasePermission p : mSettings.mPermissions.values()) {
3227                if (group == null) {
3228                    if (p.perm == null || p.perm.info.group == null) {
3229                        out.add(generatePermissionInfo(p, flags));
3230                    }
3231                } else {
3232                    if (p.perm != null && group.equals(p.perm.info.group)) {
3233                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3234                    }
3235                }
3236            }
3237            return new ParceledListSlice<>(out);
3238        }
3239    }
3240
3241    @Override
3242    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3243        // reader
3244        synchronized (mPackages) {
3245            return PackageParser.generatePermissionGroupInfo(
3246                    mPermissionGroups.get(name), flags);
3247        }
3248    }
3249
3250    @Override
3251    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3252        // reader
3253        synchronized (mPackages) {
3254            final int N = mPermissionGroups.size();
3255            ArrayList<PermissionGroupInfo> out
3256                    = new ArrayList<PermissionGroupInfo>(N);
3257            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3258                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3259            }
3260            return new ParceledListSlice<>(out);
3261        }
3262    }
3263
3264    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3265            int userId) {
3266        if (!sUserManager.exists(userId)) return null;
3267        PackageSetting ps = mSettings.mPackages.get(packageName);
3268        if (ps != null) {
3269            if (ps.pkg == null) {
3270                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3271                if (pInfo != null) {
3272                    return pInfo.applicationInfo;
3273                }
3274                return null;
3275            }
3276            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3277                    ps.readUserState(userId), userId);
3278        }
3279        return null;
3280    }
3281
3282    @Override
3283    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3284        if (!sUserManager.exists(userId)) return null;
3285        flags = updateFlagsForApplication(flags, userId, packageName);
3286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3287                false /* requireFullPermission */, false /* checkShell */, "get application info");
3288        // writer
3289        synchronized (mPackages) {
3290            PackageParser.Package p = mPackages.get(packageName);
3291            if (DEBUG_PACKAGE_INFO) Log.v(
3292                    TAG, "getApplicationInfo " + packageName
3293                    + ": " + p);
3294            if (p != null) {
3295                PackageSetting ps = mSettings.mPackages.get(packageName);
3296                if (ps == null) return null;
3297                // Note: isEnabledLP() does not apply here - always return info
3298                return PackageParser.generateApplicationInfo(
3299                        p, flags, ps.readUserState(userId), userId);
3300            }
3301            if ("android".equals(packageName)||"system".equals(packageName)) {
3302                return mAndroidApplication;
3303            }
3304            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3305                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3306            }
3307        }
3308        return null;
3309    }
3310
3311    @Override
3312    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3313            final IPackageDataObserver observer) {
3314        mContext.enforceCallingOrSelfPermission(
3315                android.Manifest.permission.CLEAR_APP_CACHE, null);
3316        // Queue up an async operation since clearing cache may take a little while.
3317        mHandler.post(new Runnable() {
3318            public void run() {
3319                mHandler.removeCallbacks(this);
3320                boolean success = true;
3321                synchronized (mInstallLock) {
3322                    try {
3323                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3324                    } catch (InstallerException e) {
3325                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3326                        success = false;
3327                    }
3328                }
3329                if (observer != null) {
3330                    try {
3331                        observer.onRemoveCompleted(null, success);
3332                    } catch (RemoteException e) {
3333                        Slog.w(TAG, "RemoveException when invoking call back");
3334                    }
3335                }
3336            }
3337        });
3338    }
3339
3340    @Override
3341    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3342            final IntentSender pi) {
3343        mContext.enforceCallingOrSelfPermission(
3344                android.Manifest.permission.CLEAR_APP_CACHE, null);
3345        // Queue up an async operation since clearing cache may take a little while.
3346        mHandler.post(new Runnable() {
3347            public void run() {
3348                mHandler.removeCallbacks(this);
3349                boolean success = true;
3350                synchronized (mInstallLock) {
3351                    try {
3352                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3353                    } catch (InstallerException e) {
3354                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3355                        success = false;
3356                    }
3357                }
3358                if(pi != null) {
3359                    try {
3360                        // Callback via pending intent
3361                        int code = success ? 1 : 0;
3362                        pi.sendIntent(null, code, null,
3363                                null, null);
3364                    } catch (SendIntentException e1) {
3365                        Slog.i(TAG, "Failed to send pending intent");
3366                    }
3367                }
3368            }
3369        });
3370    }
3371
3372    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3373        synchronized (mInstallLock) {
3374            try {
3375                mInstaller.freeCache(volumeUuid, freeStorageSize);
3376            } catch (InstallerException e) {
3377                throw new IOException("Failed to free enough space", e);
3378            }
3379        }
3380    }
3381
3382    /**
3383     * Update given flags based on encryption status of current user.
3384     */
3385    private int updateFlags(int flags, int userId) {
3386        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3387                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3388            // Caller expressed an explicit opinion about what encryption
3389            // aware/unaware components they want to see, so fall through and
3390            // give them what they want
3391        } else {
3392            // Caller expressed no opinion, so match based on user state
3393            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3394                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3395            } else {
3396                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3397            }
3398        }
3399        return flags;
3400    }
3401
3402    private UserManagerInternal getUserManagerInternal() {
3403        if (mUserManagerInternal == null) {
3404            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3405        }
3406        return mUserManagerInternal;
3407    }
3408
3409    /**
3410     * Update given flags when being used to request {@link PackageInfo}.
3411     */
3412    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3413        boolean triaged = true;
3414        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3415                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3416            // Caller is asking for component details, so they'd better be
3417            // asking for specific encryption matching behavior, or be triaged
3418            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3419                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3420                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3421                triaged = false;
3422            }
3423        }
3424        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3425                | PackageManager.MATCH_SYSTEM_ONLY
3426                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3427            triaged = false;
3428        }
3429        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3430            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3431                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3432        }
3433        return updateFlags(flags, userId);
3434    }
3435
3436    /**
3437     * Update given flags when being used to request {@link ApplicationInfo}.
3438     */
3439    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3440        return updateFlagsForPackage(flags, userId, cookie);
3441    }
3442
3443    /**
3444     * Update given flags when being used to request {@link ComponentInfo}.
3445     */
3446    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3447        if (cookie instanceof Intent) {
3448            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3449                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3450            }
3451        }
3452
3453        boolean triaged = true;
3454        // Caller is asking for component details, so they'd better be
3455        // asking for specific encryption matching behavior, or be triaged
3456        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3457                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3458                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3459            triaged = false;
3460        }
3461        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3462            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3463                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3464        }
3465
3466        return updateFlags(flags, userId);
3467    }
3468
3469    /**
3470     * Update given flags when being used to request {@link ResolveInfo}.
3471     */
3472    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3473        // Safe mode means we shouldn't match any third-party components
3474        if (mSafeMode) {
3475            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3476        }
3477
3478        return updateFlagsForComponent(flags, userId, cookie);
3479    }
3480
3481    @Override
3482    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3483        if (!sUserManager.exists(userId)) return null;
3484        flags = updateFlagsForComponent(flags, userId, component);
3485        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3486                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3487        synchronized (mPackages) {
3488            PackageParser.Activity a = mActivities.mActivities.get(component);
3489
3490            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3491            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3492                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3493                if (ps == null) return null;
3494                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3495                        userId);
3496            }
3497            if (mResolveComponentName.equals(component)) {
3498                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3499                        new PackageUserState(), userId);
3500            }
3501        }
3502        return null;
3503    }
3504
3505    @Override
3506    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3507            String resolvedType) {
3508        synchronized (mPackages) {
3509            if (component.equals(mResolveComponentName)) {
3510                // The resolver supports EVERYTHING!
3511                return true;
3512            }
3513            PackageParser.Activity a = mActivities.mActivities.get(component);
3514            if (a == null) {
3515                return false;
3516            }
3517            for (int i=0; i<a.intents.size(); i++) {
3518                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3519                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3520                    return true;
3521                }
3522            }
3523            return false;
3524        }
3525    }
3526
3527    @Override
3528    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3529        if (!sUserManager.exists(userId)) return null;
3530        flags = updateFlagsForComponent(flags, userId, component);
3531        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3532                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3533        synchronized (mPackages) {
3534            PackageParser.Activity a = mReceivers.mActivities.get(component);
3535            if (DEBUG_PACKAGE_INFO) Log.v(
3536                TAG, "getReceiverInfo " + component + ": " + a);
3537            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3538                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3539                if (ps == null) return null;
3540                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3541                        userId);
3542            }
3543        }
3544        return null;
3545    }
3546
3547    @Override
3548    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3549        if (!sUserManager.exists(userId)) return null;
3550        flags = updateFlagsForComponent(flags, userId, component);
3551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3552                false /* requireFullPermission */, false /* checkShell */, "get service info");
3553        synchronized (mPackages) {
3554            PackageParser.Service s = mServices.mServices.get(component);
3555            if (DEBUG_PACKAGE_INFO) Log.v(
3556                TAG, "getServiceInfo " + component + ": " + s);
3557            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3558                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3559                if (ps == null) return null;
3560                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3561                        userId);
3562            }
3563        }
3564        return null;
3565    }
3566
3567    @Override
3568    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3569        if (!sUserManager.exists(userId)) return null;
3570        flags = updateFlagsForComponent(flags, userId, component);
3571        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3572                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3573        synchronized (mPackages) {
3574            PackageParser.Provider p = mProviders.mProviders.get(component);
3575            if (DEBUG_PACKAGE_INFO) Log.v(
3576                TAG, "getProviderInfo " + component + ": " + p);
3577            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3578                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3579                if (ps == null) return null;
3580                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3581                        userId);
3582            }
3583        }
3584        return null;
3585    }
3586
3587    @Override
3588    public String[] getSystemSharedLibraryNames() {
3589        Set<String> libSet;
3590        synchronized (mPackages) {
3591            libSet = mSharedLibraries.keySet();
3592            int size = libSet.size();
3593            if (size > 0) {
3594                String[] libs = new String[size];
3595                libSet.toArray(libs);
3596                return libs;
3597            }
3598        }
3599        return null;
3600    }
3601
3602    @Override
3603    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3604        synchronized (mPackages) {
3605            return mServicesSystemSharedLibraryPackageName;
3606        }
3607    }
3608
3609    @Override
3610    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3611        synchronized (mPackages) {
3612            return mSharedSystemSharedLibraryPackageName;
3613        }
3614    }
3615
3616    @Override
3617    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3618        synchronized (mPackages) {
3619            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3620
3621            final FeatureInfo fi = new FeatureInfo();
3622            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3623                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3624            res.add(fi);
3625
3626            return new ParceledListSlice<>(res);
3627        }
3628    }
3629
3630    @Override
3631    public boolean hasSystemFeature(String name, int version) {
3632        synchronized (mPackages) {
3633            final FeatureInfo feat = mAvailableFeatures.get(name);
3634            if (feat == null) {
3635                return false;
3636            } else {
3637                return feat.version >= version;
3638            }
3639        }
3640    }
3641
3642    @Override
3643    public int checkPermission(String permName, String pkgName, int userId) {
3644        if (!sUserManager.exists(userId)) {
3645            return PackageManager.PERMISSION_DENIED;
3646        }
3647
3648        synchronized (mPackages) {
3649            final PackageParser.Package p = mPackages.get(pkgName);
3650            if (p != null && p.mExtras != null) {
3651                final PackageSetting ps = (PackageSetting) p.mExtras;
3652                final PermissionsState permissionsState = ps.getPermissionsState();
3653                if (permissionsState.hasPermission(permName, userId)) {
3654                    return PackageManager.PERMISSION_GRANTED;
3655                }
3656                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3657                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3658                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3659                    return PackageManager.PERMISSION_GRANTED;
3660                }
3661            }
3662        }
3663
3664        return PackageManager.PERMISSION_DENIED;
3665    }
3666
3667    @Override
3668    public int checkUidPermission(String permName, int uid) {
3669        final int userId = UserHandle.getUserId(uid);
3670
3671        if (!sUserManager.exists(userId)) {
3672            return PackageManager.PERMISSION_DENIED;
3673        }
3674
3675        synchronized (mPackages) {
3676            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3677            if (obj != null) {
3678                final SettingBase ps = (SettingBase) obj;
3679                final PermissionsState permissionsState = ps.getPermissionsState();
3680                if (permissionsState.hasPermission(permName, userId)) {
3681                    return PackageManager.PERMISSION_GRANTED;
3682                }
3683                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3684                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3685                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3686                    return PackageManager.PERMISSION_GRANTED;
3687                }
3688            } else {
3689                ArraySet<String> perms = mSystemPermissions.get(uid);
3690                if (perms != null) {
3691                    if (perms.contains(permName)) {
3692                        return PackageManager.PERMISSION_GRANTED;
3693                    }
3694                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3695                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3696                        return PackageManager.PERMISSION_GRANTED;
3697                    }
3698                }
3699            }
3700        }
3701
3702        return PackageManager.PERMISSION_DENIED;
3703    }
3704
3705    @Override
3706    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3707        if (UserHandle.getCallingUserId() != userId) {
3708            mContext.enforceCallingPermission(
3709                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3710                    "isPermissionRevokedByPolicy for user " + userId);
3711        }
3712
3713        if (checkPermission(permission, packageName, userId)
3714                == PackageManager.PERMISSION_GRANTED) {
3715            return false;
3716        }
3717
3718        final long identity = Binder.clearCallingIdentity();
3719        try {
3720            final int flags = getPermissionFlags(permission, packageName, userId);
3721            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3722        } finally {
3723            Binder.restoreCallingIdentity(identity);
3724        }
3725    }
3726
3727    @Override
3728    public String getPermissionControllerPackageName() {
3729        synchronized (mPackages) {
3730            return mRequiredInstallerPackage;
3731        }
3732    }
3733
3734    /**
3735     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3736     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3737     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3738     * @param message the message to log on security exception
3739     */
3740    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3741            boolean checkShell, String message) {
3742        if (userId < 0) {
3743            throw new IllegalArgumentException("Invalid userId " + userId);
3744        }
3745        if (checkShell) {
3746            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3747        }
3748        if (userId == UserHandle.getUserId(callingUid)) return;
3749        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3750            if (requireFullPermission) {
3751                mContext.enforceCallingOrSelfPermission(
3752                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3753            } else {
3754                try {
3755                    mContext.enforceCallingOrSelfPermission(
3756                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3757                } catch (SecurityException se) {
3758                    mContext.enforceCallingOrSelfPermission(
3759                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3760                }
3761            }
3762        }
3763    }
3764
3765    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3766        if (callingUid == Process.SHELL_UID) {
3767            if (userHandle >= 0
3768                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3769                throw new SecurityException("Shell does not have permission to access user "
3770                        + userHandle);
3771            } else if (userHandle < 0) {
3772                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3773                        + Debug.getCallers(3));
3774            }
3775        }
3776    }
3777
3778    private BasePermission findPermissionTreeLP(String permName) {
3779        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3780            if (permName.startsWith(bp.name) &&
3781                    permName.length() > bp.name.length() &&
3782                    permName.charAt(bp.name.length()) == '.') {
3783                return bp;
3784            }
3785        }
3786        return null;
3787    }
3788
3789    private BasePermission checkPermissionTreeLP(String permName) {
3790        if (permName != null) {
3791            BasePermission bp = findPermissionTreeLP(permName);
3792            if (bp != null) {
3793                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3794                    return bp;
3795                }
3796                throw new SecurityException("Calling uid "
3797                        + Binder.getCallingUid()
3798                        + " is not allowed to add to permission tree "
3799                        + bp.name + " owned by uid " + bp.uid);
3800            }
3801        }
3802        throw new SecurityException("No permission tree found for " + permName);
3803    }
3804
3805    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3806        if (s1 == null) {
3807            return s2 == null;
3808        }
3809        if (s2 == null) {
3810            return false;
3811        }
3812        if (s1.getClass() != s2.getClass()) {
3813            return false;
3814        }
3815        return s1.equals(s2);
3816    }
3817
3818    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3819        if (pi1.icon != pi2.icon) return false;
3820        if (pi1.logo != pi2.logo) return false;
3821        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3822        if (!compareStrings(pi1.name, pi2.name)) return false;
3823        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3824        // We'll take care of setting this one.
3825        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3826        // These are not currently stored in settings.
3827        //if (!compareStrings(pi1.group, pi2.group)) return false;
3828        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3829        //if (pi1.labelRes != pi2.labelRes) return false;
3830        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3831        return true;
3832    }
3833
3834    int permissionInfoFootprint(PermissionInfo info) {
3835        int size = info.name.length();
3836        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3837        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3838        return size;
3839    }
3840
3841    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3842        int size = 0;
3843        for (BasePermission perm : mSettings.mPermissions.values()) {
3844            if (perm.uid == tree.uid) {
3845                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3846            }
3847        }
3848        return size;
3849    }
3850
3851    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3852        // We calculate the max size of permissions defined by this uid and throw
3853        // if that plus the size of 'info' would exceed our stated maximum.
3854        if (tree.uid != Process.SYSTEM_UID) {
3855            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3856            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3857                throw new SecurityException("Permission tree size cap exceeded");
3858            }
3859        }
3860    }
3861
3862    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3863        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3864            throw new SecurityException("Label must be specified in permission");
3865        }
3866        BasePermission tree = checkPermissionTreeLP(info.name);
3867        BasePermission bp = mSettings.mPermissions.get(info.name);
3868        boolean added = bp == null;
3869        boolean changed = true;
3870        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3871        if (added) {
3872            enforcePermissionCapLocked(info, tree);
3873            bp = new BasePermission(info.name, tree.sourcePackage,
3874                    BasePermission.TYPE_DYNAMIC);
3875        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3876            throw new SecurityException(
3877                    "Not allowed to modify non-dynamic permission "
3878                    + info.name);
3879        } else {
3880            if (bp.protectionLevel == fixedLevel
3881                    && bp.perm.owner.equals(tree.perm.owner)
3882                    && bp.uid == tree.uid
3883                    && comparePermissionInfos(bp.perm.info, info)) {
3884                changed = false;
3885            }
3886        }
3887        bp.protectionLevel = fixedLevel;
3888        info = new PermissionInfo(info);
3889        info.protectionLevel = fixedLevel;
3890        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3891        bp.perm.info.packageName = tree.perm.info.packageName;
3892        bp.uid = tree.uid;
3893        if (added) {
3894            mSettings.mPermissions.put(info.name, bp);
3895        }
3896        if (changed) {
3897            if (!async) {
3898                mSettings.writeLPr();
3899            } else {
3900                scheduleWriteSettingsLocked();
3901            }
3902        }
3903        return added;
3904    }
3905
3906    @Override
3907    public boolean addPermission(PermissionInfo info) {
3908        synchronized (mPackages) {
3909            return addPermissionLocked(info, false);
3910        }
3911    }
3912
3913    @Override
3914    public boolean addPermissionAsync(PermissionInfo info) {
3915        synchronized (mPackages) {
3916            return addPermissionLocked(info, true);
3917        }
3918    }
3919
3920    @Override
3921    public void removePermission(String name) {
3922        synchronized (mPackages) {
3923            checkPermissionTreeLP(name);
3924            BasePermission bp = mSettings.mPermissions.get(name);
3925            if (bp != null) {
3926                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3927                    throw new SecurityException(
3928                            "Not allowed to modify non-dynamic permission "
3929                            + name);
3930                }
3931                mSettings.mPermissions.remove(name);
3932                mSettings.writeLPr();
3933            }
3934        }
3935    }
3936
3937    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3938            BasePermission bp) {
3939        int index = pkg.requestedPermissions.indexOf(bp.name);
3940        if (index == -1) {
3941            throw new SecurityException("Package " + pkg.packageName
3942                    + " has not requested permission " + bp.name);
3943        }
3944        if (!bp.isRuntime() && !bp.isDevelopment()) {
3945            throw new SecurityException("Permission " + bp.name
3946                    + " is not a changeable permission type");
3947        }
3948    }
3949
3950    @Override
3951    public void grantRuntimePermission(String packageName, String name, final int userId) {
3952        if (!sUserManager.exists(userId)) {
3953            Log.e(TAG, "No such user:" + userId);
3954            return;
3955        }
3956
3957        mContext.enforceCallingOrSelfPermission(
3958                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3959                "grantRuntimePermission");
3960
3961        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3962                true /* requireFullPermission */, true /* checkShell */,
3963                "grantRuntimePermission");
3964
3965        final int uid;
3966        final SettingBase sb;
3967
3968        synchronized (mPackages) {
3969            final PackageParser.Package pkg = mPackages.get(packageName);
3970            if (pkg == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            final BasePermission bp = mSettings.mPermissions.get(name);
3975            if (bp == null) {
3976                throw new IllegalArgumentException("Unknown permission: " + name);
3977            }
3978
3979            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3980
3981            // If a permission review is required for legacy apps we represent
3982            // their permissions as always granted runtime ones since we need
3983            // to keep the review required permission flag per user while an
3984            // install permission's state is shared across all users.
3985            if (Build.PERMISSIONS_REVIEW_REQUIRED
3986                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3987                    && bp.isRuntime()) {
3988                return;
3989            }
3990
3991            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3992            sb = (SettingBase) pkg.mExtras;
3993            if (sb == null) {
3994                throw new IllegalArgumentException("Unknown package: " + packageName);
3995            }
3996
3997            final PermissionsState permissionsState = sb.getPermissionsState();
3998
3999            final int flags = permissionsState.getPermissionFlags(name, userId);
4000            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4001                throw new SecurityException("Cannot grant system fixed permission "
4002                        + name + " for package " + packageName);
4003            }
4004
4005            if (bp.isDevelopment()) {
4006                // Development permissions must be handled specially, since they are not
4007                // normal runtime permissions.  For now they apply to all users.
4008                if (permissionsState.grantInstallPermission(bp) !=
4009                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4010                    scheduleWriteSettingsLocked();
4011                }
4012                return;
4013            }
4014
4015            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4016                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4017                return;
4018            }
4019
4020            final int result = permissionsState.grantRuntimePermission(bp, userId);
4021            switch (result) {
4022                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4023                    return;
4024                }
4025
4026                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4027                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4028                    mHandler.post(new Runnable() {
4029                        @Override
4030                        public void run() {
4031                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4032                        }
4033                    });
4034                }
4035                break;
4036            }
4037
4038            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4039
4040            // Not critical if that is lost - app has to request again.
4041            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4042        }
4043
4044        // Only need to do this if user is initialized. Otherwise it's a new user
4045        // and there are no processes running as the user yet and there's no need
4046        // to make an expensive call to remount processes for the changed permissions.
4047        if (READ_EXTERNAL_STORAGE.equals(name)
4048                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4049            final long token = Binder.clearCallingIdentity();
4050            try {
4051                if (sUserManager.isInitialized(userId)) {
4052                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4053                            MountServiceInternal.class);
4054                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4055                }
4056            } finally {
4057                Binder.restoreCallingIdentity(token);
4058            }
4059        }
4060    }
4061
4062    @Override
4063    public void revokeRuntimePermission(String packageName, String name, int userId) {
4064        if (!sUserManager.exists(userId)) {
4065            Log.e(TAG, "No such user:" + userId);
4066            return;
4067        }
4068
4069        mContext.enforceCallingOrSelfPermission(
4070                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4071                "revokeRuntimePermission");
4072
4073        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4074                true /* requireFullPermission */, true /* checkShell */,
4075                "revokeRuntimePermission");
4076
4077        final int appId;
4078
4079        synchronized (mPackages) {
4080            final PackageParser.Package pkg = mPackages.get(packageName);
4081            if (pkg == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final BasePermission bp = mSettings.mPermissions.get(name);
4086            if (bp == null) {
4087                throw new IllegalArgumentException("Unknown permission: " + name);
4088            }
4089
4090            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4091
4092            // If a permission review is required for legacy apps we represent
4093            // their permissions as always granted runtime ones since we need
4094            // to keep the review required permission flag per user while an
4095            // install permission's state is shared across all users.
4096            if (Build.PERMISSIONS_REVIEW_REQUIRED
4097                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4098                    && bp.isRuntime()) {
4099                return;
4100            }
4101
4102            SettingBase sb = (SettingBase) pkg.mExtras;
4103            if (sb == null) {
4104                throw new IllegalArgumentException("Unknown package: " + packageName);
4105            }
4106
4107            final PermissionsState permissionsState = sb.getPermissionsState();
4108
4109            final int flags = permissionsState.getPermissionFlags(name, userId);
4110            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4111                throw new SecurityException("Cannot revoke system fixed permission "
4112                        + name + " for package " + packageName);
4113            }
4114
4115            if (bp.isDevelopment()) {
4116                // Development permissions must be handled specially, since they are not
4117                // normal runtime permissions.  For now they apply to all users.
4118                if (permissionsState.revokeInstallPermission(bp) !=
4119                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4120                    scheduleWriteSettingsLocked();
4121                }
4122                return;
4123            }
4124
4125            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4126                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4127                return;
4128            }
4129
4130            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4131
4132            // Critical, after this call app should never have the permission.
4133            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4134
4135            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4136        }
4137
4138        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4139    }
4140
4141    @Override
4142    public void resetRuntimePermissions() {
4143        mContext.enforceCallingOrSelfPermission(
4144                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4145                "revokeRuntimePermission");
4146
4147        int callingUid = Binder.getCallingUid();
4148        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4149            mContext.enforceCallingOrSelfPermission(
4150                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4151                    "resetRuntimePermissions");
4152        }
4153
4154        synchronized (mPackages) {
4155            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4156            for (int userId : UserManagerService.getInstance().getUserIds()) {
4157                final int packageCount = mPackages.size();
4158                for (int i = 0; i < packageCount; i++) {
4159                    PackageParser.Package pkg = mPackages.valueAt(i);
4160                    if (!(pkg.mExtras instanceof PackageSetting)) {
4161                        continue;
4162                    }
4163                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4164                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4165                }
4166            }
4167        }
4168    }
4169
4170    @Override
4171    public int getPermissionFlags(String name, String packageName, int userId) {
4172        if (!sUserManager.exists(userId)) {
4173            return 0;
4174        }
4175
4176        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4177
4178        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4179                true /* requireFullPermission */, false /* checkShell */,
4180                "getPermissionFlags");
4181
4182        synchronized (mPackages) {
4183            final PackageParser.Package pkg = mPackages.get(packageName);
4184            if (pkg == null) {
4185                return 0;
4186            }
4187
4188            final BasePermission bp = mSettings.mPermissions.get(name);
4189            if (bp == null) {
4190                return 0;
4191            }
4192
4193            SettingBase sb = (SettingBase) pkg.mExtras;
4194            if (sb == null) {
4195                return 0;
4196            }
4197
4198            PermissionsState permissionsState = sb.getPermissionsState();
4199            return permissionsState.getPermissionFlags(name, userId);
4200        }
4201    }
4202
4203    @Override
4204    public void updatePermissionFlags(String name, String packageName, int flagMask,
4205            int flagValues, int userId) {
4206        if (!sUserManager.exists(userId)) {
4207            return;
4208        }
4209
4210        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4211
4212        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4213                true /* requireFullPermission */, true /* checkShell */,
4214                "updatePermissionFlags");
4215
4216        // Only the system can change these flags and nothing else.
4217        if (getCallingUid() != Process.SYSTEM_UID) {
4218            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4219            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4220            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4221            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4222            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4223        }
4224
4225        synchronized (mPackages) {
4226            final PackageParser.Package pkg = mPackages.get(packageName);
4227            if (pkg == null) {
4228                throw new IllegalArgumentException("Unknown package: " + packageName);
4229            }
4230
4231            final BasePermission bp = mSettings.mPermissions.get(name);
4232            if (bp == null) {
4233                throw new IllegalArgumentException("Unknown permission: " + name);
4234            }
4235
4236            SettingBase sb = (SettingBase) pkg.mExtras;
4237            if (sb == null) {
4238                throw new IllegalArgumentException("Unknown package: " + packageName);
4239            }
4240
4241            PermissionsState permissionsState = sb.getPermissionsState();
4242
4243            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4244
4245            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4246                // Install and runtime permissions are stored in different places,
4247                // so figure out what permission changed and persist the change.
4248                if (permissionsState.getInstallPermissionState(name) != null) {
4249                    scheduleWriteSettingsLocked();
4250                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4251                        || hadState) {
4252                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4253                }
4254            }
4255        }
4256    }
4257
4258    /**
4259     * Update the permission flags for all packages and runtime permissions of a user in order
4260     * to allow device or profile owner to remove POLICY_FIXED.
4261     */
4262    @Override
4263    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4264        if (!sUserManager.exists(userId)) {
4265            return;
4266        }
4267
4268        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4269
4270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4271                true /* requireFullPermission */, true /* checkShell */,
4272                "updatePermissionFlagsForAllApps");
4273
4274        // Only the system can change system fixed flags.
4275        if (getCallingUid() != Process.SYSTEM_UID) {
4276            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4277            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4278        }
4279
4280        synchronized (mPackages) {
4281            boolean changed = false;
4282            final int packageCount = mPackages.size();
4283            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4284                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4285                SettingBase sb = (SettingBase) pkg.mExtras;
4286                if (sb == null) {
4287                    continue;
4288                }
4289                PermissionsState permissionsState = sb.getPermissionsState();
4290                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4291                        userId, flagMask, flagValues);
4292            }
4293            if (changed) {
4294                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4295            }
4296        }
4297    }
4298
4299    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4300        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4301                != PackageManager.PERMISSION_GRANTED
4302            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4303                != PackageManager.PERMISSION_GRANTED) {
4304            throw new SecurityException(message + " requires "
4305                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4306                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4307        }
4308    }
4309
4310    @Override
4311    public boolean shouldShowRequestPermissionRationale(String permissionName,
4312            String packageName, int userId) {
4313        if (UserHandle.getCallingUserId() != userId) {
4314            mContext.enforceCallingPermission(
4315                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4316                    "canShowRequestPermissionRationale for user " + userId);
4317        }
4318
4319        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4320        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4321            return false;
4322        }
4323
4324        if (checkPermission(permissionName, packageName, userId)
4325                == PackageManager.PERMISSION_GRANTED) {
4326            return false;
4327        }
4328
4329        final int flags;
4330
4331        final long identity = Binder.clearCallingIdentity();
4332        try {
4333            flags = getPermissionFlags(permissionName,
4334                    packageName, userId);
4335        } finally {
4336            Binder.restoreCallingIdentity(identity);
4337        }
4338
4339        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4340                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4341                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4342
4343        if ((flags & fixedFlags) != 0) {
4344            return false;
4345        }
4346
4347        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4348    }
4349
4350    @Override
4351    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4352        mContext.enforceCallingOrSelfPermission(
4353                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4354                "addOnPermissionsChangeListener");
4355
4356        synchronized (mPackages) {
4357            mOnPermissionChangeListeners.addListenerLocked(listener);
4358        }
4359    }
4360
4361    @Override
4362    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4363        synchronized (mPackages) {
4364            mOnPermissionChangeListeners.removeListenerLocked(listener);
4365        }
4366    }
4367
4368    @Override
4369    public boolean isProtectedBroadcast(String actionName) {
4370        synchronized (mPackages) {
4371            if (mProtectedBroadcasts.contains(actionName)) {
4372                return true;
4373            } else if (actionName != null) {
4374                // TODO: remove these terrible hacks
4375                if (actionName.startsWith("android.net.netmon.lingerExpired")
4376                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4377                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4378                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4379                    return true;
4380                }
4381            }
4382        }
4383        return false;
4384    }
4385
4386    @Override
4387    public int checkSignatures(String pkg1, String pkg2) {
4388        synchronized (mPackages) {
4389            final PackageParser.Package p1 = mPackages.get(pkg1);
4390            final PackageParser.Package p2 = mPackages.get(pkg2);
4391            if (p1 == null || p1.mExtras == null
4392                    || p2 == null || p2.mExtras == null) {
4393                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4394            }
4395            return compareSignatures(p1.mSignatures, p2.mSignatures);
4396        }
4397    }
4398
4399    @Override
4400    public int checkUidSignatures(int uid1, int uid2) {
4401        // Map to base uids.
4402        uid1 = UserHandle.getAppId(uid1);
4403        uid2 = UserHandle.getAppId(uid2);
4404        // reader
4405        synchronized (mPackages) {
4406            Signature[] s1;
4407            Signature[] s2;
4408            Object obj = mSettings.getUserIdLPr(uid1);
4409            if (obj != null) {
4410                if (obj instanceof SharedUserSetting) {
4411                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4412                } else if (obj instanceof PackageSetting) {
4413                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4414                } else {
4415                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4416                }
4417            } else {
4418                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4419            }
4420            obj = mSettings.getUserIdLPr(uid2);
4421            if (obj != null) {
4422                if (obj instanceof SharedUserSetting) {
4423                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4424                } else if (obj instanceof PackageSetting) {
4425                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4426                } else {
4427                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4428                }
4429            } else {
4430                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4431            }
4432            return compareSignatures(s1, s2);
4433        }
4434    }
4435
4436    /**
4437     * This method should typically only be used when granting or revoking
4438     * permissions, since the app may immediately restart after this call.
4439     * <p>
4440     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4441     * guard your work against the app being relaunched.
4442     */
4443    private void killUid(int appId, int userId, String reason) {
4444        final long identity = Binder.clearCallingIdentity();
4445        try {
4446            IActivityManager am = ActivityManagerNative.getDefault();
4447            if (am != null) {
4448                try {
4449                    am.killUid(appId, userId, reason);
4450                } catch (RemoteException e) {
4451                    /* ignore - same process */
4452                }
4453            }
4454        } finally {
4455            Binder.restoreCallingIdentity(identity);
4456        }
4457    }
4458
4459    /**
4460     * Compares two sets of signatures. Returns:
4461     * <br />
4462     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4463     * <br />
4464     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4465     * <br />
4466     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4467     * <br />
4468     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4469     * <br />
4470     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4471     */
4472    static int compareSignatures(Signature[] s1, Signature[] s2) {
4473        if (s1 == null) {
4474            return s2 == null
4475                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4476                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4477        }
4478
4479        if (s2 == null) {
4480            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4481        }
4482
4483        if (s1.length != s2.length) {
4484            return PackageManager.SIGNATURE_NO_MATCH;
4485        }
4486
4487        // Since both signature sets are of size 1, we can compare without HashSets.
4488        if (s1.length == 1) {
4489            return s1[0].equals(s2[0]) ?
4490                    PackageManager.SIGNATURE_MATCH :
4491                    PackageManager.SIGNATURE_NO_MATCH;
4492        }
4493
4494        ArraySet<Signature> set1 = new ArraySet<Signature>();
4495        for (Signature sig : s1) {
4496            set1.add(sig);
4497        }
4498        ArraySet<Signature> set2 = new ArraySet<Signature>();
4499        for (Signature sig : s2) {
4500            set2.add(sig);
4501        }
4502        // Make sure s2 contains all signatures in s1.
4503        if (set1.equals(set2)) {
4504            return PackageManager.SIGNATURE_MATCH;
4505        }
4506        return PackageManager.SIGNATURE_NO_MATCH;
4507    }
4508
4509    /**
4510     * If the database version for this type of package (internal storage or
4511     * external storage) is less than the version where package signatures
4512     * were updated, return true.
4513     */
4514    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4515        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4516        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4517    }
4518
4519    /**
4520     * Used for backward compatibility to make sure any packages with
4521     * certificate chains get upgraded to the new style. {@code existingSigs}
4522     * will be in the old format (since they were stored on disk from before the
4523     * system upgrade) and {@code scannedSigs} will be in the newer format.
4524     */
4525    private int compareSignaturesCompat(PackageSignatures existingSigs,
4526            PackageParser.Package scannedPkg) {
4527        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4528            return PackageManager.SIGNATURE_NO_MATCH;
4529        }
4530
4531        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4532        for (Signature sig : existingSigs.mSignatures) {
4533            existingSet.add(sig);
4534        }
4535        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4536        for (Signature sig : scannedPkg.mSignatures) {
4537            try {
4538                Signature[] chainSignatures = sig.getChainSignatures();
4539                for (Signature chainSig : chainSignatures) {
4540                    scannedCompatSet.add(chainSig);
4541                }
4542            } catch (CertificateEncodingException e) {
4543                scannedCompatSet.add(sig);
4544            }
4545        }
4546        /*
4547         * Make sure the expanded scanned set contains all signatures in the
4548         * existing one.
4549         */
4550        if (scannedCompatSet.equals(existingSet)) {
4551            // Migrate the old signatures to the new scheme.
4552            existingSigs.assignSignatures(scannedPkg.mSignatures);
4553            // The new KeySets will be re-added later in the scanning process.
4554            synchronized (mPackages) {
4555                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4556            }
4557            return PackageManager.SIGNATURE_MATCH;
4558        }
4559        return PackageManager.SIGNATURE_NO_MATCH;
4560    }
4561
4562    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4563        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4564        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4565    }
4566
4567    private int compareSignaturesRecover(PackageSignatures existingSigs,
4568            PackageParser.Package scannedPkg) {
4569        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4570            return PackageManager.SIGNATURE_NO_MATCH;
4571        }
4572
4573        String msg = null;
4574        try {
4575            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4576                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4577                        + scannedPkg.packageName);
4578                return PackageManager.SIGNATURE_MATCH;
4579            }
4580        } catch (CertificateException e) {
4581            msg = e.getMessage();
4582        }
4583
4584        logCriticalInfo(Log.INFO,
4585                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4586        return PackageManager.SIGNATURE_NO_MATCH;
4587    }
4588
4589    @Override
4590    public List<String> getAllPackages() {
4591        synchronized (mPackages) {
4592            return new ArrayList<String>(mPackages.keySet());
4593        }
4594    }
4595
4596    @Override
4597    public String[] getPackagesForUid(int uid) {
4598        uid = UserHandle.getAppId(uid);
4599        // reader
4600        synchronized (mPackages) {
4601            Object obj = mSettings.getUserIdLPr(uid);
4602            if (obj instanceof SharedUserSetting) {
4603                final SharedUserSetting sus = (SharedUserSetting) obj;
4604                final int N = sus.packages.size();
4605                final String[] res = new String[N];
4606                for (int i = 0; i < N; i++) {
4607                    res[i] = sus.packages.valueAt(i).name;
4608                }
4609                return res;
4610            } else if (obj instanceof PackageSetting) {
4611                final PackageSetting ps = (PackageSetting) obj;
4612                return new String[] { ps.name };
4613            }
4614        }
4615        return null;
4616    }
4617
4618    @Override
4619    public String getNameForUid(int uid) {
4620        // reader
4621        synchronized (mPackages) {
4622            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4623            if (obj instanceof SharedUserSetting) {
4624                final SharedUserSetting sus = (SharedUserSetting) obj;
4625                return sus.name + ":" + sus.userId;
4626            } else if (obj instanceof PackageSetting) {
4627                final PackageSetting ps = (PackageSetting) obj;
4628                return ps.name;
4629            }
4630        }
4631        return null;
4632    }
4633
4634    @Override
4635    public int getUidForSharedUser(String sharedUserName) {
4636        if(sharedUserName == null) {
4637            return -1;
4638        }
4639        // reader
4640        synchronized (mPackages) {
4641            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4642            if (suid == null) {
4643                return -1;
4644            }
4645            return suid.userId;
4646        }
4647    }
4648
4649    @Override
4650    public int getFlagsForUid(int uid) {
4651        synchronized (mPackages) {
4652            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4653            if (obj instanceof SharedUserSetting) {
4654                final SharedUserSetting sus = (SharedUserSetting) obj;
4655                return sus.pkgFlags;
4656            } else if (obj instanceof PackageSetting) {
4657                final PackageSetting ps = (PackageSetting) obj;
4658                return ps.pkgFlags;
4659            }
4660        }
4661        return 0;
4662    }
4663
4664    @Override
4665    public int getPrivateFlagsForUid(int uid) {
4666        synchronized (mPackages) {
4667            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4668            if (obj instanceof SharedUserSetting) {
4669                final SharedUserSetting sus = (SharedUserSetting) obj;
4670                return sus.pkgPrivateFlags;
4671            } else if (obj instanceof PackageSetting) {
4672                final PackageSetting ps = (PackageSetting) obj;
4673                return ps.pkgPrivateFlags;
4674            }
4675        }
4676        return 0;
4677    }
4678
4679    @Override
4680    public boolean isUidPrivileged(int uid) {
4681        uid = UserHandle.getAppId(uid);
4682        // reader
4683        synchronized (mPackages) {
4684            Object obj = mSettings.getUserIdLPr(uid);
4685            if (obj instanceof SharedUserSetting) {
4686                final SharedUserSetting sus = (SharedUserSetting) obj;
4687                final Iterator<PackageSetting> it = sus.packages.iterator();
4688                while (it.hasNext()) {
4689                    if (it.next().isPrivileged()) {
4690                        return true;
4691                    }
4692                }
4693            } else if (obj instanceof PackageSetting) {
4694                final PackageSetting ps = (PackageSetting) obj;
4695                return ps.isPrivileged();
4696            }
4697        }
4698        return false;
4699    }
4700
4701    @Override
4702    public String[] getAppOpPermissionPackages(String permissionName) {
4703        synchronized (mPackages) {
4704            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4705            if (pkgs == null) {
4706                return null;
4707            }
4708            return pkgs.toArray(new String[pkgs.size()]);
4709        }
4710    }
4711
4712    @Override
4713    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4714            int flags, int userId) {
4715        try {
4716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4717
4718            if (!sUserManager.exists(userId)) return null;
4719            flags = updateFlagsForResolve(flags, userId, intent);
4720            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4721                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4722
4723            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4724            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4725                    flags, userId);
4726            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4727
4728            final ResolveInfo bestChoice =
4729                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4730
4731            if (isEphemeralAllowed(intent, query, userId)) {
4732                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4733                final EphemeralResolveInfo ai =
4734                        getEphemeralResolveInfo(intent, resolvedType, userId);
4735                if (ai != null) {
4736                    if (DEBUG_EPHEMERAL) {
4737                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4738                    }
4739                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4740                    bestChoice.ephemeralResolveInfo = ai;
4741                }
4742                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4743            }
4744            return bestChoice;
4745        } finally {
4746            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4747        }
4748    }
4749
4750    @Override
4751    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4752            IntentFilter filter, int match, ComponentName activity) {
4753        final int userId = UserHandle.getCallingUserId();
4754        if (DEBUG_PREFERRED) {
4755            Log.v(TAG, "setLastChosenActivity intent=" + intent
4756                + " resolvedType=" + resolvedType
4757                + " flags=" + flags
4758                + " filter=" + filter
4759                + " match=" + match
4760                + " activity=" + activity);
4761            filter.dump(new PrintStreamPrinter(System.out), "    ");
4762        }
4763        intent.setComponent(null);
4764        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4765                userId);
4766        // Find any earlier preferred or last chosen entries and nuke them
4767        findPreferredActivity(intent, resolvedType,
4768                flags, query, 0, false, true, false, userId);
4769        // Add the new activity as the last chosen for this filter
4770        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4771                "Setting last chosen");
4772    }
4773
4774    @Override
4775    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4776        final int userId = UserHandle.getCallingUserId();
4777        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4778        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4779                userId);
4780        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4781                false, false, false, userId);
4782    }
4783
4784
4785    private boolean isEphemeralAllowed(
4786            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4787        // Short circuit and return early if possible.
4788        if (DISABLE_EPHEMERAL_APPS) {
4789            return false;
4790        }
4791        final int callingUser = UserHandle.getCallingUserId();
4792        if (callingUser != UserHandle.USER_SYSTEM) {
4793            return false;
4794        }
4795        if (mEphemeralResolverConnection == null) {
4796            return false;
4797        }
4798        if (intent.getComponent() != null) {
4799            return false;
4800        }
4801        if (intent.getPackage() != null) {
4802            return false;
4803        }
4804        final boolean isWebUri = hasWebURI(intent);
4805        if (!isWebUri) {
4806            return false;
4807        }
4808        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4809        synchronized (mPackages) {
4810            final int count = resolvedActivites.size();
4811            for (int n = 0; n < count; n++) {
4812                ResolveInfo info = resolvedActivites.get(n);
4813                String packageName = info.activityInfo.packageName;
4814                PackageSetting ps = mSettings.mPackages.get(packageName);
4815                if (ps != null) {
4816                    // Try to get the status from User settings first
4817                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4818                    int status = (int) (packedStatus >> 32);
4819                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4820                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4821                        if (DEBUG_EPHEMERAL) {
4822                            Slog.v(TAG, "DENY ephemeral apps;"
4823                                + " pkg: " + packageName + ", status: " + status);
4824                        }
4825                        return false;
4826                    }
4827                }
4828            }
4829        }
4830        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4831        return true;
4832    }
4833
4834    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4835            int userId) {
4836        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
4837                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4838        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
4839                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4840        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4841                ephemeralPrefixCount);
4842        final int[] shaPrefix = digest.getDigestPrefix();
4843        final byte[][] digestBytes = digest.getDigestBytes();
4844        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4845                mEphemeralResolverConnection.getEphemeralResolveInfoList(
4846                        shaPrefix, ephemeralPrefixMask);
4847        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4848            // No hash prefix match; there are no ephemeral apps for this domain.
4849            return null;
4850        }
4851
4852        // Go in reverse order so we match the narrowest scope first.
4853        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4854            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4855                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4856                    continue;
4857                }
4858                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4859                // No filters; this should never happen.
4860                if (filters.isEmpty()) {
4861                    continue;
4862                }
4863                // We have a domain match; resolve the filters to see if anything matches.
4864                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4865                for (int j = filters.size() - 1; j >= 0; --j) {
4866                    final EphemeralResolveIntentInfo intentInfo =
4867                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4868                    ephemeralResolver.addFilter(intentInfo);
4869                }
4870                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4871                        intent, resolvedType, false /*defaultOnly*/, userId);
4872                if (!matchedResolveInfoList.isEmpty()) {
4873                    return matchedResolveInfoList.get(0);
4874                }
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 long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6604        if (srcFile.isDirectory()) {
6605            final File baseFile = new File(pkg.baseCodePath);
6606            long maxModifiedTime = baseFile.lastModified();
6607            if (pkg.splitCodePaths != null) {
6608                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6609                    final File splitFile = new File(pkg.splitCodePaths[i]);
6610                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6611                }
6612            }
6613            return maxModifiedTime;
6614        }
6615        return srcFile.lastModified();
6616    }
6617
6618    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6619            final int policyFlags) throws PackageManagerException {
6620        if (ps != null
6621                && ps.codePath.equals(srcFile)
6622                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6623                && !isCompatSignatureUpdateNeeded(pkg)
6624                && !isRecoverSignatureUpdateNeeded(pkg)) {
6625            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6626            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6627            ArraySet<PublicKey> signingKs;
6628            synchronized (mPackages) {
6629                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6630            }
6631            if (ps.signatures.mSignatures != null
6632                    && ps.signatures.mSignatures.length != 0
6633                    && signingKs != null) {
6634                // Optimization: reuse the existing cached certificates
6635                // if the package appears to be unchanged.
6636                pkg.mSignatures = ps.signatures.mSignatures;
6637                pkg.mSigningKeys = signingKs;
6638                return;
6639            }
6640
6641            Slog.w(TAG, "PackageSetting for " + ps.name
6642                    + " is missing signatures.  Collecting certs again to recover them.");
6643        } else {
6644            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6645        }
6646
6647        try {
6648            PackageParser.collectCertificates(pkg, policyFlags);
6649        } catch (PackageParserException e) {
6650            throw PackageManagerException.from(e);
6651        }
6652    }
6653
6654    /**
6655     *  Traces a package scan.
6656     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6657     */
6658    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6659            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6660        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6661        try {
6662            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6663        } finally {
6664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6665        }
6666    }
6667
6668    /**
6669     *  Scans a package and returns the newly parsed package.
6670     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6671     */
6672    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6673            long currentTime, UserHandle user) throws PackageManagerException {
6674        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6675        PackageParser pp = new PackageParser();
6676        pp.setSeparateProcesses(mSeparateProcesses);
6677        pp.setOnlyCoreApps(mOnlyCore);
6678        pp.setDisplayMetrics(mMetrics);
6679
6680        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6681            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6682        }
6683
6684        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6685        final PackageParser.Package pkg;
6686        try {
6687            pkg = pp.parsePackage(scanFile, parseFlags);
6688        } catch (PackageParserException e) {
6689            throw PackageManagerException.from(e);
6690        } finally {
6691            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6692        }
6693
6694        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6695    }
6696
6697    /**
6698     *  Scans a package and returns the newly parsed package.
6699     *  @throws PackageManagerException on a parse error.
6700     */
6701    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6702            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6703            throws PackageManagerException {
6704        // If the package has children and this is the first dive in the function
6705        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6706        // packages (parent and children) would be successfully scanned before the
6707        // actual scan since scanning mutates internal state and we want to atomically
6708        // install the package and its children.
6709        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6710            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6711                scanFlags |= SCAN_CHECK_ONLY;
6712            }
6713        } else {
6714            scanFlags &= ~SCAN_CHECK_ONLY;
6715        }
6716
6717        // Scan the parent
6718        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6719                scanFlags, currentTime, user);
6720
6721        // Scan the children
6722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6723        for (int i = 0; i < childCount; i++) {
6724            PackageParser.Package childPackage = pkg.childPackages.get(i);
6725            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6726                    currentTime, user);
6727        }
6728
6729
6730        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6731            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6732        }
6733
6734        return scannedPkg;
6735    }
6736
6737    /**
6738     *  Scans a package and returns the newly parsed package.
6739     *  @throws PackageManagerException on a parse error.
6740     */
6741    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6742            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6743            throws PackageManagerException {
6744        PackageSetting ps = null;
6745        PackageSetting updatedPkg;
6746        // reader
6747        synchronized (mPackages) {
6748            // Look to see if we already know about this package.
6749            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6750            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6751                // This package has been renamed to its original name.  Let's
6752                // use that.
6753                ps = mSettings.peekPackageLPr(oldName);
6754            }
6755            // If there was no original package, see one for the real package name.
6756            if (ps == null) {
6757                ps = mSettings.peekPackageLPr(pkg.packageName);
6758            }
6759            // Check to see if this package could be hiding/updating a system
6760            // package.  Must look for it either under the original or real
6761            // package name depending on our state.
6762            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6763            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6764
6765            // If this is a package we don't know about on the system partition, we
6766            // may need to remove disabled child packages on the system partition
6767            // or may need to not add child packages if the parent apk is updated
6768            // on the data partition and no longer defines this child package.
6769            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6770                // If this is a parent package for an updated system app and this system
6771                // app got an OTA update which no longer defines some of the child packages
6772                // we have to prune them from the disabled system packages.
6773                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6774                if (disabledPs != null) {
6775                    final int scannedChildCount = (pkg.childPackages != null)
6776                            ? pkg.childPackages.size() : 0;
6777                    final int disabledChildCount = disabledPs.childPackageNames != null
6778                            ? disabledPs.childPackageNames.size() : 0;
6779                    for (int i = 0; i < disabledChildCount; i++) {
6780                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6781                        boolean disabledPackageAvailable = false;
6782                        for (int j = 0; j < scannedChildCount; j++) {
6783                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6784                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6785                                disabledPackageAvailable = true;
6786                                break;
6787                            }
6788                         }
6789                         if (!disabledPackageAvailable) {
6790                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6791                         }
6792                    }
6793                }
6794            }
6795        }
6796
6797        boolean updatedPkgBetter = false;
6798        // First check if this is a system package that may involve an update
6799        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6800            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6801            // it needs to drop FLAG_PRIVILEGED.
6802            if (locationIsPrivileged(scanFile)) {
6803                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6804            } else {
6805                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6806            }
6807
6808            if (ps != null && !ps.codePath.equals(scanFile)) {
6809                // The path has changed from what was last scanned...  check the
6810                // version of the new path against what we have stored to determine
6811                // what to do.
6812                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6813                if (pkg.mVersionCode <= ps.versionCode) {
6814                    // The system package has been updated and the code path does not match
6815                    // Ignore entry. Skip it.
6816                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6817                            + " ignored: updated version " + ps.versionCode
6818                            + " better than this " + pkg.mVersionCode);
6819                    if (!updatedPkg.codePath.equals(scanFile)) {
6820                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6821                                + ps.name + " changing from " + updatedPkg.codePathString
6822                                + " to " + scanFile);
6823                        updatedPkg.codePath = scanFile;
6824                        updatedPkg.codePathString = scanFile.toString();
6825                        updatedPkg.resourcePath = scanFile;
6826                        updatedPkg.resourcePathString = scanFile.toString();
6827                    }
6828                    updatedPkg.pkg = pkg;
6829                    updatedPkg.versionCode = pkg.mVersionCode;
6830
6831                    // Update the disabled system child packages to point to the package too.
6832                    final int childCount = updatedPkg.childPackageNames != null
6833                            ? updatedPkg.childPackageNames.size() : 0;
6834                    for (int i = 0; i < childCount; i++) {
6835                        String childPackageName = updatedPkg.childPackageNames.get(i);
6836                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6837                                childPackageName);
6838                        if (updatedChildPkg != null) {
6839                            updatedChildPkg.pkg = pkg;
6840                            updatedChildPkg.versionCode = pkg.mVersionCode;
6841                        }
6842                    }
6843
6844                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6845                            + scanFile + " ignored: updated version " + ps.versionCode
6846                            + " better than this " + pkg.mVersionCode);
6847                } else {
6848                    // The current app on the system partition is better than
6849                    // what we have updated to on the data partition; switch
6850                    // back to the system partition version.
6851                    // At this point, its safely assumed that package installation for
6852                    // apps in system partition will go through. If not there won't be a working
6853                    // version of the app
6854                    // writer
6855                    synchronized (mPackages) {
6856                        // Just remove the loaded entries from package lists.
6857                        mPackages.remove(ps.name);
6858                    }
6859
6860                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6861                            + " reverting from " + ps.codePathString
6862                            + ": new version " + pkg.mVersionCode
6863                            + " better than installed " + ps.versionCode);
6864
6865                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6866                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6867                    synchronized (mInstallLock) {
6868                        args.cleanUpResourcesLI();
6869                    }
6870                    synchronized (mPackages) {
6871                        mSettings.enableSystemPackageLPw(ps.name);
6872                    }
6873                    updatedPkgBetter = true;
6874                }
6875            }
6876        }
6877
6878        if (updatedPkg != null) {
6879            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6880            // initially
6881            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6882
6883            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6884            // flag set initially
6885            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6886                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6887            }
6888        }
6889
6890        // Verify certificates against what was last scanned
6891        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6892
6893        /*
6894         * A new system app appeared, but we already had a non-system one of the
6895         * same name installed earlier.
6896         */
6897        boolean shouldHideSystemApp = false;
6898        if (updatedPkg == null && ps != null
6899                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6900            /*
6901             * Check to make sure the signatures match first. If they don't,
6902             * wipe the installed application and its data.
6903             */
6904            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6905                    != PackageManager.SIGNATURE_MATCH) {
6906                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6907                        + " signatures don't match existing userdata copy; removing");
6908                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6909                        "scanPackageInternalLI")) {
6910                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6911                }
6912                ps = null;
6913            } else {
6914                /*
6915                 * If the newly-added system app is an older version than the
6916                 * already installed version, hide it. It will be scanned later
6917                 * and re-added like an update.
6918                 */
6919                if (pkg.mVersionCode <= ps.versionCode) {
6920                    shouldHideSystemApp = true;
6921                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6922                            + " but new version " + pkg.mVersionCode + " better than installed "
6923                            + ps.versionCode + "; hiding system");
6924                } else {
6925                    /*
6926                     * The newly found system app is a newer version that the
6927                     * one previously installed. Simply remove the
6928                     * already-installed application and replace it with our own
6929                     * while keeping the application data.
6930                     */
6931                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6932                            + " reverting from " + ps.codePathString + ": new version "
6933                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6934                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6935                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6936                    synchronized (mInstallLock) {
6937                        args.cleanUpResourcesLI();
6938                    }
6939                }
6940            }
6941        }
6942
6943        // The apk is forward locked (not public) if its code and resources
6944        // are kept in different files. (except for app in either system or
6945        // vendor path).
6946        // TODO grab this value from PackageSettings
6947        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6948            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6949                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6950            }
6951        }
6952
6953        // TODO: extend to support forward-locked splits
6954        String resourcePath = null;
6955        String baseResourcePath = null;
6956        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6957            if (ps != null && ps.resourcePathString != null) {
6958                resourcePath = ps.resourcePathString;
6959                baseResourcePath = ps.resourcePathString;
6960            } else {
6961                // Should not happen at all. Just log an error.
6962                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6963            }
6964        } else {
6965            resourcePath = pkg.codePath;
6966            baseResourcePath = pkg.baseCodePath;
6967        }
6968
6969        // Set application objects path explicitly.
6970        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6971        pkg.setApplicationInfoCodePath(pkg.codePath);
6972        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6973        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6974        pkg.setApplicationInfoResourcePath(resourcePath);
6975        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6976        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6977
6978        // Note that we invoke the following method only if we are about to unpack an application
6979        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6980                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6981
6982        /*
6983         * If the system app should be overridden by a previously installed
6984         * data, hide the system app now and let the /data/app scan pick it up
6985         * again.
6986         */
6987        if (shouldHideSystemApp) {
6988            synchronized (mPackages) {
6989                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6990            }
6991        }
6992
6993        return scannedPkg;
6994    }
6995
6996    private static String fixProcessName(String defProcessName,
6997            String processName, int uid) {
6998        if (processName == null) {
6999            return defProcessName;
7000        }
7001        return processName;
7002    }
7003
7004    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7005            throws PackageManagerException {
7006        if (pkgSetting.signatures.mSignatures != null) {
7007            // Already existing package. Make sure signatures match
7008            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7009                    == PackageManager.SIGNATURE_MATCH;
7010            if (!match) {
7011                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7012                        == PackageManager.SIGNATURE_MATCH;
7013            }
7014            if (!match) {
7015                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7016                        == PackageManager.SIGNATURE_MATCH;
7017            }
7018            if (!match) {
7019                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7020                        + pkg.packageName + " signatures do not match the "
7021                        + "previously installed version; ignoring!");
7022            }
7023        }
7024
7025        // Check for shared user signatures
7026        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7027            // Already existing package. Make sure signatures match
7028            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7029                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7030            if (!match) {
7031                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7032                        == PackageManager.SIGNATURE_MATCH;
7033            }
7034            if (!match) {
7035                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7036                        == PackageManager.SIGNATURE_MATCH;
7037            }
7038            if (!match) {
7039                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7040                        "Package " + pkg.packageName
7041                        + " has no signatures that match those in shared user "
7042                        + pkgSetting.sharedUser.name + "; ignoring!");
7043            }
7044        }
7045    }
7046
7047    /**
7048     * Enforces that only the system UID or root's UID can call a method exposed
7049     * via Binder.
7050     *
7051     * @param message used as message if SecurityException is thrown
7052     * @throws SecurityException if the caller is not system or root
7053     */
7054    private static final void enforceSystemOrRoot(String message) {
7055        final int uid = Binder.getCallingUid();
7056        if (uid != Process.SYSTEM_UID && uid != 0) {
7057            throw new SecurityException(message);
7058        }
7059    }
7060
7061    @Override
7062    public void performFstrimIfNeeded() {
7063        enforceSystemOrRoot("Only the system can request fstrim");
7064
7065        // Before everything else, see whether we need to fstrim.
7066        try {
7067            IMountService ms = PackageHelper.getMountService();
7068            if (ms != null) {
7069                boolean doTrim = false;
7070                final long interval = android.provider.Settings.Global.getLong(
7071                        mContext.getContentResolver(),
7072                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7073                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7074                if (interval > 0) {
7075                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7076                    if (timeSinceLast > interval) {
7077                        doTrim = true;
7078                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7079                                + "; running immediately");
7080                    }
7081                }
7082                if (doTrim) {
7083                    if (!isFirstBoot()) {
7084                        try {
7085                            ActivityManagerNative.getDefault().showBootMessage(
7086                                    mContext.getResources().getString(
7087                                            R.string.android_upgrading_fstrim), true);
7088                        } catch (RemoteException e) {
7089                        }
7090                    }
7091                    ms.runMaintenance();
7092                }
7093            } else {
7094                Slog.e(TAG, "Mount service unavailable!");
7095            }
7096        } catch (RemoteException e) {
7097            // Can't happen; MountService is local
7098        }
7099    }
7100
7101    @Override
7102    public void updatePackagesIfNeeded() {
7103        enforceSystemOrRoot("Only the system can request package update");
7104
7105        // We need to re-extract after an OTA.
7106        boolean causeUpgrade = isUpgrade();
7107
7108        // First boot or factory reset.
7109        // Note: we also handle devices that are upgrading to N right now as if it is their
7110        //       first boot, as they do not have profile data.
7111        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7112
7113        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7114        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7115
7116        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7117            return;
7118        }
7119
7120        List<PackageParser.Package> pkgs;
7121        synchronized (mPackages) {
7122            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7123        }
7124
7125        final long startTime = System.nanoTime();
7126        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7127                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7128
7129        final int elapsedTimeSeconds =
7130                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7131
7132        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7133        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7134        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7135        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7136        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7137    }
7138
7139    /**
7140     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7141     * containing statistics about the invocation. The array consists of three elements,
7142     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7143     * and {@code numberOfPackagesFailed}.
7144     */
7145    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7146            String compilerFilter) {
7147
7148        int numberOfPackagesVisited = 0;
7149        int numberOfPackagesOptimized = 0;
7150        int numberOfPackagesSkipped = 0;
7151        int numberOfPackagesFailed = 0;
7152        final int numberOfPackagesToDexopt = pkgs.size();
7153
7154        for (PackageParser.Package pkg : pkgs) {
7155            numberOfPackagesVisited++;
7156
7157            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7158                if (DEBUG_DEXOPT) {
7159                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7160                }
7161                numberOfPackagesSkipped++;
7162                continue;
7163            }
7164
7165            if (DEBUG_DEXOPT) {
7166                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7167                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7168            }
7169
7170            if (showDialog) {
7171                try {
7172                    ActivityManagerNative.getDefault().showBootMessage(
7173                            mContext.getResources().getString(R.string.android_upgrading_apk,
7174                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7175                } catch (RemoteException e) {
7176                }
7177            }
7178
7179            // If the OTA updates a system app which was previously preopted to a non-preopted state
7180            // the app might end up being verified at runtime. That's because by default the apps
7181            // are verify-profile but for preopted apps there's no profile.
7182            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7183            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7184            // filter (by default interpret-only).
7185            // Note that at this stage unused apps are already filtered.
7186            if (isSystemApp(pkg) &&
7187                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7188                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7189                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7190            }
7191
7192            // checkProfiles is false to avoid merging profiles during boot which
7193            // might interfere with background compilation (b/28612421).
7194            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7195            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7196            // trade-off worth doing to save boot time work.
7197            int dexOptStatus = performDexOptTraced(pkg.packageName,
7198                    false /* checkProfiles */,
7199                    compilerFilter,
7200                    false /* force */);
7201            switch (dexOptStatus) {
7202                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7203                    numberOfPackagesOptimized++;
7204                    break;
7205                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7206                    numberOfPackagesSkipped++;
7207                    break;
7208                case PackageDexOptimizer.DEX_OPT_FAILED:
7209                    numberOfPackagesFailed++;
7210                    break;
7211                default:
7212                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7213                    break;
7214            }
7215        }
7216
7217        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7218                numberOfPackagesFailed };
7219    }
7220
7221    @Override
7222    public void notifyPackageUse(String packageName, int reason) {
7223        synchronized (mPackages) {
7224            PackageParser.Package p = mPackages.get(packageName);
7225            if (p == null) {
7226                return;
7227            }
7228            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7229        }
7230    }
7231
7232    // TODO: this is not used nor needed. Delete it.
7233    @Override
7234    public boolean performDexOptIfNeeded(String packageName) {
7235        int dexOptStatus = performDexOptTraced(packageName,
7236                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7237        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7238    }
7239
7240    @Override
7241    public boolean performDexOpt(String packageName,
7242            boolean checkProfiles, int compileReason, boolean force) {
7243        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7244                getCompilerFilterForReason(compileReason), force);
7245        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7246    }
7247
7248    @Override
7249    public boolean performDexOptMode(String packageName,
7250            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7251        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7252                targetCompilerFilter, force);
7253        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7254    }
7255
7256    private int performDexOptTraced(String packageName,
7257                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7258        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7259        try {
7260            return performDexOptInternal(packageName, checkProfiles,
7261                    targetCompilerFilter, force);
7262        } finally {
7263            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7264        }
7265    }
7266
7267    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7268    // if the package can now be considered up to date for the given filter.
7269    private int performDexOptInternal(String packageName,
7270                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7271        PackageParser.Package p;
7272        synchronized (mPackages) {
7273            p = mPackages.get(packageName);
7274            if (p == null) {
7275                // Package could not be found. Report failure.
7276                return PackageDexOptimizer.DEX_OPT_FAILED;
7277            }
7278            mPackageUsage.maybeWriteAsync(mPackages);
7279            mCompilerStats.maybeWriteAsync();
7280        }
7281        long callingId = Binder.clearCallingIdentity();
7282        try {
7283            synchronized (mInstallLock) {
7284                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7285                        targetCompilerFilter, force);
7286            }
7287        } finally {
7288            Binder.restoreCallingIdentity(callingId);
7289        }
7290    }
7291
7292    public ArraySet<String> getOptimizablePackages() {
7293        ArraySet<String> pkgs = new ArraySet<String>();
7294        synchronized (mPackages) {
7295            for (PackageParser.Package p : mPackages.values()) {
7296                if (PackageDexOptimizer.canOptimizePackage(p)) {
7297                    pkgs.add(p.packageName);
7298                }
7299            }
7300        }
7301        return pkgs;
7302    }
7303
7304    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7305            boolean checkProfiles, String targetCompilerFilter,
7306            boolean force) {
7307        // Select the dex optimizer based on the force parameter.
7308        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7309        //       allocate an object here.
7310        PackageDexOptimizer pdo = force
7311                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7312                : mPackageDexOptimizer;
7313
7314        // Optimize all dependencies first. Note: we ignore the return value and march on
7315        // on errors.
7316        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7317        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7318        if (!deps.isEmpty()) {
7319            for (PackageParser.Package depPackage : deps) {
7320                // TODO: Analyze and investigate if we (should) profile libraries.
7321                // Currently this will do a full compilation of the library by default.
7322                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7323                        false /* checkProfiles */,
7324                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7325                        getOrCreateCompilerPackageStats(depPackage));
7326            }
7327        }
7328        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7329                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7330    }
7331
7332    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7333        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7334            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7335            Set<String> collectedNames = new HashSet<>();
7336            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7337
7338            retValue.remove(p);
7339
7340            return retValue;
7341        } else {
7342            return Collections.emptyList();
7343        }
7344    }
7345
7346    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7347            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7348        if (!collectedNames.contains(p.packageName)) {
7349            collectedNames.add(p.packageName);
7350            collected.add(p);
7351
7352            if (p.usesLibraries != null) {
7353                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7354            }
7355            if (p.usesOptionalLibraries != null) {
7356                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7357                        collectedNames);
7358            }
7359        }
7360    }
7361
7362    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7363            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7364        for (String libName : libs) {
7365            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7366            if (libPkg != null) {
7367                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7368            }
7369        }
7370    }
7371
7372    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7373        synchronized (mPackages) {
7374            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7375            if (lib != null && lib.apk != null) {
7376                return mPackages.get(lib.apk);
7377            }
7378        }
7379        return null;
7380    }
7381
7382    public void shutdown() {
7383        mPackageUsage.writeNow(mPackages);
7384        mCompilerStats.writeNow();
7385    }
7386
7387    @Override
7388    public void dumpProfiles(String packageName) {
7389        PackageParser.Package pkg;
7390        synchronized (mPackages) {
7391            pkg = mPackages.get(packageName);
7392            if (pkg == null) {
7393                throw new IllegalArgumentException("Unknown package: " + packageName);
7394            }
7395        }
7396        /* Only the shell, root, or the app user should be able to dump profiles. */
7397        int callingUid = Binder.getCallingUid();
7398        if (callingUid != Process.SHELL_UID &&
7399            callingUid != Process.ROOT_UID &&
7400            callingUid != pkg.applicationInfo.uid) {
7401            throw new SecurityException("dumpProfiles");
7402        }
7403
7404        synchronized (mInstallLock) {
7405            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7406            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7407            try {
7408                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7409                String gid = Integer.toString(sharedGid);
7410                String codePaths = TextUtils.join(";", allCodePaths);
7411                mInstaller.dumpProfiles(gid, packageName, codePaths);
7412            } catch (InstallerException e) {
7413                Slog.w(TAG, "Failed to dump profiles", e);
7414            }
7415            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7416        }
7417    }
7418
7419    @Override
7420    public void forceDexOpt(String packageName) {
7421        enforceSystemOrRoot("forceDexOpt");
7422
7423        PackageParser.Package pkg;
7424        synchronized (mPackages) {
7425            pkg = mPackages.get(packageName);
7426            if (pkg == null) {
7427                throw new IllegalArgumentException("Unknown package: " + packageName);
7428            }
7429        }
7430
7431        synchronized (mInstallLock) {
7432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7433
7434            // Whoever is calling forceDexOpt wants a fully compiled package.
7435            // Don't use profiles since that may cause compilation to be skipped.
7436            final int res = performDexOptInternalWithDependenciesLI(pkg,
7437                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7438                    true /* force */);
7439
7440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7441            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7442                throw new IllegalStateException("Failed to dexopt: " + res);
7443            }
7444        }
7445    }
7446
7447    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7448        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7449            Slog.w(TAG, "Unable to update from " + oldPkg.name
7450                    + " to " + newPkg.packageName
7451                    + ": old package not in system partition");
7452            return false;
7453        } else if (mPackages.get(oldPkg.name) != null) {
7454            Slog.w(TAG, "Unable to update from " + oldPkg.name
7455                    + " to " + newPkg.packageName
7456                    + ": old package still exists");
7457            return false;
7458        }
7459        return true;
7460    }
7461
7462    void removeCodePathLI(File codePath) {
7463        if (codePath.isDirectory()) {
7464            try {
7465                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7466            } catch (InstallerException e) {
7467                Slog.w(TAG, "Failed to remove code path", e);
7468            }
7469        } else {
7470            codePath.delete();
7471        }
7472    }
7473
7474    private int[] resolveUserIds(int userId) {
7475        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7476    }
7477
7478    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7479        if (pkg == null) {
7480            Slog.wtf(TAG, "Package was null!", new Throwable());
7481            return;
7482        }
7483        clearAppDataLeafLIF(pkg, userId, flags);
7484        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7485        for (int i = 0; i < childCount; i++) {
7486            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7487        }
7488    }
7489
7490    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7491        final PackageSetting ps;
7492        synchronized (mPackages) {
7493            ps = mSettings.mPackages.get(pkg.packageName);
7494        }
7495        for (int realUserId : resolveUserIds(userId)) {
7496            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7497            try {
7498                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7499                        ceDataInode);
7500            } catch (InstallerException e) {
7501                Slog.w(TAG, String.valueOf(e));
7502            }
7503        }
7504    }
7505
7506    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7507        if (pkg == null) {
7508            Slog.wtf(TAG, "Package was null!", new Throwable());
7509            return;
7510        }
7511        destroyAppDataLeafLIF(pkg, userId, flags);
7512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7513        for (int i = 0; i < childCount; i++) {
7514            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7515        }
7516    }
7517
7518    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7519        final PackageSetting ps;
7520        synchronized (mPackages) {
7521            ps = mSettings.mPackages.get(pkg.packageName);
7522        }
7523        for (int realUserId : resolveUserIds(userId)) {
7524            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7525            try {
7526                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7527                        ceDataInode);
7528            } catch (InstallerException e) {
7529                Slog.w(TAG, String.valueOf(e));
7530            }
7531        }
7532    }
7533
7534    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7535        if (pkg == null) {
7536            Slog.wtf(TAG, "Package was null!", new Throwable());
7537            return;
7538        }
7539        destroyAppProfilesLeafLIF(pkg);
7540        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7541        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7542        for (int i = 0; i < childCount; i++) {
7543            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7544            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7545                    true /* removeBaseMarker */);
7546        }
7547    }
7548
7549    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7550            boolean removeBaseMarker) {
7551        if (pkg.isForwardLocked()) {
7552            return;
7553        }
7554
7555        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7556            try {
7557                path = PackageManagerServiceUtils.realpath(new File(path));
7558            } catch (IOException e) {
7559                // TODO: Should we return early here ?
7560                Slog.w(TAG, "Failed to get canonical path", e);
7561                continue;
7562            }
7563
7564            final String useMarker = path.replace('/', '@');
7565            for (int realUserId : resolveUserIds(userId)) {
7566                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7567                if (removeBaseMarker) {
7568                    File foreignUseMark = new File(profileDir, useMarker);
7569                    if (foreignUseMark.exists()) {
7570                        if (!foreignUseMark.delete()) {
7571                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7572                                    + pkg.packageName);
7573                        }
7574                    }
7575                }
7576
7577                File[] markers = profileDir.listFiles();
7578                if (markers != null) {
7579                    final String searchString = "@" + pkg.packageName + "@";
7580                    // We also delete all markers that contain the package name we're
7581                    // uninstalling. These are associated with secondary dex-files belonging
7582                    // to the package. Reconstructing the path of these dex files is messy
7583                    // in general.
7584                    for (File marker : markers) {
7585                        if (marker.getName().indexOf(searchString) > 0) {
7586                            if (!marker.delete()) {
7587                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7588                                    + pkg.packageName);
7589                            }
7590                        }
7591                    }
7592                }
7593            }
7594        }
7595    }
7596
7597    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7598        try {
7599            mInstaller.destroyAppProfiles(pkg.packageName);
7600        } catch (InstallerException e) {
7601            Slog.w(TAG, String.valueOf(e));
7602        }
7603    }
7604
7605    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7606        if (pkg == null) {
7607            Slog.wtf(TAG, "Package was null!", new Throwable());
7608            return;
7609        }
7610        clearAppProfilesLeafLIF(pkg);
7611        // We don't remove the base foreign use marker when clearing profiles because
7612        // we will rename it when the app is updated. Unlike the actual profile contents,
7613        // the foreign use marker is good across installs.
7614        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7615        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7616        for (int i = 0; i < childCount; i++) {
7617            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7618        }
7619    }
7620
7621    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7622        try {
7623            mInstaller.clearAppProfiles(pkg.packageName);
7624        } catch (InstallerException e) {
7625            Slog.w(TAG, String.valueOf(e));
7626        }
7627    }
7628
7629    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7630            long lastUpdateTime) {
7631        // Set parent install/update time
7632        PackageSetting ps = (PackageSetting) pkg.mExtras;
7633        if (ps != null) {
7634            ps.firstInstallTime = firstInstallTime;
7635            ps.lastUpdateTime = lastUpdateTime;
7636        }
7637        // Set children install/update time
7638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7639        for (int i = 0; i < childCount; i++) {
7640            PackageParser.Package childPkg = pkg.childPackages.get(i);
7641            ps = (PackageSetting) childPkg.mExtras;
7642            if (ps != null) {
7643                ps.firstInstallTime = firstInstallTime;
7644                ps.lastUpdateTime = lastUpdateTime;
7645            }
7646        }
7647    }
7648
7649    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7650            PackageParser.Package changingLib) {
7651        if (file.path != null) {
7652            usesLibraryFiles.add(file.path);
7653            return;
7654        }
7655        PackageParser.Package p = mPackages.get(file.apk);
7656        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7657            // If we are doing this while in the middle of updating a library apk,
7658            // then we need to make sure to use that new apk for determining the
7659            // dependencies here.  (We haven't yet finished committing the new apk
7660            // to the package manager state.)
7661            if (p == null || p.packageName.equals(changingLib.packageName)) {
7662                p = changingLib;
7663            }
7664        }
7665        if (p != null) {
7666            usesLibraryFiles.addAll(p.getAllCodePaths());
7667        }
7668    }
7669
7670    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7671            PackageParser.Package changingLib) throws PackageManagerException {
7672        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7673            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7674            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7675            for (int i=0; i<N; i++) {
7676                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7677                if (file == null) {
7678                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7679                            "Package " + pkg.packageName + " requires unavailable shared library "
7680                            + pkg.usesLibraries.get(i) + "; failing!");
7681                }
7682                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7683            }
7684            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7685            for (int i=0; i<N; i++) {
7686                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7687                if (file == null) {
7688                    Slog.w(TAG, "Package " + pkg.packageName
7689                            + " desires unavailable shared library "
7690                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7691                } else {
7692                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7693                }
7694            }
7695            N = usesLibraryFiles.size();
7696            if (N > 0) {
7697                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7698            } else {
7699                pkg.usesLibraryFiles = null;
7700            }
7701        }
7702    }
7703
7704    private static boolean hasString(List<String> list, List<String> which) {
7705        if (list == null) {
7706            return false;
7707        }
7708        for (int i=list.size()-1; i>=0; i--) {
7709            for (int j=which.size()-1; j>=0; j--) {
7710                if (which.get(j).equals(list.get(i))) {
7711                    return true;
7712                }
7713            }
7714        }
7715        return false;
7716    }
7717
7718    private void updateAllSharedLibrariesLPw() {
7719        for (PackageParser.Package pkg : mPackages.values()) {
7720            try {
7721                updateSharedLibrariesLPw(pkg, null);
7722            } catch (PackageManagerException e) {
7723                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7724            }
7725        }
7726    }
7727
7728    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7729            PackageParser.Package changingPkg) {
7730        ArrayList<PackageParser.Package> res = null;
7731        for (PackageParser.Package pkg : mPackages.values()) {
7732            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7733                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7734                if (res == null) {
7735                    res = new ArrayList<PackageParser.Package>();
7736                }
7737                res.add(pkg);
7738                try {
7739                    updateSharedLibrariesLPw(pkg, changingPkg);
7740                } catch (PackageManagerException e) {
7741                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7742                }
7743            }
7744        }
7745        return res;
7746    }
7747
7748    /**
7749     * Derive the value of the {@code cpuAbiOverride} based on the provided
7750     * value and an optional stored value from the package settings.
7751     */
7752    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7753        String cpuAbiOverride = null;
7754
7755        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7756            cpuAbiOverride = null;
7757        } else if (abiOverride != null) {
7758            cpuAbiOverride = abiOverride;
7759        } else if (settings != null) {
7760            cpuAbiOverride = settings.cpuAbiOverrideString;
7761        }
7762
7763        return cpuAbiOverride;
7764    }
7765
7766    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7767            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7768                    throws PackageManagerException {
7769        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7770        // If the package has children and this is the first dive in the function
7771        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7772        // whether all packages (parent and children) would be successfully scanned
7773        // before the actual scan since scanning mutates internal state and we want
7774        // to atomically install the package and its children.
7775        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7776            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7777                scanFlags |= SCAN_CHECK_ONLY;
7778            }
7779        } else {
7780            scanFlags &= ~SCAN_CHECK_ONLY;
7781        }
7782
7783        final PackageParser.Package scannedPkg;
7784        try {
7785            // Scan the parent
7786            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7787            // Scan the children
7788            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7789            for (int i = 0; i < childCount; i++) {
7790                PackageParser.Package childPkg = pkg.childPackages.get(i);
7791                scanPackageLI(childPkg, policyFlags,
7792                        scanFlags, currentTime, user);
7793            }
7794        } finally {
7795            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7796        }
7797
7798        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7799            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7800        }
7801
7802        return scannedPkg;
7803    }
7804
7805    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7806            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7807        boolean success = false;
7808        try {
7809            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7810                    currentTime, user);
7811            success = true;
7812            return res;
7813        } finally {
7814            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7815                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7816                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7817                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7818                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7819            }
7820        }
7821    }
7822
7823    /**
7824     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7825     */
7826    private static boolean apkHasCode(String fileName) {
7827        StrictJarFile jarFile = null;
7828        try {
7829            jarFile = new StrictJarFile(fileName,
7830                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7831            return jarFile.findEntry("classes.dex") != null;
7832        } catch (IOException ignore) {
7833        } finally {
7834            try {
7835                if (jarFile != null) {
7836                    jarFile.close();
7837                }
7838            } catch (IOException ignore) {}
7839        }
7840        return false;
7841    }
7842
7843    /**
7844     * Enforces code policy for the package. This ensures that if an APK has
7845     * declared hasCode="true" in its manifest that the APK actually contains
7846     * code.
7847     *
7848     * @throws PackageManagerException If bytecode could not be found when it should exist
7849     */
7850    private static void enforceCodePolicy(PackageParser.Package pkg)
7851            throws PackageManagerException {
7852        final boolean shouldHaveCode =
7853                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7854        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7855            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7856                    "Package " + pkg.baseCodePath + " code is missing");
7857        }
7858
7859        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7860            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7861                final boolean splitShouldHaveCode =
7862                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7863                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7864                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7865                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7866                }
7867            }
7868        }
7869    }
7870
7871    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7872            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7873            throws PackageManagerException {
7874        final File scanFile = new File(pkg.codePath);
7875        if (pkg.applicationInfo.getCodePath() == null ||
7876                pkg.applicationInfo.getResourcePath() == null) {
7877            // Bail out. The resource and code paths haven't been set.
7878            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7879                    "Code and resource paths haven't been set correctly");
7880        }
7881
7882        // Apply policy
7883        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7884            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7885            if (pkg.applicationInfo.isDirectBootAware()) {
7886                // we're direct boot aware; set for all components
7887                for (PackageParser.Service s : pkg.services) {
7888                    s.info.encryptionAware = s.info.directBootAware = true;
7889                }
7890                for (PackageParser.Provider p : pkg.providers) {
7891                    p.info.encryptionAware = p.info.directBootAware = true;
7892                }
7893                for (PackageParser.Activity a : pkg.activities) {
7894                    a.info.encryptionAware = a.info.directBootAware = true;
7895                }
7896                for (PackageParser.Activity r : pkg.receivers) {
7897                    r.info.encryptionAware = r.info.directBootAware = true;
7898                }
7899            }
7900        } else {
7901            // Only allow system apps to be flagged as core apps.
7902            pkg.coreApp = false;
7903            // clear flags not applicable to regular apps
7904            pkg.applicationInfo.privateFlags &=
7905                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7906            pkg.applicationInfo.privateFlags &=
7907                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7908        }
7909        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7910
7911        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7912            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7913        }
7914
7915        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7916            enforceCodePolicy(pkg);
7917        }
7918
7919        if (mCustomResolverComponentName != null &&
7920                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7921            setUpCustomResolverActivity(pkg);
7922        }
7923
7924        if (pkg.packageName.equals("android")) {
7925            synchronized (mPackages) {
7926                if (mAndroidApplication != null) {
7927                    Slog.w(TAG, "*************************************************");
7928                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7929                    Slog.w(TAG, " file=" + scanFile);
7930                    Slog.w(TAG, "*************************************************");
7931                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7932                            "Core android package being redefined.  Skipping.");
7933                }
7934
7935                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7936                    // Set up information for our fall-back user intent resolution activity.
7937                    mPlatformPackage = pkg;
7938                    pkg.mVersionCode = mSdkVersion;
7939                    mAndroidApplication = pkg.applicationInfo;
7940
7941                    if (!mResolverReplaced) {
7942                        mResolveActivity.applicationInfo = mAndroidApplication;
7943                        mResolveActivity.name = ResolverActivity.class.getName();
7944                        mResolveActivity.packageName = mAndroidApplication.packageName;
7945                        mResolveActivity.processName = "system:ui";
7946                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7947                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7948                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7949                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7950                        mResolveActivity.exported = true;
7951                        mResolveActivity.enabled = true;
7952                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7953                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7954                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7955                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7956                                | ActivityInfo.CONFIG_ORIENTATION
7957                                | ActivityInfo.CONFIG_KEYBOARD
7958                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7959                        mResolveInfo.activityInfo = mResolveActivity;
7960                        mResolveInfo.priority = 0;
7961                        mResolveInfo.preferredOrder = 0;
7962                        mResolveInfo.match = 0;
7963                        mResolveComponentName = new ComponentName(
7964                                mAndroidApplication.packageName, mResolveActivity.name);
7965                    }
7966                }
7967            }
7968        }
7969
7970        if (DEBUG_PACKAGE_SCANNING) {
7971            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7972                Log.d(TAG, "Scanning package " + pkg.packageName);
7973        }
7974
7975        synchronized (mPackages) {
7976            if (mPackages.containsKey(pkg.packageName)
7977                    || mSharedLibraries.containsKey(pkg.packageName)) {
7978                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7979                        "Application package " + pkg.packageName
7980                                + " already installed.  Skipping duplicate.");
7981            }
7982
7983            // If we're only installing presumed-existing packages, require that the
7984            // scanned APK is both already known and at the path previously established
7985            // for it.  Previously unknown packages we pick up normally, but if we have an
7986            // a priori expectation about this package's install presence, enforce it.
7987            // With a singular exception for new system packages. When an OTA contains
7988            // a new system package, we allow the codepath to change from a system location
7989            // to the user-installed location. If we don't allow this change, any newer,
7990            // user-installed version of the application will be ignored.
7991            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7992                if (mExpectingBetter.containsKey(pkg.packageName)) {
7993                    logCriticalInfo(Log.WARN,
7994                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7995                } else {
7996                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7997                    if (known != null) {
7998                        if (DEBUG_PACKAGE_SCANNING) {
7999                            Log.d(TAG, "Examining " + pkg.codePath
8000                                    + " and requiring known paths " + known.codePathString
8001                                    + " & " + known.resourcePathString);
8002                        }
8003                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8004                                || !pkg.applicationInfo.getResourcePath().equals(
8005                                known.resourcePathString)) {
8006                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8007                                    "Application package " + pkg.packageName
8008                                            + " found at " + pkg.applicationInfo.getCodePath()
8009                                            + " but expected at " + known.codePathString
8010                                            + "; ignoring.");
8011                        }
8012                    }
8013                }
8014            }
8015        }
8016
8017        // Initialize package source and resource directories
8018        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8019        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8020
8021        SharedUserSetting suid = null;
8022        PackageSetting pkgSetting = null;
8023
8024        if (!isSystemApp(pkg)) {
8025            // Only system apps can use these features.
8026            pkg.mOriginalPackages = null;
8027            pkg.mRealPackage = null;
8028            pkg.mAdoptPermissions = null;
8029        }
8030
8031        // Getting the package setting may have a side-effect, so if we
8032        // are only checking if scan would succeed, stash a copy of the
8033        // old setting to restore at the end.
8034        PackageSetting nonMutatedPs = null;
8035
8036        // writer
8037        synchronized (mPackages) {
8038            if (pkg.mSharedUserId != null) {
8039                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8040                if (suid == null) {
8041                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8042                            "Creating application package " + pkg.packageName
8043                            + " for shared user failed");
8044                }
8045                if (DEBUG_PACKAGE_SCANNING) {
8046                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8047                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8048                                + "): packages=" + suid.packages);
8049                }
8050            }
8051
8052            // Check if we are renaming from an original package name.
8053            PackageSetting origPackage = null;
8054            String realName = null;
8055            if (pkg.mOriginalPackages != null) {
8056                // This package may need to be renamed to a previously
8057                // installed name.  Let's check on that...
8058                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8059                if (pkg.mOriginalPackages.contains(renamed)) {
8060                    // This package had originally been installed as the
8061                    // original name, and we have already taken care of
8062                    // transitioning to the new one.  Just update the new
8063                    // one to continue using the old name.
8064                    realName = pkg.mRealPackage;
8065                    if (!pkg.packageName.equals(renamed)) {
8066                        // Callers into this function may have already taken
8067                        // care of renaming the package; only do it here if
8068                        // it is not already done.
8069                        pkg.setPackageName(renamed);
8070                    }
8071
8072                } else {
8073                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8074                        if ((origPackage = mSettings.peekPackageLPr(
8075                                pkg.mOriginalPackages.get(i))) != null) {
8076                            // We do have the package already installed under its
8077                            // original name...  should we use it?
8078                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8079                                // New package is not compatible with original.
8080                                origPackage = null;
8081                                continue;
8082                            } else if (origPackage.sharedUser != null) {
8083                                // Make sure uid is compatible between packages.
8084                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8085                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8086                                            + " to " + pkg.packageName + ": old uid "
8087                                            + origPackage.sharedUser.name
8088                                            + " differs from " + pkg.mSharedUserId);
8089                                    origPackage = null;
8090                                    continue;
8091                                }
8092                                // TODO: Add case when shared user id is added [b/28144775]
8093                            } else {
8094                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8095                                        + pkg.packageName + " to old name " + origPackage.name);
8096                            }
8097                            break;
8098                        }
8099                    }
8100                }
8101            }
8102
8103            if (mTransferedPackages.contains(pkg.packageName)) {
8104                Slog.w(TAG, "Package " + pkg.packageName
8105                        + " was transferred to another, but its .apk remains");
8106            }
8107
8108            // See comments in nonMutatedPs declaration
8109            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8110                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8111                if (foundPs != null) {
8112                    nonMutatedPs = new PackageSetting(foundPs);
8113                }
8114            }
8115
8116            // Just create the setting, don't add it yet. For already existing packages
8117            // the PkgSetting exists already and doesn't have to be created.
8118            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8119                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8120                    pkg.applicationInfo.primaryCpuAbi,
8121                    pkg.applicationInfo.secondaryCpuAbi,
8122                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8123                    user, false);
8124            if (pkgSetting == null) {
8125                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8126                        "Creating application package " + pkg.packageName + " failed");
8127            }
8128
8129            if (pkgSetting.origPackage != null) {
8130                // If we are first transitioning from an original package,
8131                // fix up the new package's name now.  We need to do this after
8132                // looking up the package under its new name, so getPackageLP
8133                // can take care of fiddling things correctly.
8134                pkg.setPackageName(origPackage.name);
8135
8136                // File a report about this.
8137                String msg = "New package " + pkgSetting.realName
8138                        + " renamed to replace old package " + pkgSetting.name;
8139                reportSettingsProblem(Log.WARN, msg);
8140
8141                // Make a note of it.
8142                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8143                    mTransferedPackages.add(origPackage.name);
8144                }
8145
8146                // No longer need to retain this.
8147                pkgSetting.origPackage = null;
8148            }
8149
8150            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8151                // Make a note of it.
8152                mTransferedPackages.add(pkg.packageName);
8153            }
8154
8155            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8156                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8157            }
8158
8159            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8160                // Check all shared libraries and map to their actual file path.
8161                // We only do this here for apps not on a system dir, because those
8162                // are the only ones that can fail an install due to this.  We
8163                // will take care of the system apps by updating all of their
8164                // library paths after the scan is done.
8165                updateSharedLibrariesLPw(pkg, null);
8166            }
8167
8168            if (mFoundPolicyFile) {
8169                SELinuxMMAC.assignSeinfoValue(pkg);
8170            }
8171
8172            pkg.applicationInfo.uid = pkgSetting.appId;
8173            pkg.mExtras = pkgSetting;
8174            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8175                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8176                    // We just determined the app is signed correctly, so bring
8177                    // over the latest parsed certs.
8178                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8179                } else {
8180                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8181                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8182                                "Package " + pkg.packageName + " upgrade keys do not match the "
8183                                + "previously installed version");
8184                    } else {
8185                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8186                        String msg = "System package " + pkg.packageName
8187                            + " signature changed; retaining data.";
8188                        reportSettingsProblem(Log.WARN, msg);
8189                    }
8190                }
8191            } else {
8192                try {
8193                    verifySignaturesLP(pkgSetting, pkg);
8194                    // We just determined the app is signed correctly, so bring
8195                    // over the latest parsed certs.
8196                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8197                } catch (PackageManagerException e) {
8198                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8199                        throw e;
8200                    }
8201                    // The signature has changed, but this package is in the system
8202                    // image...  let's recover!
8203                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8204                    // However...  if this package is part of a shared user, but it
8205                    // doesn't match the signature of the shared user, let's fail.
8206                    // What this means is that you can't change the signatures
8207                    // associated with an overall shared user, which doesn't seem all
8208                    // that unreasonable.
8209                    if (pkgSetting.sharedUser != null) {
8210                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8211                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8212                            throw new PackageManagerException(
8213                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8214                                            "Signature mismatch for shared user: "
8215                                            + pkgSetting.sharedUser);
8216                        }
8217                    }
8218                    // File a report about this.
8219                    String msg = "System package " + pkg.packageName
8220                        + " signature changed; retaining data.";
8221                    reportSettingsProblem(Log.WARN, msg);
8222                }
8223            }
8224            // Verify that this new package doesn't have any content providers
8225            // that conflict with existing packages.  Only do this if the
8226            // package isn't already installed, since we don't want to break
8227            // things that are installed.
8228            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8229                final int N = pkg.providers.size();
8230                int i;
8231                for (i=0; i<N; i++) {
8232                    PackageParser.Provider p = pkg.providers.get(i);
8233                    if (p.info.authority != null) {
8234                        String names[] = p.info.authority.split(";");
8235                        for (int j = 0; j < names.length; j++) {
8236                            if (mProvidersByAuthority.containsKey(names[j])) {
8237                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8238                                final String otherPackageName =
8239                                        ((other != null && other.getComponentName() != null) ?
8240                                                other.getComponentName().getPackageName() : "?");
8241                                throw new PackageManagerException(
8242                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8243                                                "Can't install because provider name " + names[j]
8244                                                + " (in package " + pkg.applicationInfo.packageName
8245                                                + ") is already used by " + otherPackageName);
8246                            }
8247                        }
8248                    }
8249                }
8250            }
8251
8252            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8253                // This package wants to adopt ownership of permissions from
8254                // another package.
8255                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8256                    final String origName = pkg.mAdoptPermissions.get(i);
8257                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8258                    if (orig != null) {
8259                        if (verifyPackageUpdateLPr(orig, pkg)) {
8260                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8261                                    + pkg.packageName);
8262                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8263                        }
8264                    }
8265                }
8266            }
8267        }
8268
8269        final String pkgName = pkg.packageName;
8270
8271        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8272        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8273        pkg.applicationInfo.processName = fixProcessName(
8274                pkg.applicationInfo.packageName,
8275                pkg.applicationInfo.processName,
8276                pkg.applicationInfo.uid);
8277
8278        if (pkg != mPlatformPackage) {
8279            // Get all of our default paths setup
8280            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8281        }
8282
8283        final String path = scanFile.getPath();
8284        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8285
8286        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8287            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8288
8289            // Some system apps still use directory structure for native libraries
8290            // in which case we might end up not detecting abi solely based on apk
8291            // structure. Try to detect abi based on directory structure.
8292            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8293                    pkg.applicationInfo.primaryCpuAbi == null) {
8294                setBundledAppAbisAndRoots(pkg, pkgSetting);
8295                setNativeLibraryPaths(pkg);
8296            }
8297
8298        } else {
8299            if ((scanFlags & SCAN_MOVE) != 0) {
8300                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8301                // but we already have this packages package info in the PackageSetting. We just
8302                // use that and derive the native library path based on the new codepath.
8303                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8304                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8305            }
8306
8307            // Set native library paths again. For moves, the path will be updated based on the
8308            // ABIs we've determined above. For non-moves, the path will be updated based on the
8309            // ABIs we determined during compilation, but the path will depend on the final
8310            // package path (after the rename away from the stage path).
8311            setNativeLibraryPaths(pkg);
8312        }
8313
8314        // This is a special case for the "system" package, where the ABI is
8315        // dictated by the zygote configuration (and init.rc). We should keep track
8316        // of this ABI so that we can deal with "normal" applications that run under
8317        // the same UID correctly.
8318        if (mPlatformPackage == pkg) {
8319            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8320                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8321        }
8322
8323        // If there's a mismatch between the abi-override in the package setting
8324        // and the abiOverride specified for the install. Warn about this because we
8325        // would've already compiled the app without taking the package setting into
8326        // account.
8327        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8328            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8329                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8330                        " for package " + pkg.packageName);
8331            }
8332        }
8333
8334        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8335        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8336        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8337
8338        // Copy the derived override back to the parsed package, so that we can
8339        // update the package settings accordingly.
8340        pkg.cpuAbiOverride = cpuAbiOverride;
8341
8342        if (DEBUG_ABI_SELECTION) {
8343            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8344                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8345                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8346        }
8347
8348        // Push the derived path down into PackageSettings so we know what to
8349        // clean up at uninstall time.
8350        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8351
8352        if (DEBUG_ABI_SELECTION) {
8353            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8354                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8355                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8356        }
8357
8358        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8359            // We don't do this here during boot because we can do it all
8360            // at once after scanning all existing packages.
8361            //
8362            // We also do this *before* we perform dexopt on this package, so that
8363            // we can avoid redundant dexopts, and also to make sure we've got the
8364            // code and package path correct.
8365            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8366                    pkg, true /* boot complete */);
8367        }
8368
8369        if (mFactoryTest && pkg.requestedPermissions.contains(
8370                android.Manifest.permission.FACTORY_TEST)) {
8371            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8372        }
8373
8374        ArrayList<PackageParser.Package> clientLibPkgs = null;
8375
8376        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8377            if (nonMutatedPs != null) {
8378                synchronized (mPackages) {
8379                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8380                }
8381            }
8382            return pkg;
8383        }
8384
8385        // Only privileged apps and updated privileged apps can add child packages.
8386        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8387            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8388                throw new PackageManagerException("Only privileged apps and updated "
8389                        + "privileged apps can add child packages. Ignoring package "
8390                        + pkg.packageName);
8391            }
8392            final int childCount = pkg.childPackages.size();
8393            for (int i = 0; i < childCount; i++) {
8394                PackageParser.Package childPkg = pkg.childPackages.get(i);
8395                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8396                        childPkg.packageName)) {
8397                    throw new PackageManagerException("Cannot override a child package of "
8398                            + "another disabled system app. Ignoring package " + pkg.packageName);
8399                }
8400            }
8401        }
8402
8403        // writer
8404        synchronized (mPackages) {
8405            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8406                // Only system apps can add new shared libraries.
8407                if (pkg.libraryNames != null) {
8408                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8409                        String name = pkg.libraryNames.get(i);
8410                        boolean allowed = false;
8411                        if (pkg.isUpdatedSystemApp()) {
8412                            // New library entries can only be added through the
8413                            // system image.  This is important to get rid of a lot
8414                            // of nasty edge cases: for example if we allowed a non-
8415                            // system update of the app to add a library, then uninstalling
8416                            // the update would make the library go away, and assumptions
8417                            // we made such as through app install filtering would now
8418                            // have allowed apps on the device which aren't compatible
8419                            // with it.  Better to just have the restriction here, be
8420                            // conservative, and create many fewer cases that can negatively
8421                            // impact the user experience.
8422                            final PackageSetting sysPs = mSettings
8423                                    .getDisabledSystemPkgLPr(pkg.packageName);
8424                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8425                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8426                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8427                                        allowed = true;
8428                                        break;
8429                                    }
8430                                }
8431                            }
8432                        } else {
8433                            allowed = true;
8434                        }
8435                        if (allowed) {
8436                            if (!mSharedLibraries.containsKey(name)) {
8437                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8438                            } else if (!name.equals(pkg.packageName)) {
8439                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8440                                        + name + " already exists; skipping");
8441                            }
8442                        } else {
8443                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8444                                    + name + " that is not declared on system image; skipping");
8445                        }
8446                    }
8447                    if ((scanFlags & SCAN_BOOTING) == 0) {
8448                        // If we are not booting, we need to update any applications
8449                        // that are clients of our shared library.  If we are booting,
8450                        // this will all be done once the scan is complete.
8451                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8452                    }
8453                }
8454            }
8455        }
8456
8457        if ((scanFlags & SCAN_BOOTING) != 0) {
8458            // No apps can run during boot scan, so they don't need to be frozen
8459        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8460            // Caller asked to not kill app, so it's probably not frozen
8461        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8462            // Caller asked us to ignore frozen check for some reason; they
8463            // probably didn't know the package name
8464        } else {
8465            // We're doing major surgery on this package, so it better be frozen
8466            // right now to keep it from launching
8467            checkPackageFrozen(pkgName);
8468        }
8469
8470        // Also need to kill any apps that are dependent on the library.
8471        if (clientLibPkgs != null) {
8472            for (int i=0; i<clientLibPkgs.size(); i++) {
8473                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8474                killApplication(clientPkg.applicationInfo.packageName,
8475                        clientPkg.applicationInfo.uid, "update lib");
8476            }
8477        }
8478
8479        // Make sure we're not adding any bogus keyset info
8480        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8481        ksms.assertScannedPackageValid(pkg);
8482
8483        // writer
8484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8485
8486        boolean createIdmapFailed = false;
8487        synchronized (mPackages) {
8488            // We don't expect installation to fail beyond this point
8489
8490            if (pkgSetting.pkg != null) {
8491                // Note that |user| might be null during the initial boot scan. If a codePath
8492                // for an app has changed during a boot scan, it's due to an app update that's
8493                // part of the system partition and marker changes must be applied to all users.
8494                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8495                    (user != null) ? user : UserHandle.ALL);
8496            }
8497
8498            // Add the new setting to mSettings
8499            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8500            // Add the new setting to mPackages
8501            mPackages.put(pkg.applicationInfo.packageName, pkg);
8502            // Make sure we don't accidentally delete its data.
8503            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8504            while (iter.hasNext()) {
8505                PackageCleanItem item = iter.next();
8506                if (pkgName.equals(item.packageName)) {
8507                    iter.remove();
8508                }
8509            }
8510
8511            // Take care of first install / last update times.
8512            if (currentTime != 0) {
8513                if (pkgSetting.firstInstallTime == 0) {
8514                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8515                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8516                    pkgSetting.lastUpdateTime = currentTime;
8517                }
8518            } else if (pkgSetting.firstInstallTime == 0) {
8519                // We need *something*.  Take time time stamp of the file.
8520                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8521            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8522                if (scanFileTime != pkgSetting.timeStamp) {
8523                    // A package on the system image has changed; consider this
8524                    // to be an update.
8525                    pkgSetting.lastUpdateTime = scanFileTime;
8526                }
8527            }
8528
8529            // Add the package's KeySets to the global KeySetManagerService
8530            ksms.addScannedPackageLPw(pkg);
8531
8532            int N = pkg.providers.size();
8533            StringBuilder r = null;
8534            int i;
8535            for (i=0; i<N; i++) {
8536                PackageParser.Provider p = pkg.providers.get(i);
8537                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8538                        p.info.processName, pkg.applicationInfo.uid);
8539                mProviders.addProvider(p);
8540                p.syncable = p.info.isSyncable;
8541                if (p.info.authority != null) {
8542                    String names[] = p.info.authority.split(";");
8543                    p.info.authority = null;
8544                    for (int j = 0; j < names.length; j++) {
8545                        if (j == 1 && p.syncable) {
8546                            // We only want the first authority for a provider to possibly be
8547                            // syncable, so if we already added this provider using a different
8548                            // authority clear the syncable flag. We copy the provider before
8549                            // changing it because the mProviders object contains a reference
8550                            // to a provider that we don't want to change.
8551                            // Only do this for the second authority since the resulting provider
8552                            // object can be the same for all future authorities for this provider.
8553                            p = new PackageParser.Provider(p);
8554                            p.syncable = false;
8555                        }
8556                        if (!mProvidersByAuthority.containsKey(names[j])) {
8557                            mProvidersByAuthority.put(names[j], p);
8558                            if (p.info.authority == null) {
8559                                p.info.authority = names[j];
8560                            } else {
8561                                p.info.authority = p.info.authority + ";" + names[j];
8562                            }
8563                            if (DEBUG_PACKAGE_SCANNING) {
8564                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8565                                    Log.d(TAG, "Registered content provider: " + names[j]
8566                                            + ", className = " + p.info.name + ", isSyncable = "
8567                                            + p.info.isSyncable);
8568                            }
8569                        } else {
8570                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8571                            Slog.w(TAG, "Skipping provider name " + names[j] +
8572                                    " (in package " + pkg.applicationInfo.packageName +
8573                                    "): name already used by "
8574                                    + ((other != null && other.getComponentName() != null)
8575                                            ? other.getComponentName().getPackageName() : "?"));
8576                        }
8577                    }
8578                }
8579                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8580                    if (r == null) {
8581                        r = new StringBuilder(256);
8582                    } else {
8583                        r.append(' ');
8584                    }
8585                    r.append(p.info.name);
8586                }
8587            }
8588            if (r != null) {
8589                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8590            }
8591
8592            N = pkg.services.size();
8593            r = null;
8594            for (i=0; i<N; i++) {
8595                PackageParser.Service s = pkg.services.get(i);
8596                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8597                        s.info.processName, pkg.applicationInfo.uid);
8598                mServices.addService(s);
8599                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8600                    if (r == null) {
8601                        r = new StringBuilder(256);
8602                    } else {
8603                        r.append(' ');
8604                    }
8605                    r.append(s.info.name);
8606                }
8607            }
8608            if (r != null) {
8609                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8610            }
8611
8612            N = pkg.receivers.size();
8613            r = null;
8614            for (i=0; i<N; i++) {
8615                PackageParser.Activity a = pkg.receivers.get(i);
8616                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8617                        a.info.processName, pkg.applicationInfo.uid);
8618                mReceivers.addActivity(a, "receiver");
8619                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8620                    if (r == null) {
8621                        r = new StringBuilder(256);
8622                    } else {
8623                        r.append(' ');
8624                    }
8625                    r.append(a.info.name);
8626                }
8627            }
8628            if (r != null) {
8629                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8630            }
8631
8632            N = pkg.activities.size();
8633            r = null;
8634            for (i=0; i<N; i++) {
8635                PackageParser.Activity a = pkg.activities.get(i);
8636                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8637                        a.info.processName, pkg.applicationInfo.uid);
8638                mActivities.addActivity(a, "activity");
8639                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8640                    if (r == null) {
8641                        r = new StringBuilder(256);
8642                    } else {
8643                        r.append(' ');
8644                    }
8645                    r.append(a.info.name);
8646                }
8647            }
8648            if (r != null) {
8649                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8650            }
8651
8652            N = pkg.permissionGroups.size();
8653            r = null;
8654            for (i=0; i<N; i++) {
8655                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8656                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8657                if (cur == null) {
8658                    mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
8666                    }
8667                } else {
8668                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8669                            + pg.info.packageName + " ignored: original from "
8670                            + cur.info.packageName);
8671                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8672                        if (r == null) {
8673                            r = new StringBuilder(256);
8674                        } else {
8675                            r.append(' ');
8676                        }
8677                        r.append("DUP:");
8678                        r.append(pg.info.name);
8679                    }
8680                }
8681            }
8682            if (r != null) {
8683                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8684            }
8685
8686            N = pkg.permissions.size();
8687            r = null;
8688            for (i=0; i<N; i++) {
8689                PackageParser.Permission p = pkg.permissions.get(i);
8690
8691                // Assume by default that we did not install this permission into the system.
8692                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8693
8694                // Now that permission groups have a special meaning, we ignore permission
8695                // groups for legacy apps to prevent unexpected behavior. In particular,
8696                // permissions for one app being granted to someone just becase they happen
8697                // to be in a group defined by another app (before this had no implications).
8698                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8699                    p.group = mPermissionGroups.get(p.info.group);
8700                    // Warn for a permission in an unknown group.
8701                    if (p.info.group != null && p.group == null) {
8702                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8703                                + p.info.packageName + " in an unknown group " + p.info.group);
8704                    }
8705                }
8706
8707                ArrayMap<String, BasePermission> permissionMap =
8708                        p.tree ? mSettings.mPermissionTrees
8709                                : mSettings.mPermissions;
8710                BasePermission bp = permissionMap.get(p.info.name);
8711
8712                // Allow system apps to redefine non-system permissions
8713                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8714                    final boolean currentOwnerIsSystem = (bp.perm != null
8715                            && isSystemApp(bp.perm.owner));
8716                    if (isSystemApp(p.owner)) {
8717                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8718                            // It's a built-in permission and no owner, take ownership now
8719                            bp.packageSetting = pkgSetting;
8720                            bp.perm = p;
8721                            bp.uid = pkg.applicationInfo.uid;
8722                            bp.sourcePackage = p.info.packageName;
8723                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8724                        } else if (!currentOwnerIsSystem) {
8725                            String msg = "New decl " + p.owner + " of permission  "
8726                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8727                            reportSettingsProblem(Log.WARN, msg);
8728                            bp = null;
8729                        }
8730                    }
8731                }
8732
8733                if (bp == null) {
8734                    bp = new BasePermission(p.info.name, p.info.packageName,
8735                            BasePermission.TYPE_NORMAL);
8736                    permissionMap.put(p.info.name, bp);
8737                }
8738
8739                if (bp.perm == null) {
8740                    if (bp.sourcePackage == null
8741                            || bp.sourcePackage.equals(p.info.packageName)) {
8742                        BasePermission tree = findPermissionTreeLP(p.info.name);
8743                        if (tree == null
8744                                || tree.sourcePackage.equals(p.info.packageName)) {
8745                            bp.packageSetting = pkgSetting;
8746                            bp.perm = p;
8747                            bp.uid = pkg.applicationInfo.uid;
8748                            bp.sourcePackage = p.info.packageName;
8749                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8750                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8751                                if (r == null) {
8752                                    r = new StringBuilder(256);
8753                                } else {
8754                                    r.append(' ');
8755                                }
8756                                r.append(p.info.name);
8757                            }
8758                        } else {
8759                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8760                                    + p.info.packageName + " ignored: base tree "
8761                                    + tree.name + " is from package "
8762                                    + tree.sourcePackage);
8763                        }
8764                    } else {
8765                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8766                                + p.info.packageName + " ignored: original from "
8767                                + bp.sourcePackage);
8768                    }
8769                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8770                    if (r == null) {
8771                        r = new StringBuilder(256);
8772                    } else {
8773                        r.append(' ');
8774                    }
8775                    r.append("DUP:");
8776                    r.append(p.info.name);
8777                }
8778                if (bp.perm == p) {
8779                    bp.protectionLevel = p.info.protectionLevel;
8780                }
8781            }
8782
8783            if (r != null) {
8784                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8785            }
8786
8787            N = pkg.instrumentation.size();
8788            r = null;
8789            for (i=0; i<N; i++) {
8790                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8791                a.info.packageName = pkg.applicationInfo.packageName;
8792                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8793                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8794                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8795                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8796                a.info.dataDir = pkg.applicationInfo.dataDir;
8797                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8798                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8799
8800                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8801                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8802                mInstrumentation.put(a.getComponentName(), a);
8803                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8804                    if (r == null) {
8805                        r = new StringBuilder(256);
8806                    } else {
8807                        r.append(' ');
8808                    }
8809                    r.append(a.info.name);
8810                }
8811            }
8812            if (r != null) {
8813                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8814            }
8815
8816            if (pkg.protectedBroadcasts != null) {
8817                N = pkg.protectedBroadcasts.size();
8818                for (i=0; i<N; i++) {
8819                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8820                }
8821            }
8822
8823            pkgSetting.setTimeStamp(scanFileTime);
8824
8825            // Create idmap files for pairs of (packages, overlay packages).
8826            // Note: "android", ie framework-res.apk, is handled by native layers.
8827            if (pkg.mOverlayTarget != null) {
8828                // This is an overlay package.
8829                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8830                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8831                        mOverlays.put(pkg.mOverlayTarget,
8832                                new ArrayMap<String, PackageParser.Package>());
8833                    }
8834                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8835                    map.put(pkg.packageName, pkg);
8836                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8837                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8838                        createIdmapFailed = true;
8839                    }
8840                }
8841            } else if (mOverlays.containsKey(pkg.packageName) &&
8842                    !pkg.packageName.equals("android")) {
8843                // This is a regular package, with one or more known overlay packages.
8844                createIdmapsForPackageLI(pkg);
8845            }
8846        }
8847
8848        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8849
8850        if (createIdmapFailed) {
8851            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8852                    "scanPackageLI failed to createIdmap");
8853        }
8854        return pkg;
8855    }
8856
8857    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8858            PackageParser.Package update, UserHandle user) {
8859        if (existing.applicationInfo == null || update.applicationInfo == null) {
8860            // This isn't due to an app installation.
8861            return;
8862        }
8863
8864        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8865        final File newCodePath = new File(update.applicationInfo.getCodePath());
8866
8867        // The codePath hasn't changed, so there's nothing for us to do.
8868        if (Objects.equals(oldCodePath, newCodePath)) {
8869            return;
8870        }
8871
8872        File canonicalNewCodePath;
8873        try {
8874            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8875        } catch (IOException e) {
8876            Slog.w(TAG, "Failed to get canonical path.", e);
8877            return;
8878        }
8879
8880        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8881        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8882        // that the last component of the path (i.e, the name) doesn't need canonicalization
8883        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8884        // but may change in the future. Hopefully this function won't exist at that point.
8885        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8886                oldCodePath.getName());
8887
8888        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8889        // with "@".
8890        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8891        if (!oldMarkerPrefix.endsWith("@")) {
8892            oldMarkerPrefix += "@";
8893        }
8894        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8895        if (!newMarkerPrefix.endsWith("@")) {
8896            newMarkerPrefix += "@";
8897        }
8898
8899        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8900        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8901        for (String updatedPath : updatedPaths) {
8902            String updatedPathName = new File(updatedPath).getName();
8903            markerSuffixes.add(updatedPathName.replace('/', '@'));
8904        }
8905
8906        for (int userId : resolveUserIds(user.getIdentifier())) {
8907            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8908
8909            for (String markerSuffix : markerSuffixes) {
8910                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8911                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8912                if (oldForeignUseMark.exists()) {
8913                    try {
8914                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8915                                newForeignUseMark.getAbsolutePath());
8916                    } catch (ErrnoException e) {
8917                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8918                        oldForeignUseMark.delete();
8919                    }
8920                }
8921            }
8922        }
8923    }
8924
8925    /**
8926     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8927     * is derived purely on the basis of the contents of {@code scanFile} and
8928     * {@code cpuAbiOverride}.
8929     *
8930     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8931     */
8932    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8933                                 String cpuAbiOverride, boolean extractLibs)
8934            throws PackageManagerException {
8935        // TODO: We can probably be smarter about this stuff. For installed apps,
8936        // we can calculate this information at install time once and for all. For
8937        // system apps, we can probably assume that this information doesn't change
8938        // after the first boot scan. As things stand, we do lots of unnecessary work.
8939
8940        // Give ourselves some initial paths; we'll come back for another
8941        // pass once we've determined ABI below.
8942        setNativeLibraryPaths(pkg);
8943
8944        // We would never need to extract libs for forward-locked and external packages,
8945        // since the container service will do it for us. We shouldn't attempt to
8946        // extract libs from system app when it was not updated.
8947        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8948                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8949            extractLibs = false;
8950        }
8951
8952        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8953        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8954
8955        NativeLibraryHelper.Handle handle = null;
8956        try {
8957            handle = NativeLibraryHelper.Handle.create(pkg);
8958            // TODO(multiArch): This can be null for apps that didn't go through the
8959            // usual installation process. We can calculate it again, like we
8960            // do during install time.
8961            //
8962            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8963            // unnecessary.
8964            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8965
8966            // Null out the abis so that they can be recalculated.
8967            pkg.applicationInfo.primaryCpuAbi = null;
8968            pkg.applicationInfo.secondaryCpuAbi = null;
8969            if (isMultiArch(pkg.applicationInfo)) {
8970                // Warn if we've set an abiOverride for multi-lib packages..
8971                // By definition, we need to copy both 32 and 64 bit libraries for
8972                // such packages.
8973                if (pkg.cpuAbiOverride != null
8974                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8975                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8976                }
8977
8978                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8979                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8980                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8981                    if (extractLibs) {
8982                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8983                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8984                                useIsaSpecificSubdirs);
8985                    } else {
8986                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8987                    }
8988                }
8989
8990                maybeThrowExceptionForMultiArchCopy(
8991                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8992
8993                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8994                    if (extractLibs) {
8995                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8996                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8997                                useIsaSpecificSubdirs);
8998                    } else {
8999                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9000                    }
9001                }
9002
9003                maybeThrowExceptionForMultiArchCopy(
9004                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9005
9006                if (abi64 >= 0) {
9007                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9008                }
9009
9010                if (abi32 >= 0) {
9011                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9012                    if (abi64 >= 0) {
9013                        if (pkg.use32bitAbi) {
9014                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9015                            pkg.applicationInfo.primaryCpuAbi = abi;
9016                        } else {
9017                            pkg.applicationInfo.secondaryCpuAbi = abi;
9018                        }
9019                    } else {
9020                        pkg.applicationInfo.primaryCpuAbi = abi;
9021                    }
9022                }
9023
9024            } else {
9025                String[] abiList = (cpuAbiOverride != null) ?
9026                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9027
9028                // Enable gross and lame hacks for apps that are built with old
9029                // SDK tools. We must scan their APKs for renderscript bitcode and
9030                // not launch them if it's present. Don't bother checking on devices
9031                // that don't have 64 bit support.
9032                boolean needsRenderScriptOverride = false;
9033                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9034                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9035                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9036                    needsRenderScriptOverride = true;
9037                }
9038
9039                final int copyRet;
9040                if (extractLibs) {
9041                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9042                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9043                } else {
9044                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9045                }
9046
9047                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9048                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9049                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9050                }
9051
9052                if (copyRet >= 0) {
9053                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9054                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9055                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9056                } else if (needsRenderScriptOverride) {
9057                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9058                }
9059            }
9060        } catch (IOException ioe) {
9061            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9062        } finally {
9063            IoUtils.closeQuietly(handle);
9064        }
9065
9066        // Now that we've calculated the ABIs and determined if it's an internal app,
9067        // we will go ahead and populate the nativeLibraryPath.
9068        setNativeLibraryPaths(pkg);
9069    }
9070
9071    /**
9072     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9073     * i.e, so that all packages can be run inside a single process if required.
9074     *
9075     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9076     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9077     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9078     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9079     * updating a package that belongs to a shared user.
9080     *
9081     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9082     * adds unnecessary complexity.
9083     */
9084    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9085            PackageParser.Package scannedPackage, boolean bootComplete) {
9086        String requiredInstructionSet = null;
9087        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9088            requiredInstructionSet = VMRuntime.getInstructionSet(
9089                     scannedPackage.applicationInfo.primaryCpuAbi);
9090        }
9091
9092        PackageSetting requirer = null;
9093        for (PackageSetting ps : packagesForUser) {
9094            // If packagesForUser contains scannedPackage, we skip it. This will happen
9095            // when scannedPackage is an update of an existing package. Without this check,
9096            // we will never be able to change the ABI of any package belonging to a shared
9097            // user, even if it's compatible with other packages.
9098            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9099                if (ps.primaryCpuAbiString == null) {
9100                    continue;
9101                }
9102
9103                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9104                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9105                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9106                    // this but there's not much we can do.
9107                    String errorMessage = "Instruction set mismatch, "
9108                            + ((requirer == null) ? "[caller]" : requirer)
9109                            + " requires " + requiredInstructionSet + " whereas " + ps
9110                            + " requires " + instructionSet;
9111                    Slog.w(TAG, errorMessage);
9112                }
9113
9114                if (requiredInstructionSet == null) {
9115                    requiredInstructionSet = instructionSet;
9116                    requirer = ps;
9117                }
9118            }
9119        }
9120
9121        if (requiredInstructionSet != null) {
9122            String adjustedAbi;
9123            if (requirer != null) {
9124                // requirer != null implies that either scannedPackage was null or that scannedPackage
9125                // did not require an ABI, in which case we have to adjust scannedPackage to match
9126                // the ABI of the set (which is the same as requirer's ABI)
9127                adjustedAbi = requirer.primaryCpuAbiString;
9128                if (scannedPackage != null) {
9129                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9130                }
9131            } else {
9132                // requirer == null implies that we're updating all ABIs in the set to
9133                // match scannedPackage.
9134                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9135            }
9136
9137            for (PackageSetting ps : packagesForUser) {
9138                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9139                    if (ps.primaryCpuAbiString != null) {
9140                        continue;
9141                    }
9142
9143                    ps.primaryCpuAbiString = adjustedAbi;
9144                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9145                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9146                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9147                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9148                                + " (requirer="
9149                                + (requirer == null ? "null" : requirer.pkg.packageName)
9150                                + ", scannedPackage="
9151                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9152                                + ")");
9153                        try {
9154                            mInstaller.rmdex(ps.codePathString,
9155                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9156                        } catch (InstallerException ignored) {
9157                        }
9158                    }
9159                }
9160            }
9161        }
9162    }
9163
9164    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9165        synchronized (mPackages) {
9166            mResolverReplaced = true;
9167            // Set up information for custom user intent resolution activity.
9168            mResolveActivity.applicationInfo = pkg.applicationInfo;
9169            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9170            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9171            mResolveActivity.processName = pkg.applicationInfo.packageName;
9172            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9173            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9174                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9175            mResolveActivity.theme = 0;
9176            mResolveActivity.exported = true;
9177            mResolveActivity.enabled = true;
9178            mResolveInfo.activityInfo = mResolveActivity;
9179            mResolveInfo.priority = 0;
9180            mResolveInfo.preferredOrder = 0;
9181            mResolveInfo.match = 0;
9182            mResolveComponentName = mCustomResolverComponentName;
9183            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9184                    mResolveComponentName);
9185        }
9186    }
9187
9188    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9189        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9190
9191        // Set up information for ephemeral installer activity
9192        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9193        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9194        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9195        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9196        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9197        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9198                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9199        mEphemeralInstallerActivity.theme = 0;
9200        mEphemeralInstallerActivity.exported = true;
9201        mEphemeralInstallerActivity.enabled = true;
9202        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9203        mEphemeralInstallerInfo.priority = 0;
9204        mEphemeralInstallerInfo.preferredOrder = 0;
9205        mEphemeralInstallerInfo.match = 0;
9206
9207        if (DEBUG_EPHEMERAL) {
9208            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9209        }
9210    }
9211
9212    private static String calculateBundledApkRoot(final String codePathString) {
9213        final File codePath = new File(codePathString);
9214        final File codeRoot;
9215        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9216            codeRoot = Environment.getRootDirectory();
9217        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9218            codeRoot = Environment.getOemDirectory();
9219        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9220            codeRoot = Environment.getVendorDirectory();
9221        } else {
9222            // Unrecognized code path; take its top real segment as the apk root:
9223            // e.g. /something/app/blah.apk => /something
9224            try {
9225                File f = codePath.getCanonicalFile();
9226                File parent = f.getParentFile();    // non-null because codePath is a file
9227                File tmp;
9228                while ((tmp = parent.getParentFile()) != null) {
9229                    f = parent;
9230                    parent = tmp;
9231                }
9232                codeRoot = f;
9233                Slog.w(TAG, "Unrecognized code path "
9234                        + codePath + " - using " + codeRoot);
9235            } catch (IOException e) {
9236                // Can't canonicalize the code path -- shenanigans?
9237                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9238                return Environment.getRootDirectory().getPath();
9239            }
9240        }
9241        return codeRoot.getPath();
9242    }
9243
9244    /**
9245     * Derive and set the location of native libraries for the given package,
9246     * which varies depending on where and how the package was installed.
9247     */
9248    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9249        final ApplicationInfo info = pkg.applicationInfo;
9250        final String codePath = pkg.codePath;
9251        final File codeFile = new File(codePath);
9252        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9253        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9254
9255        info.nativeLibraryRootDir = null;
9256        info.nativeLibraryRootRequiresIsa = false;
9257        info.nativeLibraryDir = null;
9258        info.secondaryNativeLibraryDir = null;
9259
9260        if (isApkFile(codeFile)) {
9261            // Monolithic install
9262            if (bundledApp) {
9263                // If "/system/lib64/apkname" exists, assume that is the per-package
9264                // native library directory to use; otherwise use "/system/lib/apkname".
9265                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9266                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9267                        getPrimaryInstructionSet(info));
9268
9269                // This is a bundled system app so choose the path based on the ABI.
9270                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9271                // is just the default path.
9272                final String apkName = deriveCodePathName(codePath);
9273                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9274                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9275                        apkName).getAbsolutePath();
9276
9277                if (info.secondaryCpuAbi != null) {
9278                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9279                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9280                            secondaryLibDir, apkName).getAbsolutePath();
9281                }
9282            } else if (asecApp) {
9283                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9284                        .getAbsolutePath();
9285            } else {
9286                final String apkName = deriveCodePathName(codePath);
9287                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9288                        .getAbsolutePath();
9289            }
9290
9291            info.nativeLibraryRootRequiresIsa = false;
9292            info.nativeLibraryDir = info.nativeLibraryRootDir;
9293        } else {
9294            // Cluster install
9295            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9296            info.nativeLibraryRootRequiresIsa = true;
9297
9298            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9299                    getPrimaryInstructionSet(info)).getAbsolutePath();
9300
9301            if (info.secondaryCpuAbi != null) {
9302                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9303                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9304            }
9305        }
9306    }
9307
9308    /**
9309     * Calculate the abis and roots for a bundled app. These can uniquely
9310     * be determined from the contents of the system partition, i.e whether
9311     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9312     * of this information, and instead assume that the system was built
9313     * sensibly.
9314     */
9315    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9316                                           PackageSetting pkgSetting) {
9317        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9318
9319        // If "/system/lib64/apkname" exists, assume that is the per-package
9320        // native library directory to use; otherwise use "/system/lib/apkname".
9321        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9322        setBundledAppAbi(pkg, apkRoot, apkName);
9323        // pkgSetting might be null during rescan following uninstall of updates
9324        // to a bundled app, so accommodate that possibility.  The settings in
9325        // that case will be established later from the parsed package.
9326        //
9327        // If the settings aren't null, sync them up with what we've just derived.
9328        // note that apkRoot isn't stored in the package settings.
9329        if (pkgSetting != null) {
9330            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9331            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9332        }
9333    }
9334
9335    /**
9336     * Deduces the ABI of a bundled app and sets the relevant fields on the
9337     * parsed pkg object.
9338     *
9339     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9340     *        under which system libraries are installed.
9341     * @param apkName the name of the installed package.
9342     */
9343    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9344        final File codeFile = new File(pkg.codePath);
9345
9346        final boolean has64BitLibs;
9347        final boolean has32BitLibs;
9348        if (isApkFile(codeFile)) {
9349            // Monolithic install
9350            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9351            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9352        } else {
9353            // Cluster install
9354            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9355            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9356                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9357                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9358                has64BitLibs = (new File(rootDir, isa)).exists();
9359            } else {
9360                has64BitLibs = false;
9361            }
9362            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9363                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9364                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9365                has32BitLibs = (new File(rootDir, isa)).exists();
9366            } else {
9367                has32BitLibs = false;
9368            }
9369        }
9370
9371        if (has64BitLibs && !has32BitLibs) {
9372            // The package has 64 bit libs, but not 32 bit libs. Its primary
9373            // ABI should be 64 bit. We can safely assume here that the bundled
9374            // native libraries correspond to the most preferred ABI in the list.
9375
9376            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9377            pkg.applicationInfo.secondaryCpuAbi = null;
9378        } else if (has32BitLibs && !has64BitLibs) {
9379            // The package has 32 bit libs but not 64 bit libs. Its primary
9380            // ABI should be 32 bit.
9381
9382            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9383            pkg.applicationInfo.secondaryCpuAbi = null;
9384        } else if (has32BitLibs && has64BitLibs) {
9385            // The application has both 64 and 32 bit bundled libraries. We check
9386            // here that the app declares multiArch support, and warn if it doesn't.
9387            //
9388            // We will be lenient here and record both ABIs. The primary will be the
9389            // ABI that's higher on the list, i.e, a device that's configured to prefer
9390            // 64 bit apps will see a 64 bit primary ABI,
9391
9392            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9393                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9394            }
9395
9396            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9397                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9398                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9399            } else {
9400                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9401                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9402            }
9403        } else {
9404            pkg.applicationInfo.primaryCpuAbi = null;
9405            pkg.applicationInfo.secondaryCpuAbi = null;
9406        }
9407    }
9408
9409    private void killApplication(String pkgName, int appId, String reason) {
9410        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9411    }
9412
9413    private void killApplication(String pkgName, int appId, int userId, String reason) {
9414        // Request the ActivityManager to kill the process(only for existing packages)
9415        // so that we do not end up in a confused state while the user is still using the older
9416        // version of the application while the new one gets installed.
9417        final long token = Binder.clearCallingIdentity();
9418        try {
9419            IActivityManager am = ActivityManagerNative.getDefault();
9420            if (am != null) {
9421                try {
9422                    am.killApplication(pkgName, appId, userId, reason);
9423                } catch (RemoteException e) {
9424                }
9425            }
9426        } finally {
9427            Binder.restoreCallingIdentity(token);
9428        }
9429    }
9430
9431    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9432        // Remove the parent package setting
9433        PackageSetting ps = (PackageSetting) pkg.mExtras;
9434        if (ps != null) {
9435            removePackageLI(ps, chatty);
9436        }
9437        // Remove the child package setting
9438        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9439        for (int i = 0; i < childCount; i++) {
9440            PackageParser.Package childPkg = pkg.childPackages.get(i);
9441            ps = (PackageSetting) childPkg.mExtras;
9442            if (ps != null) {
9443                removePackageLI(ps, chatty);
9444            }
9445        }
9446    }
9447
9448    void removePackageLI(PackageSetting ps, boolean chatty) {
9449        if (DEBUG_INSTALL) {
9450            if (chatty)
9451                Log.d(TAG, "Removing package " + ps.name);
9452        }
9453
9454        // writer
9455        synchronized (mPackages) {
9456            mPackages.remove(ps.name);
9457            final PackageParser.Package pkg = ps.pkg;
9458            if (pkg != null) {
9459                cleanPackageDataStructuresLILPw(pkg, chatty);
9460            }
9461        }
9462    }
9463
9464    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9465        if (DEBUG_INSTALL) {
9466            if (chatty)
9467                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9468        }
9469
9470        // writer
9471        synchronized (mPackages) {
9472            // Remove the parent package
9473            mPackages.remove(pkg.applicationInfo.packageName);
9474            cleanPackageDataStructuresLILPw(pkg, chatty);
9475
9476            // Remove the child packages
9477            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9478            for (int i = 0; i < childCount; i++) {
9479                PackageParser.Package childPkg = pkg.childPackages.get(i);
9480                mPackages.remove(childPkg.applicationInfo.packageName);
9481                cleanPackageDataStructuresLILPw(childPkg, chatty);
9482            }
9483        }
9484    }
9485
9486    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9487        int N = pkg.providers.size();
9488        StringBuilder r = null;
9489        int i;
9490        for (i=0; i<N; i++) {
9491            PackageParser.Provider p = pkg.providers.get(i);
9492            mProviders.removeProvider(p);
9493            if (p.info.authority == null) {
9494
9495                /* There was another ContentProvider with this authority when
9496                 * this app was installed so this authority is null,
9497                 * Ignore it as we don't have to unregister the provider.
9498                 */
9499                continue;
9500            }
9501            String names[] = p.info.authority.split(";");
9502            for (int j = 0; j < names.length; j++) {
9503                if (mProvidersByAuthority.get(names[j]) == p) {
9504                    mProvidersByAuthority.remove(names[j]);
9505                    if (DEBUG_REMOVE) {
9506                        if (chatty)
9507                            Log.d(TAG, "Unregistered content provider: " + names[j]
9508                                    + ", className = " + p.info.name + ", isSyncable = "
9509                                    + p.info.isSyncable);
9510                    }
9511                }
9512            }
9513            if (DEBUG_REMOVE && chatty) {
9514                if (r == null) {
9515                    r = new StringBuilder(256);
9516                } else {
9517                    r.append(' ');
9518                }
9519                r.append(p.info.name);
9520            }
9521        }
9522        if (r != null) {
9523            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9524        }
9525
9526        N = pkg.services.size();
9527        r = null;
9528        for (i=0; i<N; i++) {
9529            PackageParser.Service s = pkg.services.get(i);
9530            mServices.removeService(s);
9531            if (chatty) {
9532                if (r == null) {
9533                    r = new StringBuilder(256);
9534                } else {
9535                    r.append(' ');
9536                }
9537                r.append(s.info.name);
9538            }
9539        }
9540        if (r != null) {
9541            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9542        }
9543
9544        N = pkg.receivers.size();
9545        r = null;
9546        for (i=0; i<N; i++) {
9547            PackageParser.Activity a = pkg.receivers.get(i);
9548            mReceivers.removeActivity(a, "receiver");
9549            if (DEBUG_REMOVE && chatty) {
9550                if (r == null) {
9551                    r = new StringBuilder(256);
9552                } else {
9553                    r.append(' ');
9554                }
9555                r.append(a.info.name);
9556            }
9557        }
9558        if (r != null) {
9559            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9560        }
9561
9562        N = pkg.activities.size();
9563        r = null;
9564        for (i=0; i<N; i++) {
9565            PackageParser.Activity a = pkg.activities.get(i);
9566            mActivities.removeActivity(a, "activity");
9567            if (DEBUG_REMOVE && chatty) {
9568                if (r == null) {
9569                    r = new StringBuilder(256);
9570                } else {
9571                    r.append(' ');
9572                }
9573                r.append(a.info.name);
9574            }
9575        }
9576        if (r != null) {
9577            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9578        }
9579
9580        N = pkg.permissions.size();
9581        r = null;
9582        for (i=0; i<N; i++) {
9583            PackageParser.Permission p = pkg.permissions.get(i);
9584            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9585            if (bp == null) {
9586                bp = mSettings.mPermissionTrees.get(p.info.name);
9587            }
9588            if (bp != null && bp.perm == p) {
9589                bp.perm = null;
9590                if (DEBUG_REMOVE && chatty) {
9591                    if (r == null) {
9592                        r = new StringBuilder(256);
9593                    } else {
9594                        r.append(' ');
9595                    }
9596                    r.append(p.info.name);
9597                }
9598            }
9599            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9600                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9601                if (appOpPkgs != null) {
9602                    appOpPkgs.remove(pkg.packageName);
9603                }
9604            }
9605        }
9606        if (r != null) {
9607            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9608        }
9609
9610        N = pkg.requestedPermissions.size();
9611        r = null;
9612        for (i=0; i<N; i++) {
9613            String perm = pkg.requestedPermissions.get(i);
9614            BasePermission bp = mSettings.mPermissions.get(perm);
9615            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9616                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9617                if (appOpPkgs != null) {
9618                    appOpPkgs.remove(pkg.packageName);
9619                    if (appOpPkgs.isEmpty()) {
9620                        mAppOpPermissionPackages.remove(perm);
9621                    }
9622                }
9623            }
9624        }
9625        if (r != null) {
9626            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9627        }
9628
9629        N = pkg.instrumentation.size();
9630        r = null;
9631        for (i=0; i<N; i++) {
9632            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9633            mInstrumentation.remove(a.getComponentName());
9634            if (DEBUG_REMOVE && chatty) {
9635                if (r == null) {
9636                    r = new StringBuilder(256);
9637                } else {
9638                    r.append(' ');
9639                }
9640                r.append(a.info.name);
9641            }
9642        }
9643        if (r != null) {
9644            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9645        }
9646
9647        r = null;
9648        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9649            // Only system apps can hold shared libraries.
9650            if (pkg.libraryNames != null) {
9651                for (i=0; i<pkg.libraryNames.size(); i++) {
9652                    String name = pkg.libraryNames.get(i);
9653                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9654                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9655                        mSharedLibraries.remove(name);
9656                        if (DEBUG_REMOVE && chatty) {
9657                            if (r == null) {
9658                                r = new StringBuilder(256);
9659                            } else {
9660                                r.append(' ');
9661                            }
9662                            r.append(name);
9663                        }
9664                    }
9665                }
9666            }
9667        }
9668        if (r != null) {
9669            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9670        }
9671    }
9672
9673    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9674        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9675            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9676                return true;
9677            }
9678        }
9679        return false;
9680    }
9681
9682    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9683    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9684    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9685
9686    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9687        // Update the parent permissions
9688        updatePermissionsLPw(pkg.packageName, pkg, flags);
9689        // Update the child permissions
9690        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9691        for (int i = 0; i < childCount; i++) {
9692            PackageParser.Package childPkg = pkg.childPackages.get(i);
9693            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9694        }
9695    }
9696
9697    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9698            int flags) {
9699        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9700        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9701    }
9702
9703    private void updatePermissionsLPw(String changingPkg,
9704            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9705        // Make sure there are no dangling permission trees.
9706        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9707        while (it.hasNext()) {
9708            final BasePermission bp = it.next();
9709            if (bp.packageSetting == null) {
9710                // We may not yet have parsed the package, so just see if
9711                // we still know about its settings.
9712                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9713            }
9714            if (bp.packageSetting == null) {
9715                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9716                        + " from package " + bp.sourcePackage);
9717                it.remove();
9718            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9719                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9720                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9721                            + " from package " + bp.sourcePackage);
9722                    flags |= UPDATE_PERMISSIONS_ALL;
9723                    it.remove();
9724                }
9725            }
9726        }
9727
9728        // Make sure all dynamic permissions have been assigned to a package,
9729        // and make sure there are no dangling permissions.
9730        it = mSettings.mPermissions.values().iterator();
9731        while (it.hasNext()) {
9732            final BasePermission bp = it.next();
9733            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9734                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9735                        + bp.name + " pkg=" + bp.sourcePackage
9736                        + " info=" + bp.pendingInfo);
9737                if (bp.packageSetting == null && bp.pendingInfo != null) {
9738                    final BasePermission tree = findPermissionTreeLP(bp.name);
9739                    if (tree != null && tree.perm != null) {
9740                        bp.packageSetting = tree.packageSetting;
9741                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9742                                new PermissionInfo(bp.pendingInfo));
9743                        bp.perm.info.packageName = tree.perm.info.packageName;
9744                        bp.perm.info.name = bp.name;
9745                        bp.uid = tree.uid;
9746                    }
9747                }
9748            }
9749            if (bp.packageSetting == null) {
9750                // We may not yet have parsed the package, so just see if
9751                // we still know about its settings.
9752                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9753            }
9754            if (bp.packageSetting == null) {
9755                Slog.w(TAG, "Removing dangling permission: " + bp.name
9756                        + " from package " + bp.sourcePackage);
9757                it.remove();
9758            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9759                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9760                    Slog.i(TAG, "Removing old permission: " + bp.name
9761                            + " from package " + bp.sourcePackage);
9762                    flags |= UPDATE_PERMISSIONS_ALL;
9763                    it.remove();
9764                }
9765            }
9766        }
9767
9768        // Now update the permissions for all packages, in particular
9769        // replace the granted permissions of the system packages.
9770        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9771            for (PackageParser.Package pkg : mPackages.values()) {
9772                if (pkg != pkgInfo) {
9773                    // Only replace for packages on requested volume
9774                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9775                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9776                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9777                    grantPermissionsLPw(pkg, replace, changingPkg);
9778                }
9779            }
9780        }
9781
9782        if (pkgInfo != null) {
9783            // Only replace for packages on requested volume
9784            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9785            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9786                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9787            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9788        }
9789    }
9790
9791    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9792            String packageOfInterest) {
9793        // IMPORTANT: There are two types of permissions: install and runtime.
9794        // Install time permissions are granted when the app is installed to
9795        // all device users and users added in the future. Runtime permissions
9796        // are granted at runtime explicitly to specific users. Normal and signature
9797        // protected permissions are install time permissions. Dangerous permissions
9798        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9799        // otherwise they are runtime permissions. This function does not manage
9800        // runtime permissions except for the case an app targeting Lollipop MR1
9801        // being upgraded to target a newer SDK, in which case dangerous permissions
9802        // are transformed from install time to runtime ones.
9803
9804        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9805        if (ps == null) {
9806            return;
9807        }
9808
9809        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9810
9811        PermissionsState permissionsState = ps.getPermissionsState();
9812        PermissionsState origPermissions = permissionsState;
9813
9814        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9815
9816        boolean runtimePermissionsRevoked = false;
9817        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9818
9819        boolean changedInstallPermission = false;
9820
9821        if (replace) {
9822            ps.installPermissionsFixed = false;
9823            if (!ps.isSharedUser()) {
9824                origPermissions = new PermissionsState(permissionsState);
9825                permissionsState.reset();
9826            } else {
9827                // We need to know only about runtime permission changes since the
9828                // calling code always writes the install permissions state but
9829                // the runtime ones are written only if changed. The only cases of
9830                // changed runtime permissions here are promotion of an install to
9831                // runtime and revocation of a runtime from a shared user.
9832                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9833                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9834                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9835                    runtimePermissionsRevoked = true;
9836                }
9837            }
9838        }
9839
9840        permissionsState.setGlobalGids(mGlobalGids);
9841
9842        final int N = pkg.requestedPermissions.size();
9843        for (int i=0; i<N; i++) {
9844            final String name = pkg.requestedPermissions.get(i);
9845            final BasePermission bp = mSettings.mPermissions.get(name);
9846
9847            if (DEBUG_INSTALL) {
9848                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9849            }
9850
9851            if (bp == null || bp.packageSetting == null) {
9852                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9853                    Slog.w(TAG, "Unknown permission " + name
9854                            + " in package " + pkg.packageName);
9855                }
9856                continue;
9857            }
9858
9859            final String perm = bp.name;
9860            boolean allowedSig = false;
9861            int grant = GRANT_DENIED;
9862
9863            // Keep track of app op permissions.
9864            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9865                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9866                if (pkgs == null) {
9867                    pkgs = new ArraySet<>();
9868                    mAppOpPermissionPackages.put(bp.name, pkgs);
9869                }
9870                pkgs.add(pkg.packageName);
9871            }
9872
9873            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9874            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9875                    >= Build.VERSION_CODES.M;
9876            switch (level) {
9877                case PermissionInfo.PROTECTION_NORMAL: {
9878                    // For all apps normal permissions are install time ones.
9879                    grant = GRANT_INSTALL;
9880                } break;
9881
9882                case PermissionInfo.PROTECTION_DANGEROUS: {
9883                    // If a permission review is required for legacy apps we represent
9884                    // their permissions as always granted runtime ones since we need
9885                    // to keep the review required permission flag per user while an
9886                    // install permission's state is shared across all users.
9887                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9888                        // For legacy apps dangerous permissions are install time ones.
9889                        grant = GRANT_INSTALL;
9890                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9891                        // For legacy apps that became modern, install becomes runtime.
9892                        grant = GRANT_UPGRADE;
9893                    } else if (mPromoteSystemApps
9894                            && isSystemApp(ps)
9895                            && mExistingSystemPackages.contains(ps.name)) {
9896                        // For legacy system apps, install becomes runtime.
9897                        // We cannot check hasInstallPermission() for system apps since those
9898                        // permissions were granted implicitly and not persisted pre-M.
9899                        grant = GRANT_UPGRADE;
9900                    } else {
9901                        // For modern apps keep runtime permissions unchanged.
9902                        grant = GRANT_RUNTIME;
9903                    }
9904                } break;
9905
9906                case PermissionInfo.PROTECTION_SIGNATURE: {
9907                    // For all apps signature permissions are install time ones.
9908                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9909                    if (allowedSig) {
9910                        grant = GRANT_INSTALL;
9911                    }
9912                } break;
9913            }
9914
9915            if (DEBUG_INSTALL) {
9916                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9917            }
9918
9919            if (grant != GRANT_DENIED) {
9920                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9921                    // If this is an existing, non-system package, then
9922                    // we can't add any new permissions to it.
9923                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9924                        // Except...  if this is a permission that was added
9925                        // to the platform (note: need to only do this when
9926                        // updating the platform).
9927                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9928                            grant = GRANT_DENIED;
9929                        }
9930                    }
9931                }
9932
9933                switch (grant) {
9934                    case GRANT_INSTALL: {
9935                        // Revoke this as runtime permission to handle the case of
9936                        // a runtime permission being downgraded to an install one.
9937                        // Also in permission review mode we keep dangerous permissions
9938                        // for legacy apps
9939                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9940                            if (origPermissions.getRuntimePermissionState(
9941                                    bp.name, userId) != null) {
9942                                // Revoke the runtime permission and clear the flags.
9943                                origPermissions.revokeRuntimePermission(bp, userId);
9944                                origPermissions.updatePermissionFlags(bp, userId,
9945                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9946                                // If we revoked a permission permission, we have to write.
9947                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9948                                        changedRuntimePermissionUserIds, userId);
9949                            }
9950                        }
9951                        // Grant an install permission.
9952                        if (permissionsState.grantInstallPermission(bp) !=
9953                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9954                            changedInstallPermission = true;
9955                        }
9956                    } break;
9957
9958                    case GRANT_RUNTIME: {
9959                        // Grant previously granted runtime permissions.
9960                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9961                            PermissionState permissionState = origPermissions
9962                                    .getRuntimePermissionState(bp.name, userId);
9963                            int flags = permissionState != null
9964                                    ? permissionState.getFlags() : 0;
9965                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9966                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9967                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9968                                    // If we cannot put the permission as it was, we have to write.
9969                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9970                                            changedRuntimePermissionUserIds, userId);
9971                                }
9972                                // If the app supports runtime permissions no need for a review.
9973                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9974                                        && appSupportsRuntimePermissions
9975                                        && (flags & PackageManager
9976                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9977                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9978                                    // Since we changed the flags, we have to write.
9979                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9980                                            changedRuntimePermissionUserIds, userId);
9981                                }
9982                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9983                                    && !appSupportsRuntimePermissions) {
9984                                // For legacy apps that need a permission review, every new
9985                                // runtime permission is granted but it is pending a review.
9986                                // We also need to review only platform defined runtime
9987                                // permissions as these are the only ones the platform knows
9988                                // how to disable the API to simulate revocation as legacy
9989                                // apps don't expect to run with revoked permissions.
9990                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9991                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9992                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9993                                        // We changed the flags, hence have to write.
9994                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9995                                                changedRuntimePermissionUserIds, userId);
9996                                    }
9997                                }
9998                                if (permissionsState.grantRuntimePermission(bp, userId)
9999                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10000                                    // We changed the permission, hence have to write.
10001                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10002                                            changedRuntimePermissionUserIds, userId);
10003                                }
10004                            }
10005                            // Propagate the permission flags.
10006                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10007                        }
10008                    } break;
10009
10010                    case GRANT_UPGRADE: {
10011                        // Grant runtime permissions for a previously held install permission.
10012                        PermissionState permissionState = origPermissions
10013                                .getInstallPermissionState(bp.name);
10014                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10015
10016                        if (origPermissions.revokeInstallPermission(bp)
10017                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10018                            // We will be transferring the permission flags, so clear them.
10019                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10020                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10021                            changedInstallPermission = true;
10022                        }
10023
10024                        // If the permission is not to be promoted to runtime we ignore it and
10025                        // also its other flags as they are not applicable to install permissions.
10026                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10027                            for (int userId : currentUserIds) {
10028                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10029                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10030                                    // Transfer the permission flags.
10031                                    permissionsState.updatePermissionFlags(bp, userId,
10032                                            flags, flags);
10033                                    // If we granted the permission, we have to write.
10034                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10035                                            changedRuntimePermissionUserIds, userId);
10036                                }
10037                            }
10038                        }
10039                    } break;
10040
10041                    default: {
10042                        if (packageOfInterest == null
10043                                || packageOfInterest.equals(pkg.packageName)) {
10044                            Slog.w(TAG, "Not granting permission " + perm
10045                                    + " to package " + pkg.packageName
10046                                    + " because it was previously installed without");
10047                        }
10048                    } break;
10049                }
10050            } else {
10051                if (permissionsState.revokeInstallPermission(bp) !=
10052                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10053                    // Also drop the permission flags.
10054                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10055                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10056                    changedInstallPermission = true;
10057                    Slog.i(TAG, "Un-granting permission " + perm
10058                            + " from package " + pkg.packageName
10059                            + " (protectionLevel=" + bp.protectionLevel
10060                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10061                            + ")");
10062                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10063                    // Don't print warning for app op permissions, since it is fine for them
10064                    // not to be granted, there is a UI for the user to decide.
10065                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10066                        Slog.w(TAG, "Not granting permission " + perm
10067                                + " to package " + pkg.packageName
10068                                + " (protectionLevel=" + bp.protectionLevel
10069                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10070                                + ")");
10071                    }
10072                }
10073            }
10074        }
10075
10076        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10077                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10078            // This is the first that we have heard about this package, so the
10079            // permissions we have now selected are fixed until explicitly
10080            // changed.
10081            ps.installPermissionsFixed = true;
10082        }
10083
10084        // Persist the runtime permissions state for users with changes. If permissions
10085        // were revoked because no app in the shared user declares them we have to
10086        // write synchronously to avoid losing runtime permissions state.
10087        for (int userId : changedRuntimePermissionUserIds) {
10088            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10089        }
10090
10091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10092    }
10093
10094    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10095        boolean allowed = false;
10096        final int NP = PackageParser.NEW_PERMISSIONS.length;
10097        for (int ip=0; ip<NP; ip++) {
10098            final PackageParser.NewPermissionInfo npi
10099                    = PackageParser.NEW_PERMISSIONS[ip];
10100            if (npi.name.equals(perm)
10101                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10102                allowed = true;
10103                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10104                        + pkg.packageName);
10105                break;
10106            }
10107        }
10108        return allowed;
10109    }
10110
10111    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10112            BasePermission bp, PermissionsState origPermissions) {
10113        boolean allowed;
10114        allowed = (compareSignatures(
10115                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10116                        == PackageManager.SIGNATURE_MATCH)
10117                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10118                        == PackageManager.SIGNATURE_MATCH);
10119        if (!allowed && (bp.protectionLevel
10120                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10121            if (isSystemApp(pkg)) {
10122                // For updated system applications, a system permission
10123                // is granted only if it had been defined by the original application.
10124                if (pkg.isUpdatedSystemApp()) {
10125                    final PackageSetting sysPs = mSettings
10126                            .getDisabledSystemPkgLPr(pkg.packageName);
10127                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10128                        // If the original was granted this permission, we take
10129                        // that grant decision as read and propagate it to the
10130                        // update.
10131                        if (sysPs.isPrivileged()) {
10132                            allowed = true;
10133                        }
10134                    } else {
10135                        // The system apk may have been updated with an older
10136                        // version of the one on the data partition, but which
10137                        // granted a new system permission that it didn't have
10138                        // before.  In this case we do want to allow the app to
10139                        // now get the new permission if the ancestral apk is
10140                        // privileged to get it.
10141                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10142                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10143                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10144                                    allowed = true;
10145                                    break;
10146                                }
10147                            }
10148                        }
10149                        // Also if a privileged parent package on the system image or any of
10150                        // its children requested a privileged permission, the updated child
10151                        // packages can also get the permission.
10152                        if (pkg.parentPackage != null) {
10153                            final PackageSetting disabledSysParentPs = mSettings
10154                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10155                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10156                                    && disabledSysParentPs.isPrivileged()) {
10157                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10158                                    allowed = true;
10159                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10160                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10161                                    for (int i = 0; i < count; i++) {
10162                                        PackageParser.Package disabledSysChildPkg =
10163                                                disabledSysParentPs.pkg.childPackages.get(i);
10164                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10165                                                perm)) {
10166                                            allowed = true;
10167                                            break;
10168                                        }
10169                                    }
10170                                }
10171                            }
10172                        }
10173                    }
10174                } else {
10175                    allowed = isPrivilegedApp(pkg);
10176                }
10177            }
10178        }
10179        if (!allowed) {
10180            if (!allowed && (bp.protectionLevel
10181                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10182                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10183                // If this was a previously normal/dangerous permission that got moved
10184                // to a system permission as part of the runtime permission redesign, then
10185                // we still want to blindly grant it to old apps.
10186                allowed = true;
10187            }
10188            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10189                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10190                // If this permission is to be granted to the system installer and
10191                // this app is an installer, then it gets the permission.
10192                allowed = true;
10193            }
10194            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10195                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10196                // If this permission is to be granted to the system verifier and
10197                // this app is a verifier, then it gets the permission.
10198                allowed = true;
10199            }
10200            if (!allowed && (bp.protectionLevel
10201                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10202                    && isSystemApp(pkg)) {
10203                // Any pre-installed system app is allowed to get this permission.
10204                allowed = true;
10205            }
10206            if (!allowed && (bp.protectionLevel
10207                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10208                // For development permissions, a development permission
10209                // is granted only if it was already granted.
10210                allowed = origPermissions.hasInstallPermission(perm);
10211            }
10212            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10213                    && pkg.packageName.equals(mSetupWizardPackage)) {
10214                // If this permission is to be granted to the system setup wizard and
10215                // this app is a setup wizard, then it gets the permission.
10216                allowed = true;
10217            }
10218        }
10219        return allowed;
10220    }
10221
10222    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10223        final int permCount = pkg.requestedPermissions.size();
10224        for (int j = 0; j < permCount; j++) {
10225            String requestedPermission = pkg.requestedPermissions.get(j);
10226            if (permission.equals(requestedPermission)) {
10227                return true;
10228            }
10229        }
10230        return false;
10231    }
10232
10233    final class ActivityIntentResolver
10234            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10235        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10236                boolean defaultOnly, int userId) {
10237            if (!sUserManager.exists(userId)) return null;
10238            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10239            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10240        }
10241
10242        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10243                int userId) {
10244            if (!sUserManager.exists(userId)) return null;
10245            mFlags = flags;
10246            return super.queryIntent(intent, resolvedType,
10247                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10248        }
10249
10250        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10251                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10252            if (!sUserManager.exists(userId)) return null;
10253            if (packageActivities == null) {
10254                return null;
10255            }
10256            mFlags = flags;
10257            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10258            final int N = packageActivities.size();
10259            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10260                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10261
10262            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10263            for (int i = 0; i < N; ++i) {
10264                intentFilters = packageActivities.get(i).intents;
10265                if (intentFilters != null && intentFilters.size() > 0) {
10266                    PackageParser.ActivityIntentInfo[] array =
10267                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10268                    intentFilters.toArray(array);
10269                    listCut.add(array);
10270                }
10271            }
10272            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10273        }
10274
10275        /**
10276         * Finds a privileged activity that matches the specified activity names.
10277         */
10278        private PackageParser.Activity findMatchingActivity(
10279                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10280            for (PackageParser.Activity sysActivity : activityList) {
10281                if (sysActivity.info.name.equals(activityInfo.name)) {
10282                    return sysActivity;
10283                }
10284                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10285                    return sysActivity;
10286                }
10287                if (sysActivity.info.targetActivity != null) {
10288                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10289                        return sysActivity;
10290                    }
10291                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10292                        return sysActivity;
10293                    }
10294                }
10295            }
10296            return null;
10297        }
10298
10299        public class IterGenerator<E> {
10300            public Iterator<E> generate(ActivityIntentInfo info) {
10301                return null;
10302            }
10303        }
10304
10305        public class ActionIterGenerator extends IterGenerator<String> {
10306            @Override
10307            public Iterator<String> generate(ActivityIntentInfo info) {
10308                return info.actionsIterator();
10309            }
10310        }
10311
10312        public class CategoriesIterGenerator extends IterGenerator<String> {
10313            @Override
10314            public Iterator<String> generate(ActivityIntentInfo info) {
10315                return info.categoriesIterator();
10316            }
10317        }
10318
10319        public class SchemesIterGenerator extends IterGenerator<String> {
10320            @Override
10321            public Iterator<String> generate(ActivityIntentInfo info) {
10322                return info.schemesIterator();
10323            }
10324        }
10325
10326        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10327            @Override
10328            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10329                return info.authoritiesIterator();
10330            }
10331        }
10332
10333        /**
10334         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10335         * MODIFIED. Do not pass in a list that should not be changed.
10336         */
10337        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10338                IterGenerator<T> generator, Iterator<T> searchIterator) {
10339            // loop through the set of actions; every one must be found in the intent filter
10340            while (searchIterator.hasNext()) {
10341                // we must have at least one filter in the list to consider a match
10342                if (intentList.size() == 0) {
10343                    break;
10344                }
10345
10346                final T searchAction = searchIterator.next();
10347
10348                // loop through the set of intent filters
10349                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10350                while (intentIter.hasNext()) {
10351                    final ActivityIntentInfo intentInfo = intentIter.next();
10352                    boolean selectionFound = false;
10353
10354                    // loop through the intent filter's selection criteria; at least one
10355                    // of them must match the searched criteria
10356                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10357                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10358                        final T intentSelection = intentSelectionIter.next();
10359                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10360                            selectionFound = true;
10361                            break;
10362                        }
10363                    }
10364
10365                    // the selection criteria wasn't found in this filter's set; this filter
10366                    // is not a potential match
10367                    if (!selectionFound) {
10368                        intentIter.remove();
10369                    }
10370                }
10371            }
10372        }
10373
10374        private boolean isProtectedAction(ActivityIntentInfo filter) {
10375            final Iterator<String> actionsIter = filter.actionsIterator();
10376            while (actionsIter != null && actionsIter.hasNext()) {
10377                final String filterAction = actionsIter.next();
10378                if (PROTECTED_ACTIONS.contains(filterAction)) {
10379                    return true;
10380                }
10381            }
10382            return false;
10383        }
10384
10385        /**
10386         * Adjusts the priority of the given intent filter according to policy.
10387         * <p>
10388         * <ul>
10389         * <li>The priority for non privileged applications is capped to '0'</li>
10390         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10391         * <li>The priority for unbundled updates to privileged applications is capped to the
10392         *      priority defined on the system partition</li>
10393         * </ul>
10394         * <p>
10395         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10396         * allowed to obtain any priority on any action.
10397         */
10398        private void adjustPriority(
10399                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10400            // nothing to do; priority is fine as-is
10401            if (intent.getPriority() <= 0) {
10402                return;
10403            }
10404
10405            final ActivityInfo activityInfo = intent.activity.info;
10406            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10407
10408            final boolean privilegedApp =
10409                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10410            if (!privilegedApp) {
10411                // non-privileged applications can never define a priority >0
10412                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10413                        + " package: " + applicationInfo.packageName
10414                        + " activity: " + intent.activity.className
10415                        + " origPrio: " + intent.getPriority());
10416                intent.setPriority(0);
10417                return;
10418            }
10419
10420            if (systemActivities == null) {
10421                // the system package is not disabled; we're parsing the system partition
10422                if (isProtectedAction(intent)) {
10423                    if (mDeferProtectedFilters) {
10424                        // We can't deal with these just yet. No component should ever obtain a
10425                        // >0 priority for a protected actions, with ONE exception -- the setup
10426                        // wizard. The setup wizard, however, cannot be known until we're able to
10427                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10428                        // until all intent filters have been processed. Chicken, meet egg.
10429                        // Let the filter temporarily have a high priority and rectify the
10430                        // priorities after all system packages have been scanned.
10431                        mProtectedFilters.add(intent);
10432                        if (DEBUG_FILTERS) {
10433                            Slog.i(TAG, "Protected action; save for later;"
10434                                    + " package: " + applicationInfo.packageName
10435                                    + " activity: " + intent.activity.className
10436                                    + " origPrio: " + intent.getPriority());
10437                        }
10438                        return;
10439                    } else {
10440                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10441                            Slog.i(TAG, "No setup wizard;"
10442                                + " All protected intents capped to priority 0");
10443                        }
10444                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10445                            if (DEBUG_FILTERS) {
10446                                Slog.i(TAG, "Found setup wizard;"
10447                                    + " allow priority " + intent.getPriority() + ";"
10448                                    + " package: " + intent.activity.info.packageName
10449                                    + " activity: " + intent.activity.className
10450                                    + " priority: " + intent.getPriority());
10451                            }
10452                            // setup wizard gets whatever it wants
10453                            return;
10454                        }
10455                        Slog.w(TAG, "Protected action; cap priority to 0;"
10456                                + " package: " + intent.activity.info.packageName
10457                                + " activity: " + intent.activity.className
10458                                + " origPrio: " + intent.getPriority());
10459                        intent.setPriority(0);
10460                        return;
10461                    }
10462                }
10463                // privileged apps on the system image get whatever priority they request
10464                return;
10465            }
10466
10467            // privileged app unbundled update ... try to find the same activity
10468            final PackageParser.Activity foundActivity =
10469                    findMatchingActivity(systemActivities, activityInfo);
10470            if (foundActivity == null) {
10471                // this is a new activity; it cannot obtain >0 priority
10472                if (DEBUG_FILTERS) {
10473                    Slog.i(TAG, "New activity; cap priority to 0;"
10474                            + " package: " + applicationInfo.packageName
10475                            + " activity: " + intent.activity.className
10476                            + " origPrio: " + intent.getPriority());
10477                }
10478                intent.setPriority(0);
10479                return;
10480            }
10481
10482            // found activity, now check for filter equivalence
10483
10484            // a shallow copy is enough; we modify the list, not its contents
10485            final List<ActivityIntentInfo> intentListCopy =
10486                    new ArrayList<>(foundActivity.intents);
10487            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10488
10489            // find matching action subsets
10490            final Iterator<String> actionsIterator = intent.actionsIterator();
10491            if (actionsIterator != null) {
10492                getIntentListSubset(
10493                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10494                if (intentListCopy.size() == 0) {
10495                    // no more intents to match; we're not equivalent
10496                    if (DEBUG_FILTERS) {
10497                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10498                                + " package: " + applicationInfo.packageName
10499                                + " activity: " + intent.activity.className
10500                                + " origPrio: " + intent.getPriority());
10501                    }
10502                    intent.setPriority(0);
10503                    return;
10504                }
10505            }
10506
10507            // find matching category subsets
10508            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10509            if (categoriesIterator != null) {
10510                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10511                        categoriesIterator);
10512                if (intentListCopy.size() == 0) {
10513                    // no more intents to match; we're not equivalent
10514                    if (DEBUG_FILTERS) {
10515                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10516                                + " package: " + applicationInfo.packageName
10517                                + " activity: " + intent.activity.className
10518                                + " origPrio: " + intent.getPriority());
10519                    }
10520                    intent.setPriority(0);
10521                    return;
10522                }
10523            }
10524
10525            // find matching schemes subsets
10526            final Iterator<String> schemesIterator = intent.schemesIterator();
10527            if (schemesIterator != null) {
10528                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10529                        schemesIterator);
10530                if (intentListCopy.size() == 0) {
10531                    // no more intents to match; we're not equivalent
10532                    if (DEBUG_FILTERS) {
10533                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10534                                + " package: " + applicationInfo.packageName
10535                                + " activity: " + intent.activity.className
10536                                + " origPrio: " + intent.getPriority());
10537                    }
10538                    intent.setPriority(0);
10539                    return;
10540                }
10541            }
10542
10543            // find matching authorities subsets
10544            final Iterator<IntentFilter.AuthorityEntry>
10545                    authoritiesIterator = intent.authoritiesIterator();
10546            if (authoritiesIterator != null) {
10547                getIntentListSubset(intentListCopy,
10548                        new AuthoritiesIterGenerator(),
10549                        authoritiesIterator);
10550                if (intentListCopy.size() == 0) {
10551                    // no more intents to match; we're not equivalent
10552                    if (DEBUG_FILTERS) {
10553                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10554                                + " package: " + applicationInfo.packageName
10555                                + " activity: " + intent.activity.className
10556                                + " origPrio: " + intent.getPriority());
10557                    }
10558                    intent.setPriority(0);
10559                    return;
10560                }
10561            }
10562
10563            // we found matching filter(s); app gets the max priority of all intents
10564            int cappedPriority = 0;
10565            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10566                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10567            }
10568            if (intent.getPriority() > cappedPriority) {
10569                if (DEBUG_FILTERS) {
10570                    Slog.i(TAG, "Found matching filter(s);"
10571                            + " cap priority to " + cappedPriority + ";"
10572                            + " package: " + applicationInfo.packageName
10573                            + " activity: " + intent.activity.className
10574                            + " origPrio: " + intent.getPriority());
10575                }
10576                intent.setPriority(cappedPriority);
10577                return;
10578            }
10579            // all this for nothing; the requested priority was <= what was on the system
10580        }
10581
10582        public final void addActivity(PackageParser.Activity a, String type) {
10583            mActivities.put(a.getComponentName(), a);
10584            if (DEBUG_SHOW_INFO)
10585                Log.v(
10586                TAG, "  " + type + " " +
10587                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10588            if (DEBUG_SHOW_INFO)
10589                Log.v(TAG, "    Class=" + a.info.name);
10590            final int NI = a.intents.size();
10591            for (int j=0; j<NI; j++) {
10592                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10593                if ("activity".equals(type)) {
10594                    final PackageSetting ps =
10595                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10596                    final List<PackageParser.Activity> systemActivities =
10597                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10598                    adjustPriority(systemActivities, intent);
10599                }
10600                if (DEBUG_SHOW_INFO) {
10601                    Log.v(TAG, "    IntentFilter:");
10602                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10603                }
10604                if (!intent.debugCheck()) {
10605                    Log.w(TAG, "==> For Activity " + a.info.name);
10606                }
10607                addFilter(intent);
10608            }
10609        }
10610
10611        public final void removeActivity(PackageParser.Activity a, String type) {
10612            mActivities.remove(a.getComponentName());
10613            if (DEBUG_SHOW_INFO) {
10614                Log.v(TAG, "  " + type + " "
10615                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10616                                : a.info.name) + ":");
10617                Log.v(TAG, "    Class=" + a.info.name);
10618            }
10619            final int NI = a.intents.size();
10620            for (int j=0; j<NI; j++) {
10621                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10622                if (DEBUG_SHOW_INFO) {
10623                    Log.v(TAG, "    IntentFilter:");
10624                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10625                }
10626                removeFilter(intent);
10627            }
10628        }
10629
10630        @Override
10631        protected boolean allowFilterResult(
10632                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10633            ActivityInfo filterAi = filter.activity.info;
10634            for (int i=dest.size()-1; i>=0; i--) {
10635                ActivityInfo destAi = dest.get(i).activityInfo;
10636                if (destAi.name == filterAi.name
10637                        && destAi.packageName == filterAi.packageName) {
10638                    return false;
10639                }
10640            }
10641            return true;
10642        }
10643
10644        @Override
10645        protected ActivityIntentInfo[] newArray(int size) {
10646            return new ActivityIntentInfo[size];
10647        }
10648
10649        @Override
10650        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10651            if (!sUserManager.exists(userId)) return true;
10652            PackageParser.Package p = filter.activity.owner;
10653            if (p != null) {
10654                PackageSetting ps = (PackageSetting)p.mExtras;
10655                if (ps != null) {
10656                    // System apps are never considered stopped for purposes of
10657                    // filtering, because there may be no way for the user to
10658                    // actually re-launch them.
10659                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10660                            && ps.getStopped(userId);
10661                }
10662            }
10663            return false;
10664        }
10665
10666        @Override
10667        protected boolean isPackageForFilter(String packageName,
10668                PackageParser.ActivityIntentInfo info) {
10669            return packageName.equals(info.activity.owner.packageName);
10670        }
10671
10672        @Override
10673        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10674                int match, int userId) {
10675            if (!sUserManager.exists(userId)) return null;
10676            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10677                return null;
10678            }
10679            final PackageParser.Activity activity = info.activity;
10680            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10681            if (ps == null) {
10682                return null;
10683            }
10684            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10685                    ps.readUserState(userId), userId);
10686            if (ai == null) {
10687                return null;
10688            }
10689            final ResolveInfo res = new ResolveInfo();
10690            res.activityInfo = ai;
10691            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10692                res.filter = info;
10693            }
10694            if (info != null) {
10695                res.handleAllWebDataURI = info.handleAllWebDataURI();
10696            }
10697            res.priority = info.getPriority();
10698            res.preferredOrder = activity.owner.mPreferredOrder;
10699            //System.out.println("Result: " + res.activityInfo.className +
10700            //                   " = " + res.priority);
10701            res.match = match;
10702            res.isDefault = info.hasDefault;
10703            res.labelRes = info.labelRes;
10704            res.nonLocalizedLabel = info.nonLocalizedLabel;
10705            if (userNeedsBadging(userId)) {
10706                res.noResourceId = true;
10707            } else {
10708                res.icon = info.icon;
10709            }
10710            res.iconResourceId = info.icon;
10711            res.system = res.activityInfo.applicationInfo.isSystemApp();
10712            return res;
10713        }
10714
10715        @Override
10716        protected void sortResults(List<ResolveInfo> results) {
10717            Collections.sort(results, mResolvePrioritySorter);
10718        }
10719
10720        @Override
10721        protected void dumpFilter(PrintWriter out, String prefix,
10722                PackageParser.ActivityIntentInfo filter) {
10723            out.print(prefix); out.print(
10724                    Integer.toHexString(System.identityHashCode(filter.activity)));
10725                    out.print(' ');
10726                    filter.activity.printComponentShortName(out);
10727                    out.print(" filter ");
10728                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10729        }
10730
10731        @Override
10732        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10733            return filter.activity;
10734        }
10735
10736        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10737            PackageParser.Activity activity = (PackageParser.Activity)label;
10738            out.print(prefix); out.print(
10739                    Integer.toHexString(System.identityHashCode(activity)));
10740                    out.print(' ');
10741                    activity.printComponentShortName(out);
10742            if (count > 1) {
10743                out.print(" ("); out.print(count); out.print(" filters)");
10744            }
10745            out.println();
10746        }
10747
10748        // Keys are String (activity class name), values are Activity.
10749        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10750                = new ArrayMap<ComponentName, PackageParser.Activity>();
10751        private int mFlags;
10752    }
10753
10754    private final class ServiceIntentResolver
10755            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10756        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10757                boolean defaultOnly, int userId) {
10758            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10759            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10760        }
10761
10762        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10763                int userId) {
10764            if (!sUserManager.exists(userId)) return null;
10765            mFlags = flags;
10766            return super.queryIntent(intent, resolvedType,
10767                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10768        }
10769
10770        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10771                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10772            if (!sUserManager.exists(userId)) return null;
10773            if (packageServices == null) {
10774                return null;
10775            }
10776            mFlags = flags;
10777            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10778            final int N = packageServices.size();
10779            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10780                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10781
10782            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10783            for (int i = 0; i < N; ++i) {
10784                intentFilters = packageServices.get(i).intents;
10785                if (intentFilters != null && intentFilters.size() > 0) {
10786                    PackageParser.ServiceIntentInfo[] array =
10787                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10788                    intentFilters.toArray(array);
10789                    listCut.add(array);
10790                }
10791            }
10792            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10793        }
10794
10795        public final void addService(PackageParser.Service s) {
10796            mServices.put(s.getComponentName(), s);
10797            if (DEBUG_SHOW_INFO) {
10798                Log.v(TAG, "  "
10799                        + (s.info.nonLocalizedLabel != null
10800                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10801                Log.v(TAG, "    Class=" + s.info.name);
10802            }
10803            final int NI = s.intents.size();
10804            int j;
10805            for (j=0; j<NI; j++) {
10806                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10807                if (DEBUG_SHOW_INFO) {
10808                    Log.v(TAG, "    IntentFilter:");
10809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10810                }
10811                if (!intent.debugCheck()) {
10812                    Log.w(TAG, "==> For Service " + s.info.name);
10813                }
10814                addFilter(intent);
10815            }
10816        }
10817
10818        public final void removeService(PackageParser.Service s) {
10819            mServices.remove(s.getComponentName());
10820            if (DEBUG_SHOW_INFO) {
10821                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10822                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10823                Log.v(TAG, "    Class=" + s.info.name);
10824            }
10825            final int NI = s.intents.size();
10826            int j;
10827            for (j=0; j<NI; j++) {
10828                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10829                if (DEBUG_SHOW_INFO) {
10830                    Log.v(TAG, "    IntentFilter:");
10831                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10832                }
10833                removeFilter(intent);
10834            }
10835        }
10836
10837        @Override
10838        protected boolean allowFilterResult(
10839                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10840            ServiceInfo filterSi = filter.service.info;
10841            for (int i=dest.size()-1; i>=0; i--) {
10842                ServiceInfo destAi = dest.get(i).serviceInfo;
10843                if (destAi.name == filterSi.name
10844                        && destAi.packageName == filterSi.packageName) {
10845                    return false;
10846                }
10847            }
10848            return true;
10849        }
10850
10851        @Override
10852        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10853            return new PackageParser.ServiceIntentInfo[size];
10854        }
10855
10856        @Override
10857        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10858            if (!sUserManager.exists(userId)) return true;
10859            PackageParser.Package p = filter.service.owner;
10860            if (p != null) {
10861                PackageSetting ps = (PackageSetting)p.mExtras;
10862                if (ps != null) {
10863                    // System apps are never considered stopped for purposes of
10864                    // filtering, because there may be no way for the user to
10865                    // actually re-launch them.
10866                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10867                            && ps.getStopped(userId);
10868                }
10869            }
10870            return false;
10871        }
10872
10873        @Override
10874        protected boolean isPackageForFilter(String packageName,
10875                PackageParser.ServiceIntentInfo info) {
10876            return packageName.equals(info.service.owner.packageName);
10877        }
10878
10879        @Override
10880        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10881                int match, int userId) {
10882            if (!sUserManager.exists(userId)) return null;
10883            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10884            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10885                return null;
10886            }
10887            final PackageParser.Service service = info.service;
10888            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10889            if (ps == null) {
10890                return null;
10891            }
10892            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10893                    ps.readUserState(userId), userId);
10894            if (si == null) {
10895                return null;
10896            }
10897            final ResolveInfo res = new ResolveInfo();
10898            res.serviceInfo = si;
10899            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10900                res.filter = filter;
10901            }
10902            res.priority = info.getPriority();
10903            res.preferredOrder = service.owner.mPreferredOrder;
10904            res.match = match;
10905            res.isDefault = info.hasDefault;
10906            res.labelRes = info.labelRes;
10907            res.nonLocalizedLabel = info.nonLocalizedLabel;
10908            res.icon = info.icon;
10909            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10910            return res;
10911        }
10912
10913        @Override
10914        protected void sortResults(List<ResolveInfo> results) {
10915            Collections.sort(results, mResolvePrioritySorter);
10916        }
10917
10918        @Override
10919        protected void dumpFilter(PrintWriter out, String prefix,
10920                PackageParser.ServiceIntentInfo filter) {
10921            out.print(prefix); out.print(
10922                    Integer.toHexString(System.identityHashCode(filter.service)));
10923                    out.print(' ');
10924                    filter.service.printComponentShortName(out);
10925                    out.print(" filter ");
10926                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10927        }
10928
10929        @Override
10930        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10931            return filter.service;
10932        }
10933
10934        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10935            PackageParser.Service service = (PackageParser.Service)label;
10936            out.print(prefix); out.print(
10937                    Integer.toHexString(System.identityHashCode(service)));
10938                    out.print(' ');
10939                    service.printComponentShortName(out);
10940            if (count > 1) {
10941                out.print(" ("); out.print(count); out.print(" filters)");
10942            }
10943            out.println();
10944        }
10945
10946//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10947//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10948//            final List<ResolveInfo> retList = Lists.newArrayList();
10949//            while (i.hasNext()) {
10950//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10951//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10952//                    retList.add(resolveInfo);
10953//                }
10954//            }
10955//            return retList;
10956//        }
10957
10958        // Keys are String (activity class name), values are Activity.
10959        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10960                = new ArrayMap<ComponentName, PackageParser.Service>();
10961        private int mFlags;
10962    };
10963
10964    private final class ProviderIntentResolver
10965            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10966        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10967                boolean defaultOnly, int userId) {
10968            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10969            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10970        }
10971
10972        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10973                int userId) {
10974            if (!sUserManager.exists(userId))
10975                return null;
10976            mFlags = flags;
10977            return super.queryIntent(intent, resolvedType,
10978                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10979        }
10980
10981        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10982                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10983            if (!sUserManager.exists(userId))
10984                return null;
10985            if (packageProviders == null) {
10986                return null;
10987            }
10988            mFlags = flags;
10989            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10990            final int N = packageProviders.size();
10991            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10992                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10993
10994            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10995            for (int i = 0; i < N; ++i) {
10996                intentFilters = packageProviders.get(i).intents;
10997                if (intentFilters != null && intentFilters.size() > 0) {
10998                    PackageParser.ProviderIntentInfo[] array =
10999                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11000                    intentFilters.toArray(array);
11001                    listCut.add(array);
11002                }
11003            }
11004            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11005        }
11006
11007        public final void addProvider(PackageParser.Provider p) {
11008            if (mProviders.containsKey(p.getComponentName())) {
11009                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11010                return;
11011            }
11012
11013            mProviders.put(p.getComponentName(), p);
11014            if (DEBUG_SHOW_INFO) {
11015                Log.v(TAG, "  "
11016                        + (p.info.nonLocalizedLabel != null
11017                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11018                Log.v(TAG, "    Class=" + p.info.name);
11019            }
11020            final int NI = p.intents.size();
11021            int j;
11022            for (j = 0; j < NI; j++) {
11023                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11024                if (DEBUG_SHOW_INFO) {
11025                    Log.v(TAG, "    IntentFilter:");
11026                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11027                }
11028                if (!intent.debugCheck()) {
11029                    Log.w(TAG, "==> For Provider " + p.info.name);
11030                }
11031                addFilter(intent);
11032            }
11033        }
11034
11035        public final void removeProvider(PackageParser.Provider p) {
11036            mProviders.remove(p.getComponentName());
11037            if (DEBUG_SHOW_INFO) {
11038                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11039                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11040                Log.v(TAG, "    Class=" + p.info.name);
11041            }
11042            final int NI = p.intents.size();
11043            int j;
11044            for (j = 0; j < NI; j++) {
11045                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11046                if (DEBUG_SHOW_INFO) {
11047                    Log.v(TAG, "    IntentFilter:");
11048                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11049                }
11050                removeFilter(intent);
11051            }
11052        }
11053
11054        @Override
11055        protected boolean allowFilterResult(
11056                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11057            ProviderInfo filterPi = filter.provider.info;
11058            for (int i = dest.size() - 1; i >= 0; i--) {
11059                ProviderInfo destPi = dest.get(i).providerInfo;
11060                if (destPi.name == filterPi.name
11061                        && destPi.packageName == filterPi.packageName) {
11062                    return false;
11063                }
11064            }
11065            return true;
11066        }
11067
11068        @Override
11069        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11070            return new PackageParser.ProviderIntentInfo[size];
11071        }
11072
11073        @Override
11074        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11075            if (!sUserManager.exists(userId))
11076                return true;
11077            PackageParser.Package p = filter.provider.owner;
11078            if (p != null) {
11079                PackageSetting ps = (PackageSetting) p.mExtras;
11080                if (ps != null) {
11081                    // System apps are never considered stopped for purposes of
11082                    // filtering, because there may be no way for the user to
11083                    // actually re-launch them.
11084                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11085                            && ps.getStopped(userId);
11086                }
11087            }
11088            return false;
11089        }
11090
11091        @Override
11092        protected boolean isPackageForFilter(String packageName,
11093                PackageParser.ProviderIntentInfo info) {
11094            return packageName.equals(info.provider.owner.packageName);
11095        }
11096
11097        @Override
11098        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11099                int match, int userId) {
11100            if (!sUserManager.exists(userId))
11101                return null;
11102            final PackageParser.ProviderIntentInfo info = filter;
11103            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11104                return null;
11105            }
11106            final PackageParser.Provider provider = info.provider;
11107            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11108            if (ps == null) {
11109                return null;
11110            }
11111            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11112                    ps.readUserState(userId), userId);
11113            if (pi == null) {
11114                return null;
11115            }
11116            final ResolveInfo res = new ResolveInfo();
11117            res.providerInfo = pi;
11118            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11119                res.filter = filter;
11120            }
11121            res.priority = info.getPriority();
11122            res.preferredOrder = provider.owner.mPreferredOrder;
11123            res.match = match;
11124            res.isDefault = info.hasDefault;
11125            res.labelRes = info.labelRes;
11126            res.nonLocalizedLabel = info.nonLocalizedLabel;
11127            res.icon = info.icon;
11128            res.system = res.providerInfo.applicationInfo.isSystemApp();
11129            return res;
11130        }
11131
11132        @Override
11133        protected void sortResults(List<ResolveInfo> results) {
11134            Collections.sort(results, mResolvePrioritySorter);
11135        }
11136
11137        @Override
11138        protected void dumpFilter(PrintWriter out, String prefix,
11139                PackageParser.ProviderIntentInfo filter) {
11140            out.print(prefix);
11141            out.print(
11142                    Integer.toHexString(System.identityHashCode(filter.provider)));
11143            out.print(' ');
11144            filter.provider.printComponentShortName(out);
11145            out.print(" filter ");
11146            out.println(Integer.toHexString(System.identityHashCode(filter)));
11147        }
11148
11149        @Override
11150        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11151            return filter.provider;
11152        }
11153
11154        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11155            PackageParser.Provider provider = (PackageParser.Provider)label;
11156            out.print(prefix); out.print(
11157                    Integer.toHexString(System.identityHashCode(provider)));
11158                    out.print(' ');
11159                    provider.printComponentShortName(out);
11160            if (count > 1) {
11161                out.print(" ("); out.print(count); out.print(" filters)");
11162            }
11163            out.println();
11164        }
11165
11166        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11167                = new ArrayMap<ComponentName, PackageParser.Provider>();
11168        private int mFlags;
11169    }
11170
11171    private static final class EphemeralIntentResolver
11172            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11173        @Override
11174        protected EphemeralResolveIntentInfo[] newArray(int size) {
11175            return new EphemeralResolveIntentInfo[size];
11176        }
11177
11178        @Override
11179        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11180            return true;
11181        }
11182
11183        @Override
11184        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11185                int userId) {
11186            if (!sUserManager.exists(userId)) {
11187                return null;
11188            }
11189            return info.getEphemeralResolveInfo();
11190        }
11191    }
11192
11193    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11194            new Comparator<ResolveInfo>() {
11195        public int compare(ResolveInfo r1, ResolveInfo r2) {
11196            int v1 = r1.priority;
11197            int v2 = r2.priority;
11198            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11199            if (v1 != v2) {
11200                return (v1 > v2) ? -1 : 1;
11201            }
11202            v1 = r1.preferredOrder;
11203            v2 = r2.preferredOrder;
11204            if (v1 != v2) {
11205                return (v1 > v2) ? -1 : 1;
11206            }
11207            if (r1.isDefault != r2.isDefault) {
11208                return r1.isDefault ? -1 : 1;
11209            }
11210            v1 = r1.match;
11211            v2 = r2.match;
11212            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11213            if (v1 != v2) {
11214                return (v1 > v2) ? -1 : 1;
11215            }
11216            if (r1.system != r2.system) {
11217                return r1.system ? -1 : 1;
11218            }
11219            if (r1.activityInfo != null) {
11220                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11221            }
11222            if (r1.serviceInfo != null) {
11223                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11224            }
11225            if (r1.providerInfo != null) {
11226                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11227            }
11228            return 0;
11229        }
11230    };
11231
11232    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11233            new Comparator<ProviderInfo>() {
11234        public int compare(ProviderInfo p1, ProviderInfo p2) {
11235            final int v1 = p1.initOrder;
11236            final int v2 = p2.initOrder;
11237            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11238        }
11239    };
11240
11241    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11242            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11243            final int[] userIds) {
11244        mHandler.post(new Runnable() {
11245            @Override
11246            public void run() {
11247                try {
11248                    final IActivityManager am = ActivityManagerNative.getDefault();
11249                    if (am == null) return;
11250                    final int[] resolvedUserIds;
11251                    if (userIds == null) {
11252                        resolvedUserIds = am.getRunningUserIds();
11253                    } else {
11254                        resolvedUserIds = userIds;
11255                    }
11256                    for (int id : resolvedUserIds) {
11257                        final Intent intent = new Intent(action,
11258                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11259                        if (extras != null) {
11260                            intent.putExtras(extras);
11261                        }
11262                        if (targetPkg != null) {
11263                            intent.setPackage(targetPkg);
11264                        }
11265                        // Modify the UID when posting to other users
11266                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11267                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11268                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11269                            intent.putExtra(Intent.EXTRA_UID, uid);
11270                        }
11271                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11272                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11273                        if (DEBUG_BROADCASTS) {
11274                            RuntimeException here = new RuntimeException("here");
11275                            here.fillInStackTrace();
11276                            Slog.d(TAG, "Sending to user " + id + ": "
11277                                    + intent.toShortString(false, true, false, false)
11278                                    + " " + intent.getExtras(), here);
11279                        }
11280                        am.broadcastIntent(null, intent, null, finishedReceiver,
11281                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11282                                null, finishedReceiver != null, false, id);
11283                    }
11284                } catch (RemoteException ex) {
11285                }
11286            }
11287        });
11288    }
11289
11290    /**
11291     * Check if the external storage media is available. This is true if there
11292     * is a mounted external storage medium or if the external storage is
11293     * emulated.
11294     */
11295    private boolean isExternalMediaAvailable() {
11296        return mMediaMounted || Environment.isExternalStorageEmulated();
11297    }
11298
11299    @Override
11300    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11301        // writer
11302        synchronized (mPackages) {
11303            if (!isExternalMediaAvailable()) {
11304                // If the external storage is no longer mounted at this point,
11305                // the caller may not have been able to delete all of this
11306                // packages files and can not delete any more.  Bail.
11307                return null;
11308            }
11309            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11310            if (lastPackage != null) {
11311                pkgs.remove(lastPackage);
11312            }
11313            if (pkgs.size() > 0) {
11314                return pkgs.get(0);
11315            }
11316        }
11317        return null;
11318    }
11319
11320    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11321        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11322                userId, andCode ? 1 : 0, packageName);
11323        if (mSystemReady) {
11324            msg.sendToTarget();
11325        } else {
11326            if (mPostSystemReadyMessages == null) {
11327                mPostSystemReadyMessages = new ArrayList<>();
11328            }
11329            mPostSystemReadyMessages.add(msg);
11330        }
11331    }
11332
11333    void startCleaningPackages() {
11334        // reader
11335        if (!isExternalMediaAvailable()) {
11336            return;
11337        }
11338        synchronized (mPackages) {
11339            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11340                return;
11341            }
11342        }
11343        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11344        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11345        IActivityManager am = ActivityManagerNative.getDefault();
11346        if (am != null) {
11347            try {
11348                am.startService(null, intent, null, mContext.getOpPackageName(),
11349                        UserHandle.USER_SYSTEM);
11350            } catch (RemoteException e) {
11351            }
11352        }
11353    }
11354
11355    @Override
11356    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11357            int installFlags, String installerPackageName, int userId) {
11358        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11359
11360        final int callingUid = Binder.getCallingUid();
11361        enforceCrossUserPermission(callingUid, userId,
11362                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11363
11364        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11365            try {
11366                if (observer != null) {
11367                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11368                }
11369            } catch (RemoteException re) {
11370            }
11371            return;
11372        }
11373
11374        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11375            installFlags |= PackageManager.INSTALL_FROM_ADB;
11376
11377        } else {
11378            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11379            // about installerPackageName.
11380
11381            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11382            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11383        }
11384
11385        UserHandle user;
11386        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11387            user = UserHandle.ALL;
11388        } else {
11389            user = new UserHandle(userId);
11390        }
11391
11392        // Only system components can circumvent runtime permissions when installing.
11393        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11394                && mContext.checkCallingOrSelfPermission(Manifest.permission
11395                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11396            throw new SecurityException("You need the "
11397                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11398                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11399        }
11400
11401        final File originFile = new File(originPath);
11402        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11403
11404        final Message msg = mHandler.obtainMessage(INIT_COPY);
11405        final VerificationInfo verificationInfo = new VerificationInfo(
11406                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11407        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11408                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11409                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11410                null /*certificates*/);
11411        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11412        msg.obj = params;
11413
11414        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11415                System.identityHashCode(msg.obj));
11416        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11417                System.identityHashCode(msg.obj));
11418
11419        mHandler.sendMessage(msg);
11420    }
11421
11422    void installStage(String packageName, File stagedDir, String stagedCid,
11423            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11424            String installerPackageName, int installerUid, UserHandle user,
11425            Certificate[][] certificates) {
11426        if (DEBUG_EPHEMERAL) {
11427            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11428                Slog.d(TAG, "Ephemeral install of " + packageName);
11429            }
11430        }
11431        final VerificationInfo verificationInfo = new VerificationInfo(
11432                sessionParams.originatingUri, sessionParams.referrerUri,
11433                sessionParams.originatingUid, installerUid);
11434
11435        final OriginInfo origin;
11436        if (stagedDir != null) {
11437            origin = OriginInfo.fromStagedFile(stagedDir);
11438        } else {
11439            origin = OriginInfo.fromStagedContainer(stagedCid);
11440        }
11441
11442        final Message msg = mHandler.obtainMessage(INIT_COPY);
11443        final InstallParams params = new InstallParams(origin, null, observer,
11444                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11445                verificationInfo, user, sessionParams.abiOverride,
11446                sessionParams.grantedRuntimePermissions, certificates);
11447        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11448        msg.obj = params;
11449
11450        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11451                System.identityHashCode(msg.obj));
11452        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11453                System.identityHashCode(msg.obj));
11454
11455        mHandler.sendMessage(msg);
11456    }
11457
11458    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11459            int userId) {
11460        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11461        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11462    }
11463
11464    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11465            int appId, int userId) {
11466        Bundle extras = new Bundle(1);
11467        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11468
11469        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11470                packageName, extras, 0, null, null, new int[] {userId});
11471        try {
11472            IActivityManager am = ActivityManagerNative.getDefault();
11473            if (isSystem && am.isUserRunning(userId, 0)) {
11474                // The just-installed/enabled app is bundled on the system, so presumed
11475                // to be able to run automatically without needing an explicit launch.
11476                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11477                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11478                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11479                        .setPackage(packageName);
11480                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11481                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11482            }
11483        } catch (RemoteException e) {
11484            // shouldn't happen
11485            Slog.w(TAG, "Unable to bootstrap installed package", e);
11486        }
11487    }
11488
11489    @Override
11490    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11491            int userId) {
11492        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11493        PackageSetting pkgSetting;
11494        final int uid = Binder.getCallingUid();
11495        enforceCrossUserPermission(uid, userId,
11496                true /* requireFullPermission */, true /* checkShell */,
11497                "setApplicationHiddenSetting for user " + userId);
11498
11499        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11500            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11501            return false;
11502        }
11503
11504        long callingId = Binder.clearCallingIdentity();
11505        try {
11506            boolean sendAdded = false;
11507            boolean sendRemoved = false;
11508            // writer
11509            synchronized (mPackages) {
11510                pkgSetting = mSettings.mPackages.get(packageName);
11511                if (pkgSetting == null) {
11512                    return false;
11513                }
11514                // Do not allow "android" is being disabled
11515                if ("android".equals(packageName)) {
11516                    Slog.w(TAG, "Cannot hide package: android");
11517                    return false;
11518                }
11519                // Only allow protected packages to hide themselves.
11520                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11521                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11522                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11523                    return false;
11524                }
11525
11526                if (pkgSetting.getHidden(userId) != hidden) {
11527                    pkgSetting.setHidden(hidden, userId);
11528                    mSettings.writePackageRestrictionsLPr(userId);
11529                    if (hidden) {
11530                        sendRemoved = true;
11531                    } else {
11532                        sendAdded = true;
11533                    }
11534                }
11535            }
11536            if (sendAdded) {
11537                sendPackageAddedForUser(packageName, pkgSetting, userId);
11538                return true;
11539            }
11540            if (sendRemoved) {
11541                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11542                        "hiding pkg");
11543                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11544                return true;
11545            }
11546        } finally {
11547            Binder.restoreCallingIdentity(callingId);
11548        }
11549        return false;
11550    }
11551
11552    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11553            int userId) {
11554        final PackageRemovedInfo info = new PackageRemovedInfo();
11555        info.removedPackage = packageName;
11556        info.removedUsers = new int[] {userId};
11557        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11558        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11559    }
11560
11561    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11562        if (pkgList.length > 0) {
11563            Bundle extras = new Bundle(1);
11564            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11565
11566            sendPackageBroadcast(
11567                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11568                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11569                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11570                    new int[] {userId});
11571        }
11572    }
11573
11574    /**
11575     * Returns true if application is not found or there was an error. Otherwise it returns
11576     * the hidden state of the package for the given user.
11577     */
11578    @Override
11579    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11580        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11581        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11582                true /* requireFullPermission */, false /* checkShell */,
11583                "getApplicationHidden for user " + userId);
11584        PackageSetting pkgSetting;
11585        long callingId = Binder.clearCallingIdentity();
11586        try {
11587            // writer
11588            synchronized (mPackages) {
11589                pkgSetting = mSettings.mPackages.get(packageName);
11590                if (pkgSetting == null) {
11591                    return true;
11592                }
11593                return pkgSetting.getHidden(userId);
11594            }
11595        } finally {
11596            Binder.restoreCallingIdentity(callingId);
11597        }
11598    }
11599
11600    /**
11601     * @hide
11602     */
11603    @Override
11604    public int installExistingPackageAsUser(String packageName, int userId) {
11605        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11606                null);
11607        PackageSetting pkgSetting;
11608        final int uid = Binder.getCallingUid();
11609        enforceCrossUserPermission(uid, userId,
11610                true /* requireFullPermission */, true /* checkShell */,
11611                "installExistingPackage for user " + userId);
11612        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11613            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11614        }
11615
11616        long callingId = Binder.clearCallingIdentity();
11617        try {
11618            boolean installed = false;
11619
11620            // writer
11621            synchronized (mPackages) {
11622                pkgSetting = mSettings.mPackages.get(packageName);
11623                if (pkgSetting == null) {
11624                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11625                }
11626                if (!pkgSetting.getInstalled(userId)) {
11627                    pkgSetting.setInstalled(true, userId);
11628                    pkgSetting.setHidden(false, userId);
11629                    mSettings.writePackageRestrictionsLPr(userId);
11630                    installed = true;
11631                }
11632            }
11633
11634            if (installed) {
11635                if (pkgSetting.pkg != null) {
11636                    synchronized (mInstallLock) {
11637                        // We don't need to freeze for a brand new install
11638                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11639                    }
11640                }
11641                sendPackageAddedForUser(packageName, pkgSetting, userId);
11642            }
11643        } finally {
11644            Binder.restoreCallingIdentity(callingId);
11645        }
11646
11647        return PackageManager.INSTALL_SUCCEEDED;
11648    }
11649
11650    boolean isUserRestricted(int userId, String restrictionKey) {
11651        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11652        if (restrictions.getBoolean(restrictionKey, false)) {
11653            Log.w(TAG, "User is restricted: " + restrictionKey);
11654            return true;
11655        }
11656        return false;
11657    }
11658
11659    @Override
11660    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11661            int userId) {
11662        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11663        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11664                true /* requireFullPermission */, true /* checkShell */,
11665                "setPackagesSuspended for user " + userId);
11666
11667        if (ArrayUtils.isEmpty(packageNames)) {
11668            return packageNames;
11669        }
11670
11671        // List of package names for whom the suspended state has changed.
11672        List<String> changedPackages = new ArrayList<>(packageNames.length);
11673        // List of package names for whom the suspended state is not set as requested in this
11674        // method.
11675        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11676        long callingId = Binder.clearCallingIdentity();
11677        try {
11678            for (int i = 0; i < packageNames.length; i++) {
11679                String packageName = packageNames[i];
11680                boolean changed = false;
11681                final int appId;
11682                synchronized (mPackages) {
11683                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11684                    if (pkgSetting == null) {
11685                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11686                                + "\". Skipping suspending/un-suspending.");
11687                        unactionedPackages.add(packageName);
11688                        continue;
11689                    }
11690                    appId = pkgSetting.appId;
11691                    if (pkgSetting.getSuspended(userId) != suspended) {
11692                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11693                            unactionedPackages.add(packageName);
11694                            continue;
11695                        }
11696                        pkgSetting.setSuspended(suspended, userId);
11697                        mSettings.writePackageRestrictionsLPr(userId);
11698                        changed = true;
11699                        changedPackages.add(packageName);
11700                    }
11701                }
11702
11703                if (changed && suspended) {
11704                    killApplication(packageName, UserHandle.getUid(userId, appId),
11705                            "suspending package");
11706                }
11707            }
11708        } finally {
11709            Binder.restoreCallingIdentity(callingId);
11710        }
11711
11712        if (!changedPackages.isEmpty()) {
11713            sendPackagesSuspendedForUser(changedPackages.toArray(
11714                    new String[changedPackages.size()]), userId, suspended);
11715        }
11716
11717        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11718    }
11719
11720    @Override
11721    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11722        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11723                true /* requireFullPermission */, false /* checkShell */,
11724                "isPackageSuspendedForUser for user " + userId);
11725        synchronized (mPackages) {
11726            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11727            if (pkgSetting == null) {
11728                throw new IllegalArgumentException("Unknown target package: " + packageName);
11729            }
11730            return pkgSetting.getSuspended(userId);
11731        }
11732    }
11733
11734    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11735        if (isPackageDeviceAdmin(packageName, userId)) {
11736            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11737                    + "\": has an active device admin");
11738            return false;
11739        }
11740
11741        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11742        if (packageName.equals(activeLauncherPackageName)) {
11743            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11744                    + "\": contains the active launcher");
11745            return false;
11746        }
11747
11748        if (packageName.equals(mRequiredInstallerPackage)) {
11749            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11750                    + "\": required for package installation");
11751            return false;
11752        }
11753
11754        if (packageName.equals(mRequiredVerifierPackage)) {
11755            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11756                    + "\": required for package verification");
11757            return false;
11758        }
11759
11760        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11761            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11762                    + "\": is the default dialer");
11763            return false;
11764        }
11765
11766        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11767            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11768                    + "\": protected package");
11769            return false;
11770        }
11771
11772        return true;
11773    }
11774
11775    private String getActiveLauncherPackageName(int userId) {
11776        Intent intent = new Intent(Intent.ACTION_MAIN);
11777        intent.addCategory(Intent.CATEGORY_HOME);
11778        ResolveInfo resolveInfo = resolveIntent(
11779                intent,
11780                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11781                PackageManager.MATCH_DEFAULT_ONLY,
11782                userId);
11783
11784        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11785    }
11786
11787    private String getDefaultDialerPackageName(int userId) {
11788        synchronized (mPackages) {
11789            return mSettings.getDefaultDialerPackageNameLPw(userId);
11790        }
11791    }
11792
11793    @Override
11794    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11795        mContext.enforceCallingOrSelfPermission(
11796                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11797                "Only package verification agents can verify applications");
11798
11799        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11800        final PackageVerificationResponse response = new PackageVerificationResponse(
11801                verificationCode, Binder.getCallingUid());
11802        msg.arg1 = id;
11803        msg.obj = response;
11804        mHandler.sendMessage(msg);
11805    }
11806
11807    @Override
11808    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11809            long millisecondsToDelay) {
11810        mContext.enforceCallingOrSelfPermission(
11811                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11812                "Only package verification agents can extend verification timeouts");
11813
11814        final PackageVerificationState state = mPendingVerification.get(id);
11815        final PackageVerificationResponse response = new PackageVerificationResponse(
11816                verificationCodeAtTimeout, Binder.getCallingUid());
11817
11818        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11819            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11820        }
11821        if (millisecondsToDelay < 0) {
11822            millisecondsToDelay = 0;
11823        }
11824        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11825                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11826            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11827        }
11828
11829        if ((state != null) && !state.timeoutExtended()) {
11830            state.extendTimeout();
11831
11832            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11833            msg.arg1 = id;
11834            msg.obj = response;
11835            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11836        }
11837    }
11838
11839    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11840            int verificationCode, UserHandle user) {
11841        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11842        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11843        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11844        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11845        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11846
11847        mContext.sendBroadcastAsUser(intent, user,
11848                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11849    }
11850
11851    private ComponentName matchComponentForVerifier(String packageName,
11852            List<ResolveInfo> receivers) {
11853        ActivityInfo targetReceiver = null;
11854
11855        final int NR = receivers.size();
11856        for (int i = 0; i < NR; i++) {
11857            final ResolveInfo info = receivers.get(i);
11858            if (info.activityInfo == null) {
11859                continue;
11860            }
11861
11862            if (packageName.equals(info.activityInfo.packageName)) {
11863                targetReceiver = info.activityInfo;
11864                break;
11865            }
11866        }
11867
11868        if (targetReceiver == null) {
11869            return null;
11870        }
11871
11872        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11873    }
11874
11875    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11876            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11877        if (pkgInfo.verifiers.length == 0) {
11878            return null;
11879        }
11880
11881        final int N = pkgInfo.verifiers.length;
11882        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11883        for (int i = 0; i < N; i++) {
11884            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11885
11886            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11887                    receivers);
11888            if (comp == null) {
11889                continue;
11890            }
11891
11892            final int verifierUid = getUidForVerifier(verifierInfo);
11893            if (verifierUid == -1) {
11894                continue;
11895            }
11896
11897            if (DEBUG_VERIFY) {
11898                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11899                        + " with the correct signature");
11900            }
11901            sufficientVerifiers.add(comp);
11902            verificationState.addSufficientVerifier(verifierUid);
11903        }
11904
11905        return sufficientVerifiers;
11906    }
11907
11908    private int getUidForVerifier(VerifierInfo verifierInfo) {
11909        synchronized (mPackages) {
11910            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11911            if (pkg == null) {
11912                return -1;
11913            } else if (pkg.mSignatures.length != 1) {
11914                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11915                        + " has more than one signature; ignoring");
11916                return -1;
11917            }
11918
11919            /*
11920             * If the public key of the package's signature does not match
11921             * our expected public key, then this is a different package and
11922             * we should skip.
11923             */
11924
11925            final byte[] expectedPublicKey;
11926            try {
11927                final Signature verifierSig = pkg.mSignatures[0];
11928                final PublicKey publicKey = verifierSig.getPublicKey();
11929                expectedPublicKey = publicKey.getEncoded();
11930            } catch (CertificateException e) {
11931                return -1;
11932            }
11933
11934            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11935
11936            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11937                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11938                        + " does not have the expected public key; ignoring");
11939                return -1;
11940            }
11941
11942            return pkg.applicationInfo.uid;
11943        }
11944    }
11945
11946    @Override
11947    public void finishPackageInstall(int token, boolean didLaunch) {
11948        enforceSystemOrRoot("Only the system is allowed to finish installs");
11949
11950        if (DEBUG_INSTALL) {
11951            Slog.v(TAG, "BM finishing package install for " + token);
11952        }
11953        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11954
11955        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11956        mHandler.sendMessage(msg);
11957    }
11958
11959    /**
11960     * Get the verification agent timeout.
11961     *
11962     * @return verification timeout in milliseconds
11963     */
11964    private long getVerificationTimeout() {
11965        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11966                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11967                DEFAULT_VERIFICATION_TIMEOUT);
11968    }
11969
11970    /**
11971     * Get the default verification agent response code.
11972     *
11973     * @return default verification response code
11974     */
11975    private int getDefaultVerificationResponse() {
11976        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11977                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11978                DEFAULT_VERIFICATION_RESPONSE);
11979    }
11980
11981    /**
11982     * Check whether or not package verification has been enabled.
11983     *
11984     * @return true if verification should be performed
11985     */
11986    private boolean isVerificationEnabled(int userId, int installFlags) {
11987        if (!DEFAULT_VERIFY_ENABLE) {
11988            return false;
11989        }
11990        // Ephemeral apps don't get the full verification treatment
11991        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11992            if (DEBUG_EPHEMERAL) {
11993                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11994            }
11995            return false;
11996        }
11997
11998        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11999
12000        // Check if installing from ADB
12001        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12002            // Do not run verification in a test harness environment
12003            if (ActivityManager.isRunningInTestHarness()) {
12004                return false;
12005            }
12006            if (ensureVerifyAppsEnabled) {
12007                return true;
12008            }
12009            // Check if the developer does not want package verification for ADB installs
12010            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12011                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12012                return false;
12013            }
12014        }
12015
12016        if (ensureVerifyAppsEnabled) {
12017            return true;
12018        }
12019
12020        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12021                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12022    }
12023
12024    @Override
12025    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12026            throws RemoteException {
12027        mContext.enforceCallingOrSelfPermission(
12028                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12029                "Only intentfilter verification agents can verify applications");
12030
12031        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12032        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12033                Binder.getCallingUid(), verificationCode, failedDomains);
12034        msg.arg1 = id;
12035        msg.obj = response;
12036        mHandler.sendMessage(msg);
12037    }
12038
12039    @Override
12040    public int getIntentVerificationStatus(String packageName, int userId) {
12041        synchronized (mPackages) {
12042            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12043        }
12044    }
12045
12046    @Override
12047    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12048        mContext.enforceCallingOrSelfPermission(
12049                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12050
12051        boolean result = false;
12052        synchronized (mPackages) {
12053            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12054        }
12055        if (result) {
12056            scheduleWritePackageRestrictionsLocked(userId);
12057        }
12058        return result;
12059    }
12060
12061    @Override
12062    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12063            String packageName) {
12064        synchronized (mPackages) {
12065            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12066        }
12067    }
12068
12069    @Override
12070    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12071        if (TextUtils.isEmpty(packageName)) {
12072            return ParceledListSlice.emptyList();
12073        }
12074        synchronized (mPackages) {
12075            PackageParser.Package pkg = mPackages.get(packageName);
12076            if (pkg == null || pkg.activities == null) {
12077                return ParceledListSlice.emptyList();
12078            }
12079            final int count = pkg.activities.size();
12080            ArrayList<IntentFilter> result = new ArrayList<>();
12081            for (int n=0; n<count; n++) {
12082                PackageParser.Activity activity = pkg.activities.get(n);
12083                if (activity.intents != null && activity.intents.size() > 0) {
12084                    result.addAll(activity.intents);
12085                }
12086            }
12087            return new ParceledListSlice<>(result);
12088        }
12089    }
12090
12091    @Override
12092    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12093        mContext.enforceCallingOrSelfPermission(
12094                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12095
12096        synchronized (mPackages) {
12097            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12098            if (packageName != null) {
12099                result |= updateIntentVerificationStatus(packageName,
12100                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12101                        userId);
12102                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12103                        packageName, userId);
12104            }
12105            return result;
12106        }
12107    }
12108
12109    @Override
12110    public String getDefaultBrowserPackageName(int userId) {
12111        synchronized (mPackages) {
12112            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12113        }
12114    }
12115
12116    /**
12117     * Get the "allow unknown sources" setting.
12118     *
12119     * @return the current "allow unknown sources" setting
12120     */
12121    private int getUnknownSourcesSettings() {
12122        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12123                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12124                -1);
12125    }
12126
12127    @Override
12128    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12129        final int uid = Binder.getCallingUid();
12130        // writer
12131        synchronized (mPackages) {
12132            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12133            if (targetPackageSetting == null) {
12134                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12135            }
12136
12137            PackageSetting installerPackageSetting;
12138            if (installerPackageName != null) {
12139                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12140                if (installerPackageSetting == null) {
12141                    throw new IllegalArgumentException("Unknown installer package: "
12142                            + installerPackageName);
12143                }
12144            } else {
12145                installerPackageSetting = null;
12146            }
12147
12148            Signature[] callerSignature;
12149            Object obj = mSettings.getUserIdLPr(uid);
12150            if (obj != null) {
12151                if (obj instanceof SharedUserSetting) {
12152                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12153                } else if (obj instanceof PackageSetting) {
12154                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12155                } else {
12156                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12157                }
12158            } else {
12159                throw new SecurityException("Unknown calling UID: " + uid);
12160            }
12161
12162            // Verify: can't set installerPackageName to a package that is
12163            // not signed with the same cert as the caller.
12164            if (installerPackageSetting != null) {
12165                if (compareSignatures(callerSignature,
12166                        installerPackageSetting.signatures.mSignatures)
12167                        != PackageManager.SIGNATURE_MATCH) {
12168                    throw new SecurityException(
12169                            "Caller does not have same cert as new installer package "
12170                            + installerPackageName);
12171                }
12172            }
12173
12174            // Verify: if target already has an installer package, it must
12175            // be signed with the same cert as the caller.
12176            if (targetPackageSetting.installerPackageName != null) {
12177                PackageSetting setting = mSettings.mPackages.get(
12178                        targetPackageSetting.installerPackageName);
12179                // If the currently set package isn't valid, then it's always
12180                // okay to change it.
12181                if (setting != null) {
12182                    if (compareSignatures(callerSignature,
12183                            setting.signatures.mSignatures)
12184                            != PackageManager.SIGNATURE_MATCH) {
12185                        throw new SecurityException(
12186                                "Caller does not have same cert as old installer package "
12187                                + targetPackageSetting.installerPackageName);
12188                    }
12189                }
12190            }
12191
12192            // Okay!
12193            targetPackageSetting.installerPackageName = installerPackageName;
12194            if (installerPackageName != null) {
12195                mSettings.mInstallerPackages.add(installerPackageName);
12196            }
12197            scheduleWriteSettingsLocked();
12198        }
12199    }
12200
12201    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12202        // Queue up an async operation since the package installation may take a little while.
12203        mHandler.post(new Runnable() {
12204            public void run() {
12205                mHandler.removeCallbacks(this);
12206                 // Result object to be returned
12207                PackageInstalledInfo res = new PackageInstalledInfo();
12208                res.setReturnCode(currentStatus);
12209                res.uid = -1;
12210                res.pkg = null;
12211                res.removedInfo = null;
12212                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12213                    args.doPreInstall(res.returnCode);
12214                    synchronized (mInstallLock) {
12215                        installPackageTracedLI(args, res);
12216                    }
12217                    args.doPostInstall(res.returnCode, res.uid);
12218                }
12219
12220                // A restore should be performed at this point if (a) the install
12221                // succeeded, (b) the operation is not an update, and (c) the new
12222                // package has not opted out of backup participation.
12223                final boolean update = res.removedInfo != null
12224                        && res.removedInfo.removedPackage != null;
12225                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12226                boolean doRestore = !update
12227                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12228
12229                // Set up the post-install work request bookkeeping.  This will be used
12230                // and cleaned up by the post-install event handling regardless of whether
12231                // there's a restore pass performed.  Token values are >= 1.
12232                int token;
12233                if (mNextInstallToken < 0) mNextInstallToken = 1;
12234                token = mNextInstallToken++;
12235
12236                PostInstallData data = new PostInstallData(args, res);
12237                mRunningInstalls.put(token, data);
12238                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12239
12240                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12241                    // Pass responsibility to the Backup Manager.  It will perform a
12242                    // restore if appropriate, then pass responsibility back to the
12243                    // Package Manager to run the post-install observer callbacks
12244                    // and broadcasts.
12245                    IBackupManager bm = IBackupManager.Stub.asInterface(
12246                            ServiceManager.getService(Context.BACKUP_SERVICE));
12247                    if (bm != null) {
12248                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12249                                + " to BM for possible restore");
12250                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12251                        try {
12252                            // TODO: http://b/22388012
12253                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12254                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12255                            } else {
12256                                doRestore = false;
12257                            }
12258                        } catch (RemoteException e) {
12259                            // can't happen; the backup manager is local
12260                        } catch (Exception e) {
12261                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12262                            doRestore = false;
12263                        }
12264                    } else {
12265                        Slog.e(TAG, "Backup Manager not found!");
12266                        doRestore = false;
12267                    }
12268                }
12269
12270                if (!doRestore) {
12271                    // No restore possible, or the Backup Manager was mysteriously not
12272                    // available -- just fire the post-install work request directly.
12273                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12274
12275                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12276
12277                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12278                    mHandler.sendMessage(msg);
12279                }
12280            }
12281        });
12282    }
12283
12284    /**
12285     * Callback from PackageSettings whenever an app is first transitioned out of the
12286     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12287     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12288     * here whether the app is the target of an ongoing install, and only send the
12289     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12290     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12291     * handling.
12292     */
12293    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12294        // Serialize this with the rest of the install-process message chain.  In the
12295        // restore-at-install case, this Runnable will necessarily run before the
12296        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12297        // are coherent.  In the non-restore case, the app has already completed install
12298        // and been launched through some other means, so it is not in a problematic
12299        // state for observers to see the FIRST_LAUNCH signal.
12300        mHandler.post(new Runnable() {
12301            @Override
12302            public void run() {
12303                for (int i = 0; i < mRunningInstalls.size(); i++) {
12304                    final PostInstallData data = mRunningInstalls.valueAt(i);
12305                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12306                        // right package; but is it for the right user?
12307                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12308                            if (userId == data.res.newUsers[uIndex]) {
12309                                if (DEBUG_BACKUP) {
12310                                    Slog.i(TAG, "Package " + pkgName
12311                                            + " being restored so deferring FIRST_LAUNCH");
12312                                }
12313                                return;
12314                            }
12315                        }
12316                    }
12317                }
12318                // didn't find it, so not being restored
12319                if (DEBUG_BACKUP) {
12320                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12321                }
12322                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12323            }
12324        });
12325    }
12326
12327    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12328        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12329                installerPkg, null, userIds);
12330    }
12331
12332    private abstract class HandlerParams {
12333        private static final int MAX_RETRIES = 4;
12334
12335        /**
12336         * Number of times startCopy() has been attempted and had a non-fatal
12337         * error.
12338         */
12339        private int mRetries = 0;
12340
12341        /** User handle for the user requesting the information or installation. */
12342        private final UserHandle mUser;
12343        String traceMethod;
12344        int traceCookie;
12345
12346        HandlerParams(UserHandle user) {
12347            mUser = user;
12348        }
12349
12350        UserHandle getUser() {
12351            return mUser;
12352        }
12353
12354        HandlerParams setTraceMethod(String traceMethod) {
12355            this.traceMethod = traceMethod;
12356            return this;
12357        }
12358
12359        HandlerParams setTraceCookie(int traceCookie) {
12360            this.traceCookie = traceCookie;
12361            return this;
12362        }
12363
12364        final boolean startCopy() {
12365            boolean res;
12366            try {
12367                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12368
12369                if (++mRetries > MAX_RETRIES) {
12370                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12371                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12372                    handleServiceError();
12373                    return false;
12374                } else {
12375                    handleStartCopy();
12376                    res = true;
12377                }
12378            } catch (RemoteException e) {
12379                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12380                mHandler.sendEmptyMessage(MCS_RECONNECT);
12381                res = false;
12382            }
12383            handleReturnCode();
12384            return res;
12385        }
12386
12387        final void serviceError() {
12388            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12389            handleServiceError();
12390            handleReturnCode();
12391        }
12392
12393        abstract void handleStartCopy() throws RemoteException;
12394        abstract void handleServiceError();
12395        abstract void handleReturnCode();
12396    }
12397
12398    class MeasureParams extends HandlerParams {
12399        private final PackageStats mStats;
12400        private boolean mSuccess;
12401
12402        private final IPackageStatsObserver mObserver;
12403
12404        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12405            super(new UserHandle(stats.userHandle));
12406            mObserver = observer;
12407            mStats = stats;
12408        }
12409
12410        @Override
12411        public String toString() {
12412            return "MeasureParams{"
12413                + Integer.toHexString(System.identityHashCode(this))
12414                + " " + mStats.packageName + "}";
12415        }
12416
12417        @Override
12418        void handleStartCopy() throws RemoteException {
12419            synchronized (mInstallLock) {
12420                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12421            }
12422
12423            if (mSuccess) {
12424                boolean mounted = false;
12425                try {
12426                    final String status = Environment.getExternalStorageState();
12427                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12428                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12429                } catch (Exception e) {
12430                }
12431
12432                if (mounted) {
12433                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12434
12435                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12436                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12437
12438                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12439                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12440
12441                    // Always subtract cache size, since it's a subdirectory
12442                    mStats.externalDataSize -= mStats.externalCacheSize;
12443
12444                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12445                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12446
12447                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12448                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12449                }
12450            }
12451        }
12452
12453        @Override
12454        void handleReturnCode() {
12455            if (mObserver != null) {
12456                try {
12457                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12458                } catch (RemoteException e) {
12459                    Slog.i(TAG, "Observer no longer exists.");
12460                }
12461            }
12462        }
12463
12464        @Override
12465        void handleServiceError() {
12466            Slog.e(TAG, "Could not measure application " + mStats.packageName
12467                            + " external storage");
12468        }
12469    }
12470
12471    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12472            throws RemoteException {
12473        long result = 0;
12474        for (File path : paths) {
12475            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12476        }
12477        return result;
12478    }
12479
12480    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12481        for (File path : paths) {
12482            try {
12483                mcs.clearDirectory(path.getAbsolutePath());
12484            } catch (RemoteException e) {
12485            }
12486        }
12487    }
12488
12489    static class OriginInfo {
12490        /**
12491         * Location where install is coming from, before it has been
12492         * copied/renamed into place. This could be a single monolithic APK
12493         * file, or a cluster directory. This location may be untrusted.
12494         */
12495        final File file;
12496        final String cid;
12497
12498        /**
12499         * Flag indicating that {@link #file} or {@link #cid} has already been
12500         * staged, meaning downstream users don't need to defensively copy the
12501         * contents.
12502         */
12503        final boolean staged;
12504
12505        /**
12506         * Flag indicating that {@link #file} or {@link #cid} is an already
12507         * installed app that is being moved.
12508         */
12509        final boolean existing;
12510
12511        final String resolvedPath;
12512        final File resolvedFile;
12513
12514        static OriginInfo fromNothing() {
12515            return new OriginInfo(null, null, false, false);
12516        }
12517
12518        static OriginInfo fromUntrustedFile(File file) {
12519            return new OriginInfo(file, null, false, false);
12520        }
12521
12522        static OriginInfo fromExistingFile(File file) {
12523            return new OriginInfo(file, null, false, true);
12524        }
12525
12526        static OriginInfo fromStagedFile(File file) {
12527            return new OriginInfo(file, null, true, false);
12528        }
12529
12530        static OriginInfo fromStagedContainer(String cid) {
12531            return new OriginInfo(null, cid, true, false);
12532        }
12533
12534        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12535            this.file = file;
12536            this.cid = cid;
12537            this.staged = staged;
12538            this.existing = existing;
12539
12540            if (cid != null) {
12541                resolvedPath = PackageHelper.getSdDir(cid);
12542                resolvedFile = new File(resolvedPath);
12543            } else if (file != null) {
12544                resolvedPath = file.getAbsolutePath();
12545                resolvedFile = file;
12546            } else {
12547                resolvedPath = null;
12548                resolvedFile = null;
12549            }
12550        }
12551    }
12552
12553    static class MoveInfo {
12554        final int moveId;
12555        final String fromUuid;
12556        final String toUuid;
12557        final String packageName;
12558        final String dataAppName;
12559        final int appId;
12560        final String seinfo;
12561        final int targetSdkVersion;
12562
12563        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12564                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12565            this.moveId = moveId;
12566            this.fromUuid = fromUuid;
12567            this.toUuid = toUuid;
12568            this.packageName = packageName;
12569            this.dataAppName = dataAppName;
12570            this.appId = appId;
12571            this.seinfo = seinfo;
12572            this.targetSdkVersion = targetSdkVersion;
12573        }
12574    }
12575
12576    static class VerificationInfo {
12577        /** A constant used to indicate that a uid value is not present. */
12578        public static final int NO_UID = -1;
12579
12580        /** URI referencing where the package was downloaded from. */
12581        final Uri originatingUri;
12582
12583        /** HTTP referrer URI associated with the originatingURI. */
12584        final Uri referrer;
12585
12586        /** UID of the application that the install request originated from. */
12587        final int originatingUid;
12588
12589        /** UID of application requesting the install */
12590        final int installerUid;
12591
12592        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12593            this.originatingUri = originatingUri;
12594            this.referrer = referrer;
12595            this.originatingUid = originatingUid;
12596            this.installerUid = installerUid;
12597        }
12598    }
12599
12600    class InstallParams extends HandlerParams {
12601        final OriginInfo origin;
12602        final MoveInfo move;
12603        final IPackageInstallObserver2 observer;
12604        int installFlags;
12605        final String installerPackageName;
12606        final String volumeUuid;
12607        private InstallArgs mArgs;
12608        private int mRet;
12609        final String packageAbiOverride;
12610        final String[] grantedRuntimePermissions;
12611        final VerificationInfo verificationInfo;
12612        final Certificate[][] certificates;
12613
12614        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12615                int installFlags, String installerPackageName, String volumeUuid,
12616                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12617                String[] grantedPermissions, Certificate[][] certificates) {
12618            super(user);
12619            this.origin = origin;
12620            this.move = move;
12621            this.observer = observer;
12622            this.installFlags = installFlags;
12623            this.installerPackageName = installerPackageName;
12624            this.volumeUuid = volumeUuid;
12625            this.verificationInfo = verificationInfo;
12626            this.packageAbiOverride = packageAbiOverride;
12627            this.grantedRuntimePermissions = grantedPermissions;
12628            this.certificates = certificates;
12629        }
12630
12631        @Override
12632        public String toString() {
12633            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12634                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12635        }
12636
12637        private int installLocationPolicy(PackageInfoLite pkgLite) {
12638            String packageName = pkgLite.packageName;
12639            int installLocation = pkgLite.installLocation;
12640            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12641            // reader
12642            synchronized (mPackages) {
12643                // Currently installed package which the new package is attempting to replace or
12644                // null if no such package is installed.
12645                PackageParser.Package installedPkg = mPackages.get(packageName);
12646                // Package which currently owns the data which the new package will own if installed.
12647                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12648                // will be null whereas dataOwnerPkg will contain information about the package
12649                // which was uninstalled while keeping its data.
12650                PackageParser.Package dataOwnerPkg = installedPkg;
12651                if (dataOwnerPkg  == null) {
12652                    PackageSetting ps = mSettings.mPackages.get(packageName);
12653                    if (ps != null) {
12654                        dataOwnerPkg = ps.pkg;
12655                    }
12656                }
12657
12658                if (dataOwnerPkg != null) {
12659                    // If installed, the package will get access to data left on the device by its
12660                    // predecessor. As a security measure, this is permited only if this is not a
12661                    // version downgrade or if the predecessor package is marked as debuggable and
12662                    // a downgrade is explicitly requested.
12663                    //
12664                    // On debuggable platform builds, downgrades are permitted even for
12665                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12666                    // not offer security guarantees and thus it's OK to disable some security
12667                    // mechanisms to make debugging/testing easier on those builds. However, even on
12668                    // debuggable builds downgrades of packages are permitted only if requested via
12669                    // installFlags. This is because we aim to keep the behavior of debuggable
12670                    // platform builds as close as possible to the behavior of non-debuggable
12671                    // platform builds.
12672                    final boolean downgradeRequested =
12673                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12674                    final boolean packageDebuggable =
12675                                (dataOwnerPkg.applicationInfo.flags
12676                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12677                    final boolean downgradePermitted =
12678                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12679                    if (!downgradePermitted) {
12680                        try {
12681                            checkDowngrade(dataOwnerPkg, pkgLite);
12682                        } catch (PackageManagerException e) {
12683                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12684                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12685                        }
12686                    }
12687                }
12688
12689                if (installedPkg != null) {
12690                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12691                        // Check for updated system application.
12692                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12693                            if (onSd) {
12694                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12695                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12696                            }
12697                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12698                        } else {
12699                            if (onSd) {
12700                                // Install flag overrides everything.
12701                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12702                            }
12703                            // If current upgrade specifies particular preference
12704                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12705                                // Application explicitly specified internal.
12706                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12707                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12708                                // App explictly prefers external. Let policy decide
12709                            } else {
12710                                // Prefer previous location
12711                                if (isExternal(installedPkg)) {
12712                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12713                                }
12714                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12715                            }
12716                        }
12717                    } else {
12718                        // Invalid install. Return error code
12719                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12720                    }
12721                }
12722            }
12723            // All the special cases have been taken care of.
12724            // Return result based on recommended install location.
12725            if (onSd) {
12726                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12727            }
12728            return pkgLite.recommendedInstallLocation;
12729        }
12730
12731        /*
12732         * Invoke remote method to get package information and install
12733         * location values. Override install location based on default
12734         * policy if needed and then create install arguments based
12735         * on the install location.
12736         */
12737        public void handleStartCopy() throws RemoteException {
12738            int ret = PackageManager.INSTALL_SUCCEEDED;
12739
12740            // If we're already staged, we've firmly committed to an install location
12741            if (origin.staged) {
12742                if (origin.file != null) {
12743                    installFlags |= PackageManager.INSTALL_INTERNAL;
12744                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12745                } else if (origin.cid != null) {
12746                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12747                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12748                } else {
12749                    throw new IllegalStateException("Invalid stage location");
12750                }
12751            }
12752
12753            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12754            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12755            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12756            PackageInfoLite pkgLite = null;
12757
12758            if (onInt && onSd) {
12759                // Check if both bits are set.
12760                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12761                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12762            } else if (onSd && ephemeral) {
12763                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12764                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12765            } else {
12766                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12767                        packageAbiOverride);
12768
12769                if (DEBUG_EPHEMERAL && ephemeral) {
12770                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12771                }
12772
12773                /*
12774                 * If we have too little free space, try to free cache
12775                 * before giving up.
12776                 */
12777                if (!origin.staged && pkgLite.recommendedInstallLocation
12778                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12779                    // TODO: focus freeing disk space on the target device
12780                    final StorageManager storage = StorageManager.from(mContext);
12781                    final long lowThreshold = storage.getStorageLowBytes(
12782                            Environment.getDataDirectory());
12783
12784                    final long sizeBytes = mContainerService.calculateInstalledSize(
12785                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12786
12787                    try {
12788                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12789                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12790                                installFlags, packageAbiOverride);
12791                    } catch (InstallerException e) {
12792                        Slog.w(TAG, "Failed to free cache", e);
12793                    }
12794
12795                    /*
12796                     * The cache free must have deleted the file we
12797                     * downloaded to install.
12798                     *
12799                     * TODO: fix the "freeCache" call to not delete
12800                     *       the file we care about.
12801                     */
12802                    if (pkgLite.recommendedInstallLocation
12803                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12804                        pkgLite.recommendedInstallLocation
12805                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12806                    }
12807                }
12808            }
12809
12810            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12811                int loc = pkgLite.recommendedInstallLocation;
12812                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12813                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12814                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12815                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12816                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12817                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12818                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12819                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12820                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12821                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12822                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12823                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12824                } else {
12825                    // Override with defaults if needed.
12826                    loc = installLocationPolicy(pkgLite);
12827                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12828                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12829                    } else if (!onSd && !onInt) {
12830                        // Override install location with flags
12831                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12832                            // Set the flag to install on external media.
12833                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12834                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12835                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12836                            if (DEBUG_EPHEMERAL) {
12837                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12838                            }
12839                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12840                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12841                                    |PackageManager.INSTALL_INTERNAL);
12842                        } else {
12843                            // Make sure the flag for installing on external
12844                            // media is unset
12845                            installFlags |= PackageManager.INSTALL_INTERNAL;
12846                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12847                        }
12848                    }
12849                }
12850            }
12851
12852            final InstallArgs args = createInstallArgs(this);
12853            mArgs = args;
12854
12855            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12856                // TODO: http://b/22976637
12857                // Apps installed for "all" users use the device owner to verify the app
12858                UserHandle verifierUser = getUser();
12859                if (verifierUser == UserHandle.ALL) {
12860                    verifierUser = UserHandle.SYSTEM;
12861                }
12862
12863                /*
12864                 * Determine if we have any installed package verifiers. If we
12865                 * do, then we'll defer to them to verify the packages.
12866                 */
12867                final int requiredUid = mRequiredVerifierPackage == null ? -1
12868                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12869                                verifierUser.getIdentifier());
12870                if (!origin.existing && requiredUid != -1
12871                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12872                    final Intent verification = new Intent(
12873                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12874                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12875                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12876                            PACKAGE_MIME_TYPE);
12877                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12878
12879                    // Query all live verifiers based on current user state
12880                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12881                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12882
12883                    if (DEBUG_VERIFY) {
12884                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12885                                + verification.toString() + " with " + pkgLite.verifiers.length
12886                                + " optional verifiers");
12887                    }
12888
12889                    final int verificationId = mPendingVerificationToken++;
12890
12891                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12892
12893                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12894                            installerPackageName);
12895
12896                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12897                            installFlags);
12898
12899                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12900                            pkgLite.packageName);
12901
12902                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12903                            pkgLite.versionCode);
12904
12905                    if (verificationInfo != null) {
12906                        if (verificationInfo.originatingUri != null) {
12907                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12908                                    verificationInfo.originatingUri);
12909                        }
12910                        if (verificationInfo.referrer != null) {
12911                            verification.putExtra(Intent.EXTRA_REFERRER,
12912                                    verificationInfo.referrer);
12913                        }
12914                        if (verificationInfo.originatingUid >= 0) {
12915                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12916                                    verificationInfo.originatingUid);
12917                        }
12918                        if (verificationInfo.installerUid >= 0) {
12919                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12920                                    verificationInfo.installerUid);
12921                        }
12922                    }
12923
12924                    final PackageVerificationState verificationState = new PackageVerificationState(
12925                            requiredUid, args);
12926
12927                    mPendingVerification.append(verificationId, verificationState);
12928
12929                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12930                            receivers, verificationState);
12931
12932                    /*
12933                     * If any sufficient verifiers were listed in the package
12934                     * manifest, attempt to ask them.
12935                     */
12936                    if (sufficientVerifiers != null) {
12937                        final int N = sufficientVerifiers.size();
12938                        if (N == 0) {
12939                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12940                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12941                        } else {
12942                            for (int i = 0; i < N; i++) {
12943                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12944
12945                                final Intent sufficientIntent = new Intent(verification);
12946                                sufficientIntent.setComponent(verifierComponent);
12947                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12948                            }
12949                        }
12950                    }
12951
12952                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12953                            mRequiredVerifierPackage, receivers);
12954                    if (ret == PackageManager.INSTALL_SUCCEEDED
12955                            && mRequiredVerifierPackage != null) {
12956                        Trace.asyncTraceBegin(
12957                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12958                        /*
12959                         * Send the intent to the required verification agent,
12960                         * but only start the verification timeout after the
12961                         * target BroadcastReceivers have run.
12962                         */
12963                        verification.setComponent(requiredVerifierComponent);
12964                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12965                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12966                                new BroadcastReceiver() {
12967                                    @Override
12968                                    public void onReceive(Context context, Intent intent) {
12969                                        final Message msg = mHandler
12970                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12971                                        msg.arg1 = verificationId;
12972                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12973                                    }
12974                                }, null, 0, null, null);
12975
12976                        /*
12977                         * We don't want the copy to proceed until verification
12978                         * succeeds, so null out this field.
12979                         */
12980                        mArgs = null;
12981                    }
12982                } else {
12983                    /*
12984                     * No package verification is enabled, so immediately start
12985                     * the remote call to initiate copy using temporary file.
12986                     */
12987                    ret = args.copyApk(mContainerService, true);
12988                }
12989            }
12990
12991            mRet = ret;
12992        }
12993
12994        @Override
12995        void handleReturnCode() {
12996            // If mArgs is null, then MCS couldn't be reached. When it
12997            // reconnects, it will try again to install. At that point, this
12998            // will succeed.
12999            if (mArgs != null) {
13000                processPendingInstall(mArgs, mRet);
13001            }
13002        }
13003
13004        @Override
13005        void handleServiceError() {
13006            mArgs = createInstallArgs(this);
13007            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13008        }
13009
13010        public boolean isForwardLocked() {
13011            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13012        }
13013    }
13014
13015    /**
13016     * Used during creation of InstallArgs
13017     *
13018     * @param installFlags package installation flags
13019     * @return true if should be installed on external storage
13020     */
13021    private static boolean installOnExternalAsec(int installFlags) {
13022        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13023            return false;
13024        }
13025        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13026            return true;
13027        }
13028        return false;
13029    }
13030
13031    /**
13032     * Used during creation of InstallArgs
13033     *
13034     * @param installFlags package installation flags
13035     * @return true if should be installed as forward locked
13036     */
13037    private static boolean installForwardLocked(int installFlags) {
13038        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13039    }
13040
13041    private InstallArgs createInstallArgs(InstallParams params) {
13042        if (params.move != null) {
13043            return new MoveInstallArgs(params);
13044        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13045            return new AsecInstallArgs(params);
13046        } else {
13047            return new FileInstallArgs(params);
13048        }
13049    }
13050
13051    /**
13052     * Create args that describe an existing installed package. Typically used
13053     * when cleaning up old installs, or used as a move source.
13054     */
13055    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13056            String resourcePath, String[] instructionSets) {
13057        final boolean isInAsec;
13058        if (installOnExternalAsec(installFlags)) {
13059            /* Apps on SD card are always in ASEC containers. */
13060            isInAsec = true;
13061        } else if (installForwardLocked(installFlags)
13062                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13063            /*
13064             * Forward-locked apps are only in ASEC containers if they're the
13065             * new style
13066             */
13067            isInAsec = true;
13068        } else {
13069            isInAsec = false;
13070        }
13071
13072        if (isInAsec) {
13073            return new AsecInstallArgs(codePath, instructionSets,
13074                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13075        } else {
13076            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13077        }
13078    }
13079
13080    static abstract class InstallArgs {
13081        /** @see InstallParams#origin */
13082        final OriginInfo origin;
13083        /** @see InstallParams#move */
13084        final MoveInfo move;
13085
13086        final IPackageInstallObserver2 observer;
13087        // Always refers to PackageManager flags only
13088        final int installFlags;
13089        final String installerPackageName;
13090        final String volumeUuid;
13091        final UserHandle user;
13092        final String abiOverride;
13093        final String[] installGrantPermissions;
13094        /** If non-null, drop an async trace when the install completes */
13095        final String traceMethod;
13096        final int traceCookie;
13097        final Certificate[][] certificates;
13098
13099        // The list of instruction sets supported by this app. This is currently
13100        // only used during the rmdex() phase to clean up resources. We can get rid of this
13101        // if we move dex files under the common app path.
13102        /* nullable */ String[] instructionSets;
13103
13104        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13105                int installFlags, String installerPackageName, String volumeUuid,
13106                UserHandle user, String[] instructionSets,
13107                String abiOverride, String[] installGrantPermissions,
13108                String traceMethod, int traceCookie, Certificate[][] certificates) {
13109            this.origin = origin;
13110            this.move = move;
13111            this.installFlags = installFlags;
13112            this.observer = observer;
13113            this.installerPackageName = installerPackageName;
13114            this.volumeUuid = volumeUuid;
13115            this.user = user;
13116            this.instructionSets = instructionSets;
13117            this.abiOverride = abiOverride;
13118            this.installGrantPermissions = installGrantPermissions;
13119            this.traceMethod = traceMethod;
13120            this.traceCookie = traceCookie;
13121            this.certificates = certificates;
13122        }
13123
13124        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13125        abstract int doPreInstall(int status);
13126
13127        /**
13128         * Rename package into final resting place. All paths on the given
13129         * scanned package should be updated to reflect the rename.
13130         */
13131        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13132        abstract int doPostInstall(int status, int uid);
13133
13134        /** @see PackageSettingBase#codePathString */
13135        abstract String getCodePath();
13136        /** @see PackageSettingBase#resourcePathString */
13137        abstract String getResourcePath();
13138
13139        // Need installer lock especially for dex file removal.
13140        abstract void cleanUpResourcesLI();
13141        abstract boolean doPostDeleteLI(boolean delete);
13142
13143        /**
13144         * Called before the source arguments are copied. This is used mostly
13145         * for MoveParams when it needs to read the source file to put it in the
13146         * destination.
13147         */
13148        int doPreCopy() {
13149            return PackageManager.INSTALL_SUCCEEDED;
13150        }
13151
13152        /**
13153         * Called after the source arguments are copied. This is used mostly for
13154         * MoveParams when it needs to read the source file to put it in the
13155         * destination.
13156         */
13157        int doPostCopy(int uid) {
13158            return PackageManager.INSTALL_SUCCEEDED;
13159        }
13160
13161        protected boolean isFwdLocked() {
13162            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13163        }
13164
13165        protected boolean isExternalAsec() {
13166            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13167        }
13168
13169        protected boolean isEphemeral() {
13170            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13171        }
13172
13173        UserHandle getUser() {
13174            return user;
13175        }
13176    }
13177
13178    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13179        if (!allCodePaths.isEmpty()) {
13180            if (instructionSets == null) {
13181                throw new IllegalStateException("instructionSet == null");
13182            }
13183            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13184            for (String codePath : allCodePaths) {
13185                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13186                    try {
13187                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13188                    } catch (InstallerException ignored) {
13189                    }
13190                }
13191            }
13192        }
13193    }
13194
13195    /**
13196     * Logic to handle installation of non-ASEC applications, including copying
13197     * and renaming logic.
13198     */
13199    class FileInstallArgs extends InstallArgs {
13200        private File codeFile;
13201        private File resourceFile;
13202
13203        // Example topology:
13204        // /data/app/com.example/base.apk
13205        // /data/app/com.example/split_foo.apk
13206        // /data/app/com.example/lib/arm/libfoo.so
13207        // /data/app/com.example/lib/arm64/libfoo.so
13208        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13209
13210        /** New install */
13211        FileInstallArgs(InstallParams params) {
13212            super(params.origin, params.move, params.observer, params.installFlags,
13213                    params.installerPackageName, params.volumeUuid,
13214                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13215                    params.grantedRuntimePermissions,
13216                    params.traceMethod, params.traceCookie, params.certificates);
13217            if (isFwdLocked()) {
13218                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13219            }
13220        }
13221
13222        /** Existing install */
13223        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13224            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13225                    null, null, null, 0, null /*certificates*/);
13226            this.codeFile = (codePath != null) ? new File(codePath) : null;
13227            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13228        }
13229
13230        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13231            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13232            try {
13233                return doCopyApk(imcs, temp);
13234            } finally {
13235                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13236            }
13237        }
13238
13239        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13240            if (origin.staged) {
13241                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13242                codeFile = origin.file;
13243                resourceFile = origin.file;
13244                return PackageManager.INSTALL_SUCCEEDED;
13245            }
13246
13247            try {
13248                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13249                final File tempDir =
13250                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13251                codeFile = tempDir;
13252                resourceFile = tempDir;
13253            } catch (IOException e) {
13254                Slog.w(TAG, "Failed to create copy file: " + e);
13255                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13256            }
13257
13258            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13259                @Override
13260                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13261                    if (!FileUtils.isValidExtFilename(name)) {
13262                        throw new IllegalArgumentException("Invalid filename: " + name);
13263                    }
13264                    try {
13265                        final File file = new File(codeFile, name);
13266                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13267                                O_RDWR | O_CREAT, 0644);
13268                        Os.chmod(file.getAbsolutePath(), 0644);
13269                        return new ParcelFileDescriptor(fd);
13270                    } catch (ErrnoException e) {
13271                        throw new RemoteException("Failed to open: " + e.getMessage());
13272                    }
13273                }
13274            };
13275
13276            int ret = PackageManager.INSTALL_SUCCEEDED;
13277            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13278            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13279                Slog.e(TAG, "Failed to copy package");
13280                return ret;
13281            }
13282
13283            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13284            NativeLibraryHelper.Handle handle = null;
13285            try {
13286                handle = NativeLibraryHelper.Handle.create(codeFile);
13287                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13288                        abiOverride);
13289            } catch (IOException e) {
13290                Slog.e(TAG, "Copying native libraries failed", e);
13291                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13292            } finally {
13293                IoUtils.closeQuietly(handle);
13294            }
13295
13296            return ret;
13297        }
13298
13299        int doPreInstall(int status) {
13300            if (status != PackageManager.INSTALL_SUCCEEDED) {
13301                cleanUp();
13302            }
13303            return status;
13304        }
13305
13306        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13307            if (status != PackageManager.INSTALL_SUCCEEDED) {
13308                cleanUp();
13309                return false;
13310            }
13311
13312            final File targetDir = codeFile.getParentFile();
13313            final File beforeCodeFile = codeFile;
13314            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13315
13316            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13317            try {
13318                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13319            } catch (ErrnoException e) {
13320                Slog.w(TAG, "Failed to rename", e);
13321                return false;
13322            }
13323
13324            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13325                Slog.w(TAG, "Failed to restorecon");
13326                return false;
13327            }
13328
13329            // Reflect the rename internally
13330            codeFile = afterCodeFile;
13331            resourceFile = afterCodeFile;
13332
13333            // Reflect the rename in scanned details
13334            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13335            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13336                    afterCodeFile, pkg.baseCodePath));
13337            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13338                    afterCodeFile, pkg.splitCodePaths));
13339
13340            // Reflect the rename in app info
13341            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13342            pkg.setApplicationInfoCodePath(pkg.codePath);
13343            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13344            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13345            pkg.setApplicationInfoResourcePath(pkg.codePath);
13346            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13347            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13348
13349            return true;
13350        }
13351
13352        int doPostInstall(int status, int uid) {
13353            if (status != PackageManager.INSTALL_SUCCEEDED) {
13354                cleanUp();
13355            }
13356            return status;
13357        }
13358
13359        @Override
13360        String getCodePath() {
13361            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13362        }
13363
13364        @Override
13365        String getResourcePath() {
13366            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13367        }
13368
13369        private boolean cleanUp() {
13370            if (codeFile == null || !codeFile.exists()) {
13371                return false;
13372            }
13373
13374            removeCodePathLI(codeFile);
13375
13376            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13377                resourceFile.delete();
13378            }
13379
13380            return true;
13381        }
13382
13383        void cleanUpResourcesLI() {
13384            // Try enumerating all code paths before deleting
13385            List<String> allCodePaths = Collections.EMPTY_LIST;
13386            if (codeFile != null && codeFile.exists()) {
13387                try {
13388                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13389                    allCodePaths = pkg.getAllCodePaths();
13390                } catch (PackageParserException e) {
13391                    // Ignored; we tried our best
13392                }
13393            }
13394
13395            cleanUp();
13396            removeDexFiles(allCodePaths, instructionSets);
13397        }
13398
13399        boolean doPostDeleteLI(boolean delete) {
13400            // XXX err, shouldn't we respect the delete flag?
13401            cleanUpResourcesLI();
13402            return true;
13403        }
13404    }
13405
13406    private boolean isAsecExternal(String cid) {
13407        final String asecPath = PackageHelper.getSdFilesystem(cid);
13408        return !asecPath.startsWith(mAsecInternalPath);
13409    }
13410
13411    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13412            PackageManagerException {
13413        if (copyRet < 0) {
13414            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13415                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13416                throw new PackageManagerException(copyRet, message);
13417            }
13418        }
13419    }
13420
13421    /**
13422     * Extract the MountService "container ID" from the full code path of an
13423     * .apk.
13424     */
13425    static String cidFromCodePath(String fullCodePath) {
13426        int eidx = fullCodePath.lastIndexOf("/");
13427        String subStr1 = fullCodePath.substring(0, eidx);
13428        int sidx = subStr1.lastIndexOf("/");
13429        return subStr1.substring(sidx+1, eidx);
13430    }
13431
13432    /**
13433     * Logic to handle installation of ASEC applications, including copying and
13434     * renaming logic.
13435     */
13436    class AsecInstallArgs extends InstallArgs {
13437        static final String RES_FILE_NAME = "pkg.apk";
13438        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13439
13440        String cid;
13441        String packagePath;
13442        String resourcePath;
13443
13444        /** New install */
13445        AsecInstallArgs(InstallParams params) {
13446            super(params.origin, params.move, params.observer, params.installFlags,
13447                    params.installerPackageName, params.volumeUuid,
13448                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13449                    params.grantedRuntimePermissions,
13450                    params.traceMethod, params.traceCookie, params.certificates);
13451        }
13452
13453        /** Existing install */
13454        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13455                        boolean isExternal, boolean isForwardLocked) {
13456            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13457              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13458                    instructionSets, null, null, null, 0, null /*certificates*/);
13459            // Hackily pretend we're still looking at a full code path
13460            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13461                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13462            }
13463
13464            // Extract cid from fullCodePath
13465            int eidx = fullCodePath.lastIndexOf("/");
13466            String subStr1 = fullCodePath.substring(0, eidx);
13467            int sidx = subStr1.lastIndexOf("/");
13468            cid = subStr1.substring(sidx+1, eidx);
13469            setMountPath(subStr1);
13470        }
13471
13472        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13473            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13474              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13475                    instructionSets, null, null, null, 0, null /*certificates*/);
13476            this.cid = cid;
13477            setMountPath(PackageHelper.getSdDir(cid));
13478        }
13479
13480        void createCopyFile() {
13481            cid = mInstallerService.allocateExternalStageCidLegacy();
13482        }
13483
13484        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13485            if (origin.staged && origin.cid != null) {
13486                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13487                cid = origin.cid;
13488                setMountPath(PackageHelper.getSdDir(cid));
13489                return PackageManager.INSTALL_SUCCEEDED;
13490            }
13491
13492            if (temp) {
13493                createCopyFile();
13494            } else {
13495                /*
13496                 * Pre-emptively destroy the container since it's destroyed if
13497                 * copying fails due to it existing anyway.
13498                 */
13499                PackageHelper.destroySdDir(cid);
13500            }
13501
13502            final String newMountPath = imcs.copyPackageToContainer(
13503                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13504                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13505
13506            if (newMountPath != null) {
13507                setMountPath(newMountPath);
13508                return PackageManager.INSTALL_SUCCEEDED;
13509            } else {
13510                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13511            }
13512        }
13513
13514        @Override
13515        String getCodePath() {
13516            return packagePath;
13517        }
13518
13519        @Override
13520        String getResourcePath() {
13521            return resourcePath;
13522        }
13523
13524        int doPreInstall(int status) {
13525            if (status != PackageManager.INSTALL_SUCCEEDED) {
13526                // Destroy container
13527                PackageHelper.destroySdDir(cid);
13528            } else {
13529                boolean mounted = PackageHelper.isContainerMounted(cid);
13530                if (!mounted) {
13531                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13532                            Process.SYSTEM_UID);
13533                    if (newMountPath != null) {
13534                        setMountPath(newMountPath);
13535                    } else {
13536                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13537                    }
13538                }
13539            }
13540            return status;
13541        }
13542
13543        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13544            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13545            String newMountPath = null;
13546            if (PackageHelper.isContainerMounted(cid)) {
13547                // Unmount the container
13548                if (!PackageHelper.unMountSdDir(cid)) {
13549                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13550                    return false;
13551                }
13552            }
13553            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13554                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13555                        " which might be stale. Will try to clean up.");
13556                // Clean up the stale container and proceed to recreate.
13557                if (!PackageHelper.destroySdDir(newCacheId)) {
13558                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13559                    return false;
13560                }
13561                // Successfully cleaned up stale container. Try to rename again.
13562                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13563                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13564                            + " inspite of cleaning it up.");
13565                    return false;
13566                }
13567            }
13568            if (!PackageHelper.isContainerMounted(newCacheId)) {
13569                Slog.w(TAG, "Mounting container " + newCacheId);
13570                newMountPath = PackageHelper.mountSdDir(newCacheId,
13571                        getEncryptKey(), Process.SYSTEM_UID);
13572            } else {
13573                newMountPath = PackageHelper.getSdDir(newCacheId);
13574            }
13575            if (newMountPath == null) {
13576                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13577                return false;
13578            }
13579            Log.i(TAG, "Succesfully renamed " + cid +
13580                    " to " + newCacheId +
13581                    " at new path: " + newMountPath);
13582            cid = newCacheId;
13583
13584            final File beforeCodeFile = new File(packagePath);
13585            setMountPath(newMountPath);
13586            final File afterCodeFile = new File(packagePath);
13587
13588            // Reflect the rename in scanned details
13589            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13590            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13591                    afterCodeFile, pkg.baseCodePath));
13592            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13593                    afterCodeFile, pkg.splitCodePaths));
13594
13595            // Reflect the rename in app info
13596            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13597            pkg.setApplicationInfoCodePath(pkg.codePath);
13598            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13599            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13600            pkg.setApplicationInfoResourcePath(pkg.codePath);
13601            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13602            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13603
13604            return true;
13605        }
13606
13607        private void setMountPath(String mountPath) {
13608            final File mountFile = new File(mountPath);
13609
13610            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13611            if (monolithicFile.exists()) {
13612                packagePath = monolithicFile.getAbsolutePath();
13613                if (isFwdLocked()) {
13614                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13615                } else {
13616                    resourcePath = packagePath;
13617                }
13618            } else {
13619                packagePath = mountFile.getAbsolutePath();
13620                resourcePath = packagePath;
13621            }
13622        }
13623
13624        int doPostInstall(int status, int uid) {
13625            if (status != PackageManager.INSTALL_SUCCEEDED) {
13626                cleanUp();
13627            } else {
13628                final int groupOwner;
13629                final String protectedFile;
13630                if (isFwdLocked()) {
13631                    groupOwner = UserHandle.getSharedAppGid(uid);
13632                    protectedFile = RES_FILE_NAME;
13633                } else {
13634                    groupOwner = -1;
13635                    protectedFile = null;
13636                }
13637
13638                if (uid < Process.FIRST_APPLICATION_UID
13639                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13640                    Slog.e(TAG, "Failed to finalize " + cid);
13641                    PackageHelper.destroySdDir(cid);
13642                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13643                }
13644
13645                boolean mounted = PackageHelper.isContainerMounted(cid);
13646                if (!mounted) {
13647                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13648                }
13649            }
13650            return status;
13651        }
13652
13653        private void cleanUp() {
13654            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13655
13656            // Destroy secure container
13657            PackageHelper.destroySdDir(cid);
13658        }
13659
13660        private List<String> getAllCodePaths() {
13661            final File codeFile = new File(getCodePath());
13662            if (codeFile != null && codeFile.exists()) {
13663                try {
13664                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13665                    return pkg.getAllCodePaths();
13666                } catch (PackageParserException e) {
13667                    // Ignored; we tried our best
13668                }
13669            }
13670            return Collections.EMPTY_LIST;
13671        }
13672
13673        void cleanUpResourcesLI() {
13674            // Enumerate all code paths before deleting
13675            cleanUpResourcesLI(getAllCodePaths());
13676        }
13677
13678        private void cleanUpResourcesLI(List<String> allCodePaths) {
13679            cleanUp();
13680            removeDexFiles(allCodePaths, instructionSets);
13681        }
13682
13683        String getPackageName() {
13684            return getAsecPackageName(cid);
13685        }
13686
13687        boolean doPostDeleteLI(boolean delete) {
13688            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13689            final List<String> allCodePaths = getAllCodePaths();
13690            boolean mounted = PackageHelper.isContainerMounted(cid);
13691            if (mounted) {
13692                // Unmount first
13693                if (PackageHelper.unMountSdDir(cid)) {
13694                    mounted = false;
13695                }
13696            }
13697            if (!mounted && delete) {
13698                cleanUpResourcesLI(allCodePaths);
13699            }
13700            return !mounted;
13701        }
13702
13703        @Override
13704        int doPreCopy() {
13705            if (isFwdLocked()) {
13706                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13707                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13708                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13709                }
13710            }
13711
13712            return PackageManager.INSTALL_SUCCEEDED;
13713        }
13714
13715        @Override
13716        int doPostCopy(int uid) {
13717            if (isFwdLocked()) {
13718                if (uid < Process.FIRST_APPLICATION_UID
13719                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13720                                RES_FILE_NAME)) {
13721                    Slog.e(TAG, "Failed to finalize " + cid);
13722                    PackageHelper.destroySdDir(cid);
13723                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13724                }
13725            }
13726
13727            return PackageManager.INSTALL_SUCCEEDED;
13728        }
13729    }
13730
13731    /**
13732     * Logic to handle movement of existing installed applications.
13733     */
13734    class MoveInstallArgs extends InstallArgs {
13735        private File codeFile;
13736        private File resourceFile;
13737
13738        /** New install */
13739        MoveInstallArgs(InstallParams params) {
13740            super(params.origin, params.move, params.observer, params.installFlags,
13741                    params.installerPackageName, params.volumeUuid,
13742                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13743                    params.grantedRuntimePermissions,
13744                    params.traceMethod, params.traceCookie, params.certificates);
13745        }
13746
13747        int copyApk(IMediaContainerService imcs, boolean temp) {
13748            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13749                    + move.fromUuid + " to " + move.toUuid);
13750            synchronized (mInstaller) {
13751                try {
13752                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13753                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13754                } catch (InstallerException e) {
13755                    Slog.w(TAG, "Failed to move app", e);
13756                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13757                }
13758            }
13759
13760            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13761            resourceFile = codeFile;
13762            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13763
13764            return PackageManager.INSTALL_SUCCEEDED;
13765        }
13766
13767        int doPreInstall(int status) {
13768            if (status != PackageManager.INSTALL_SUCCEEDED) {
13769                cleanUp(move.toUuid);
13770            }
13771            return status;
13772        }
13773
13774        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13775            if (status != PackageManager.INSTALL_SUCCEEDED) {
13776                cleanUp(move.toUuid);
13777                return false;
13778            }
13779
13780            // Reflect the move in app info
13781            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13782            pkg.setApplicationInfoCodePath(pkg.codePath);
13783            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13784            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13785            pkg.setApplicationInfoResourcePath(pkg.codePath);
13786            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13787            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13788
13789            return true;
13790        }
13791
13792        int doPostInstall(int status, int uid) {
13793            if (status == PackageManager.INSTALL_SUCCEEDED) {
13794                cleanUp(move.fromUuid);
13795            } else {
13796                cleanUp(move.toUuid);
13797            }
13798            return status;
13799        }
13800
13801        @Override
13802        String getCodePath() {
13803            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13804        }
13805
13806        @Override
13807        String getResourcePath() {
13808            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13809        }
13810
13811        private boolean cleanUp(String volumeUuid) {
13812            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13813                    move.dataAppName);
13814            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13815            final int[] userIds = sUserManager.getUserIds();
13816            synchronized (mInstallLock) {
13817                // Clean up both app data and code
13818                // All package moves are frozen until finished
13819                for (int userId : userIds) {
13820                    try {
13821                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13822                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13823                    } catch (InstallerException e) {
13824                        Slog.w(TAG, String.valueOf(e));
13825                    }
13826                }
13827                removeCodePathLI(codeFile);
13828            }
13829            return true;
13830        }
13831
13832        void cleanUpResourcesLI() {
13833            throw new UnsupportedOperationException();
13834        }
13835
13836        boolean doPostDeleteLI(boolean delete) {
13837            throw new UnsupportedOperationException();
13838        }
13839    }
13840
13841    static String getAsecPackageName(String packageCid) {
13842        int idx = packageCid.lastIndexOf("-");
13843        if (idx == -1) {
13844            return packageCid;
13845        }
13846        return packageCid.substring(0, idx);
13847    }
13848
13849    // Utility method used to create code paths based on package name and available index.
13850    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13851        String idxStr = "";
13852        int idx = 1;
13853        // Fall back to default value of idx=1 if prefix is not
13854        // part of oldCodePath
13855        if (oldCodePath != null) {
13856            String subStr = oldCodePath;
13857            // Drop the suffix right away
13858            if (suffix != null && subStr.endsWith(suffix)) {
13859                subStr = subStr.substring(0, subStr.length() - suffix.length());
13860            }
13861            // If oldCodePath already contains prefix find out the
13862            // ending index to either increment or decrement.
13863            int sidx = subStr.lastIndexOf(prefix);
13864            if (sidx != -1) {
13865                subStr = subStr.substring(sidx + prefix.length());
13866                if (subStr != null) {
13867                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13868                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13869                    }
13870                    try {
13871                        idx = Integer.parseInt(subStr);
13872                        if (idx <= 1) {
13873                            idx++;
13874                        } else {
13875                            idx--;
13876                        }
13877                    } catch(NumberFormatException e) {
13878                    }
13879                }
13880            }
13881        }
13882        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13883        return prefix + idxStr;
13884    }
13885
13886    private File getNextCodePath(File targetDir, String packageName) {
13887        int suffix = 1;
13888        File result;
13889        do {
13890            result = new File(targetDir, packageName + "-" + suffix);
13891            suffix++;
13892        } while (result.exists());
13893        return result;
13894    }
13895
13896    // Utility method that returns the relative package path with respect
13897    // to the installation directory. Like say for /data/data/com.test-1.apk
13898    // string com.test-1 is returned.
13899    static String deriveCodePathName(String codePath) {
13900        if (codePath == null) {
13901            return null;
13902        }
13903        final File codeFile = new File(codePath);
13904        final String name = codeFile.getName();
13905        if (codeFile.isDirectory()) {
13906            return name;
13907        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13908            final int lastDot = name.lastIndexOf('.');
13909            return name.substring(0, lastDot);
13910        } else {
13911            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13912            return null;
13913        }
13914    }
13915
13916    static class PackageInstalledInfo {
13917        String name;
13918        int uid;
13919        // The set of users that originally had this package installed.
13920        int[] origUsers;
13921        // The set of users that now have this package installed.
13922        int[] newUsers;
13923        PackageParser.Package pkg;
13924        int returnCode;
13925        String returnMsg;
13926        PackageRemovedInfo removedInfo;
13927        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13928
13929        public void setError(int code, String msg) {
13930            setReturnCode(code);
13931            setReturnMessage(msg);
13932            Slog.w(TAG, msg);
13933        }
13934
13935        public void setError(String msg, PackageParserException e) {
13936            setReturnCode(e.error);
13937            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13938            Slog.w(TAG, msg, e);
13939        }
13940
13941        public void setError(String msg, PackageManagerException e) {
13942            returnCode = e.error;
13943            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13944            Slog.w(TAG, msg, e);
13945        }
13946
13947        public void setReturnCode(int returnCode) {
13948            this.returnCode = returnCode;
13949            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13950            for (int i = 0; i < childCount; i++) {
13951                addedChildPackages.valueAt(i).returnCode = returnCode;
13952            }
13953        }
13954
13955        private void setReturnMessage(String returnMsg) {
13956            this.returnMsg = returnMsg;
13957            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13958            for (int i = 0; i < childCount; i++) {
13959                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13960            }
13961        }
13962
13963        // In some error cases we want to convey more info back to the observer
13964        String origPackage;
13965        String origPermission;
13966    }
13967
13968    /*
13969     * Install a non-existing package.
13970     */
13971    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13972            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13973            PackageInstalledInfo res) {
13974        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13975
13976        // Remember this for later, in case we need to rollback this install
13977        String pkgName = pkg.packageName;
13978
13979        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13980
13981        synchronized(mPackages) {
13982            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13983                // A package with the same name is already installed, though
13984                // it has been renamed to an older name.  The package we
13985                // are trying to install should be installed as an update to
13986                // the existing one, but that has not been requested, so bail.
13987                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13988                        + " without first uninstalling package running as "
13989                        + mSettings.mRenamedPackages.get(pkgName));
13990                return;
13991            }
13992            if (mPackages.containsKey(pkgName)) {
13993                // Don't allow installation over an existing package with the same name.
13994                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13995                        + " without first uninstalling.");
13996                return;
13997            }
13998        }
13999
14000        try {
14001            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14002                    System.currentTimeMillis(), user);
14003
14004            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14005
14006            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14007                prepareAppDataAfterInstallLIF(newPackage);
14008
14009            } else {
14010                // Remove package from internal structures, but keep around any
14011                // data that might have already existed
14012                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14013                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14014            }
14015        } catch (PackageManagerException e) {
14016            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14017        }
14018
14019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14020    }
14021
14022    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14023        // Can't rotate keys during boot or if sharedUser.
14024        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14025                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14026            return false;
14027        }
14028        // app is using upgradeKeySets; make sure all are valid
14029        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14030        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14031        for (int i = 0; i < upgradeKeySets.length; i++) {
14032            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14033                Slog.wtf(TAG, "Package "
14034                         + (oldPs.name != null ? oldPs.name : "<null>")
14035                         + " contains upgrade-key-set reference to unknown key-set: "
14036                         + upgradeKeySets[i]
14037                         + " reverting to signatures check.");
14038                return false;
14039            }
14040        }
14041        return true;
14042    }
14043
14044    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14045        // Upgrade keysets are being used.  Determine if new package has a superset of the
14046        // required keys.
14047        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14048        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14049        for (int i = 0; i < upgradeKeySets.length; i++) {
14050            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14051            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14052                return true;
14053            }
14054        }
14055        return false;
14056    }
14057
14058    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14059        try (DigestInputStream digestStream =
14060                new DigestInputStream(new FileInputStream(file), digest)) {
14061            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14062        }
14063    }
14064
14065    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14066            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14067        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14068
14069        final PackageParser.Package oldPackage;
14070        final String pkgName = pkg.packageName;
14071        final int[] allUsers;
14072        final int[] installedUsers;
14073
14074        synchronized(mPackages) {
14075            oldPackage = mPackages.get(pkgName);
14076            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14077
14078            // don't allow upgrade to target a release SDK from a pre-release SDK
14079            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14080                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14081            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14082                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14083            if (oldTargetsPreRelease
14084                    && !newTargetsPreRelease
14085                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14086                Slog.w(TAG, "Can't install package targeting released sdk");
14087                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14088                return;
14089            }
14090
14091            // don't allow an upgrade from full to ephemeral
14092            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14093            if (isEphemeral && !oldIsEphemeral) {
14094                // can't downgrade from full to ephemeral
14095                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14096                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14097                return;
14098            }
14099
14100            // verify signatures are valid
14101            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14102            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14103                if (!checkUpgradeKeySetLP(ps, pkg)) {
14104                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14105                            "New package not signed by keys specified by upgrade-keysets: "
14106                                    + pkgName);
14107                    return;
14108                }
14109            } else {
14110                // default to original signature matching
14111                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14112                        != PackageManager.SIGNATURE_MATCH) {
14113                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14114                            "New package has a different signature: " + pkgName);
14115                    return;
14116                }
14117            }
14118
14119            // don't allow a system upgrade unless the upgrade hash matches
14120            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14121                byte[] digestBytes = null;
14122                try {
14123                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14124                    updateDigest(digest, new File(pkg.baseCodePath));
14125                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14126                        for (String path : pkg.splitCodePaths) {
14127                            updateDigest(digest, new File(path));
14128                        }
14129                    }
14130                    digestBytes = digest.digest();
14131                } catch (NoSuchAlgorithmException | IOException e) {
14132                    res.setError(INSTALL_FAILED_INVALID_APK,
14133                            "Could not compute hash: " + pkgName);
14134                    return;
14135                }
14136                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14137                    res.setError(INSTALL_FAILED_INVALID_APK,
14138                            "New package fails restrict-update check: " + pkgName);
14139                    return;
14140                }
14141                // retain upgrade restriction
14142                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14143            }
14144
14145            // Check for shared user id changes
14146            String invalidPackageName =
14147                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14148            if (invalidPackageName != null) {
14149                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14150                        "Package " + invalidPackageName + " tried to change user "
14151                                + oldPackage.mSharedUserId);
14152                return;
14153            }
14154
14155            // In case of rollback, remember per-user/profile install state
14156            allUsers = sUserManager.getUserIds();
14157            installedUsers = ps.queryInstalledUsers(allUsers, true);
14158        }
14159
14160        // Update what is removed
14161        res.removedInfo = new PackageRemovedInfo();
14162        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14163        res.removedInfo.removedPackage = oldPackage.packageName;
14164        res.removedInfo.isUpdate = true;
14165        res.removedInfo.origUsers = installedUsers;
14166        final int childCount = (oldPackage.childPackages != null)
14167                ? oldPackage.childPackages.size() : 0;
14168        for (int i = 0; i < childCount; i++) {
14169            boolean childPackageUpdated = false;
14170            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14171            if (res.addedChildPackages != null) {
14172                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14173                if (childRes != null) {
14174                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14175                    childRes.removedInfo.removedPackage = childPkg.packageName;
14176                    childRes.removedInfo.isUpdate = true;
14177                    childPackageUpdated = true;
14178                }
14179            }
14180            if (!childPackageUpdated) {
14181                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14182                childRemovedRes.removedPackage = childPkg.packageName;
14183                childRemovedRes.isUpdate = false;
14184                childRemovedRes.dataRemoved = true;
14185                synchronized (mPackages) {
14186                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14187                    if (childPs != null) {
14188                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14189                    }
14190                }
14191                if (res.removedInfo.removedChildPackages == null) {
14192                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14193                }
14194                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14195            }
14196        }
14197
14198        boolean sysPkg = (isSystemApp(oldPackage));
14199        if (sysPkg) {
14200            // Set the system/privileged flags as needed
14201            final boolean privileged =
14202                    (oldPackage.applicationInfo.privateFlags
14203                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14204            final int systemPolicyFlags = policyFlags
14205                    | PackageParser.PARSE_IS_SYSTEM
14206                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14207
14208            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14209                    user, allUsers, installerPackageName, res);
14210        } else {
14211            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14212                    user, allUsers, installerPackageName, res);
14213        }
14214    }
14215
14216    public List<String> getPreviousCodePaths(String packageName) {
14217        final PackageSetting ps = mSettings.mPackages.get(packageName);
14218        final List<String> result = new ArrayList<String>();
14219        if (ps != null && ps.oldCodePaths != null) {
14220            result.addAll(ps.oldCodePaths);
14221        }
14222        return result;
14223    }
14224
14225    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14226            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14227            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14228        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14229                + deletedPackage);
14230
14231        String pkgName = deletedPackage.packageName;
14232        boolean deletedPkg = true;
14233        boolean addedPkg = false;
14234        boolean updatedSettings = false;
14235        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14236        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14237                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14238
14239        final long origUpdateTime = (pkg.mExtras != null)
14240                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14241
14242        // First delete the existing package while retaining the data directory
14243        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14244                res.removedInfo, true, pkg)) {
14245            // If the existing package wasn't successfully deleted
14246            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14247            deletedPkg = false;
14248        } else {
14249            // Successfully deleted the old package; proceed with replace.
14250
14251            // If deleted package lived in a container, give users a chance to
14252            // relinquish resources before killing.
14253            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14254                if (DEBUG_INSTALL) {
14255                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14256                }
14257                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14258                final ArrayList<String> pkgList = new ArrayList<String>(1);
14259                pkgList.add(deletedPackage.applicationInfo.packageName);
14260                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14261            }
14262
14263            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14264                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14265            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14266
14267            try {
14268                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14269                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14270                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14271
14272                // Update the in-memory copy of the previous code paths.
14273                PackageSetting ps = mSettings.mPackages.get(pkgName);
14274                if (!killApp) {
14275                    if (ps.oldCodePaths == null) {
14276                        ps.oldCodePaths = new ArraySet<>();
14277                    }
14278                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14279                    if (deletedPackage.splitCodePaths != null) {
14280                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14281                    }
14282                } else {
14283                    ps.oldCodePaths = null;
14284                }
14285                if (ps.childPackageNames != null) {
14286                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14287                        final String childPkgName = ps.childPackageNames.get(i);
14288                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14289                        childPs.oldCodePaths = ps.oldCodePaths;
14290                    }
14291                }
14292                prepareAppDataAfterInstallLIF(newPackage);
14293                addedPkg = true;
14294            } catch (PackageManagerException e) {
14295                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14296            }
14297        }
14298
14299        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14300            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14301
14302            // Revert all internal state mutations and added folders for the failed install
14303            if (addedPkg) {
14304                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14305                        res.removedInfo, true, null);
14306            }
14307
14308            // Restore the old package
14309            if (deletedPkg) {
14310                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14311                File restoreFile = new File(deletedPackage.codePath);
14312                // Parse old package
14313                boolean oldExternal = isExternal(deletedPackage);
14314                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14315                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14316                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14317                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14318                try {
14319                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14320                            null);
14321                } catch (PackageManagerException e) {
14322                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14323                            + e.getMessage());
14324                    return;
14325                }
14326
14327                synchronized (mPackages) {
14328                    // Ensure the installer package name up to date
14329                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14330
14331                    // Update permissions for restored package
14332                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14333
14334                    mSettings.writeLPr();
14335                }
14336
14337                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14338            }
14339        } else {
14340            synchronized (mPackages) {
14341                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14342                if (ps != null) {
14343                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14344                    if (res.removedInfo.removedChildPackages != null) {
14345                        final int childCount = res.removedInfo.removedChildPackages.size();
14346                        // Iterate in reverse as we may modify the collection
14347                        for (int i = childCount - 1; i >= 0; i--) {
14348                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14349                            if (res.addedChildPackages.containsKey(childPackageName)) {
14350                                res.removedInfo.removedChildPackages.removeAt(i);
14351                            } else {
14352                                PackageRemovedInfo childInfo = res.removedInfo
14353                                        .removedChildPackages.valueAt(i);
14354                                childInfo.removedForAllUsers = mPackages.get(
14355                                        childInfo.removedPackage) == null;
14356                            }
14357                        }
14358                    }
14359                }
14360            }
14361        }
14362    }
14363
14364    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14365            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14366            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14367        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14368                + ", old=" + deletedPackage);
14369
14370        final boolean disabledSystem;
14371
14372        // Remove existing system package
14373        removePackageLI(deletedPackage, true);
14374
14375        synchronized (mPackages) {
14376            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14377        }
14378        if (!disabledSystem) {
14379            // We didn't need to disable the .apk as a current system package,
14380            // which means we are replacing another update that is already
14381            // installed.  We need to make sure to delete the older one's .apk.
14382            res.removedInfo.args = createInstallArgsForExisting(0,
14383                    deletedPackage.applicationInfo.getCodePath(),
14384                    deletedPackage.applicationInfo.getResourcePath(),
14385                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14386        } else {
14387            res.removedInfo.args = null;
14388        }
14389
14390        // Successfully disabled the old package. Now proceed with re-installation
14391        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14392                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14393        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14394
14395        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14396        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14397                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14398
14399        PackageParser.Package newPackage = null;
14400        try {
14401            // Add the package to the internal data structures
14402            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14403
14404            // Set the update and install times
14405            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14406            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14407                    System.currentTimeMillis());
14408
14409            // Update the package dynamic state if succeeded
14410            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14411                // Now that the install succeeded make sure we remove data
14412                // directories for any child package the update removed.
14413                final int deletedChildCount = (deletedPackage.childPackages != null)
14414                        ? deletedPackage.childPackages.size() : 0;
14415                final int newChildCount = (newPackage.childPackages != null)
14416                        ? newPackage.childPackages.size() : 0;
14417                for (int i = 0; i < deletedChildCount; i++) {
14418                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14419                    boolean childPackageDeleted = true;
14420                    for (int j = 0; j < newChildCount; j++) {
14421                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14422                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14423                            childPackageDeleted = false;
14424                            break;
14425                        }
14426                    }
14427                    if (childPackageDeleted) {
14428                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14429                                deletedChildPkg.packageName);
14430                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14431                            PackageRemovedInfo removedChildRes = res.removedInfo
14432                                    .removedChildPackages.get(deletedChildPkg.packageName);
14433                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14434                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14435                        }
14436                    }
14437                }
14438
14439                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14440                prepareAppDataAfterInstallLIF(newPackage);
14441            }
14442        } catch (PackageManagerException e) {
14443            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14444            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14445        }
14446
14447        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14448            // Re installation failed. Restore old information
14449            // Remove new pkg information
14450            if (newPackage != null) {
14451                removeInstalledPackageLI(newPackage, true);
14452            }
14453            // Add back the old system package
14454            try {
14455                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14456            } catch (PackageManagerException e) {
14457                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14458            }
14459
14460            synchronized (mPackages) {
14461                if (disabledSystem) {
14462                    enableSystemPackageLPw(deletedPackage);
14463                }
14464
14465                // Ensure the installer package name up to date
14466                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14467
14468                // Update permissions for restored package
14469                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14470
14471                mSettings.writeLPr();
14472            }
14473
14474            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14475                    + " after failed upgrade");
14476        }
14477    }
14478
14479    /**
14480     * Checks whether the parent or any of the child packages have a change shared
14481     * user. For a package to be a valid update the shred users of the parent and
14482     * the children should match. We may later support changing child shared users.
14483     * @param oldPkg The updated package.
14484     * @param newPkg The update package.
14485     * @return The shared user that change between the versions.
14486     */
14487    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14488            PackageParser.Package newPkg) {
14489        // Check parent shared user
14490        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14491            return newPkg.packageName;
14492        }
14493        // Check child shared users
14494        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14495        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14496        for (int i = 0; i < newChildCount; i++) {
14497            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14498            // If this child was present, did it have the same shared user?
14499            for (int j = 0; j < oldChildCount; j++) {
14500                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14501                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14502                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14503                    return newChildPkg.packageName;
14504                }
14505            }
14506        }
14507        return null;
14508    }
14509
14510    private void removeNativeBinariesLI(PackageSetting ps) {
14511        // Remove the lib path for the parent package
14512        if (ps != null) {
14513            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14514            // Remove the lib path for the child packages
14515            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14516            for (int i = 0; i < childCount; i++) {
14517                PackageSetting childPs = null;
14518                synchronized (mPackages) {
14519                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14520                }
14521                if (childPs != null) {
14522                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14523                            .legacyNativeLibraryPathString);
14524                }
14525            }
14526        }
14527    }
14528
14529    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14530        // Enable the parent package
14531        mSettings.enableSystemPackageLPw(pkg.packageName);
14532        // Enable the child packages
14533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14534        for (int i = 0; i < childCount; i++) {
14535            PackageParser.Package childPkg = pkg.childPackages.get(i);
14536            mSettings.enableSystemPackageLPw(childPkg.packageName);
14537        }
14538    }
14539
14540    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14541            PackageParser.Package newPkg) {
14542        // Disable the parent package (parent always replaced)
14543        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14544        // Disable the child packages
14545        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14546        for (int i = 0; i < childCount; i++) {
14547            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14548            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14549            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14550        }
14551        return disabled;
14552    }
14553
14554    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14555            String installerPackageName) {
14556        // Enable the parent package
14557        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14558        // Enable the child packages
14559        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14560        for (int i = 0; i < childCount; i++) {
14561            PackageParser.Package childPkg = pkg.childPackages.get(i);
14562            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14563        }
14564    }
14565
14566    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14567        // Collect all used permissions in the UID
14568        ArraySet<String> usedPermissions = new ArraySet<>();
14569        final int packageCount = su.packages.size();
14570        for (int i = 0; i < packageCount; i++) {
14571            PackageSetting ps = su.packages.valueAt(i);
14572            if (ps.pkg == null) {
14573                continue;
14574            }
14575            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14576            for (int j = 0; j < requestedPermCount; j++) {
14577                String permission = ps.pkg.requestedPermissions.get(j);
14578                BasePermission bp = mSettings.mPermissions.get(permission);
14579                if (bp != null) {
14580                    usedPermissions.add(permission);
14581                }
14582            }
14583        }
14584
14585        PermissionsState permissionsState = su.getPermissionsState();
14586        // Prune install permissions
14587        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14588        final int installPermCount = installPermStates.size();
14589        for (int i = installPermCount - 1; i >= 0;  i--) {
14590            PermissionState permissionState = installPermStates.get(i);
14591            if (!usedPermissions.contains(permissionState.getName())) {
14592                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14593                if (bp != null) {
14594                    permissionsState.revokeInstallPermission(bp);
14595                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14596                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14597                }
14598            }
14599        }
14600
14601        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14602
14603        // Prune runtime permissions
14604        for (int userId : allUserIds) {
14605            List<PermissionState> runtimePermStates = permissionsState
14606                    .getRuntimePermissionStates(userId);
14607            final int runtimePermCount = runtimePermStates.size();
14608            for (int i = runtimePermCount - 1; i >= 0; i--) {
14609                PermissionState permissionState = runtimePermStates.get(i);
14610                if (!usedPermissions.contains(permissionState.getName())) {
14611                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14612                    if (bp != null) {
14613                        permissionsState.revokeRuntimePermission(bp, userId);
14614                        permissionsState.updatePermissionFlags(bp, userId,
14615                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14616                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14617                                runtimePermissionChangedUserIds, userId);
14618                    }
14619                }
14620            }
14621        }
14622
14623        return runtimePermissionChangedUserIds;
14624    }
14625
14626    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14627            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14628        // Update the parent package setting
14629        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14630                res, user);
14631        // Update the child packages setting
14632        final int childCount = (newPackage.childPackages != null)
14633                ? newPackage.childPackages.size() : 0;
14634        for (int i = 0; i < childCount; i++) {
14635            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14636            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14637            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14638                    childRes.origUsers, childRes, user);
14639        }
14640    }
14641
14642    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14643            String installerPackageName, int[] allUsers, int[] installedForUsers,
14644            PackageInstalledInfo res, UserHandle user) {
14645        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14646
14647        String pkgName = newPackage.packageName;
14648        synchronized (mPackages) {
14649            //write settings. the installStatus will be incomplete at this stage.
14650            //note that the new package setting would have already been
14651            //added to mPackages. It hasn't been persisted yet.
14652            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14654            mSettings.writeLPr();
14655            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14656        }
14657
14658        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14659        synchronized (mPackages) {
14660            updatePermissionsLPw(newPackage.packageName, newPackage,
14661                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14662                            ? UPDATE_PERMISSIONS_ALL : 0));
14663            // For system-bundled packages, we assume that installing an upgraded version
14664            // of the package implies that the user actually wants to run that new code,
14665            // so we enable the package.
14666            PackageSetting ps = mSettings.mPackages.get(pkgName);
14667            final int userId = user.getIdentifier();
14668            if (ps != null) {
14669                if (isSystemApp(newPackage)) {
14670                    if (DEBUG_INSTALL) {
14671                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14672                    }
14673                    // Enable system package for requested users
14674                    if (res.origUsers != null) {
14675                        for (int origUserId : res.origUsers) {
14676                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14677                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14678                                        origUserId, installerPackageName);
14679                            }
14680                        }
14681                    }
14682                    // Also convey the prior install/uninstall state
14683                    if (allUsers != null && installedForUsers != null) {
14684                        for (int currentUserId : allUsers) {
14685                            final boolean installed = ArrayUtils.contains(
14686                                    installedForUsers, currentUserId);
14687                            if (DEBUG_INSTALL) {
14688                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14689                            }
14690                            ps.setInstalled(installed, currentUserId);
14691                        }
14692                        // these install state changes will be persisted in the
14693                        // upcoming call to mSettings.writeLPr().
14694                    }
14695                }
14696                // It's implied that when a user requests installation, they want the app to be
14697                // installed and enabled.
14698                if (userId != UserHandle.USER_ALL) {
14699                    ps.setInstalled(true, userId);
14700                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14701                }
14702            }
14703            res.name = pkgName;
14704            res.uid = newPackage.applicationInfo.uid;
14705            res.pkg = newPackage;
14706            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14707            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14708            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14709            //to update install status
14710            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14711            mSettings.writeLPr();
14712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14713        }
14714
14715        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14716    }
14717
14718    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14719        try {
14720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14721            installPackageLI(args, res);
14722        } finally {
14723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14724        }
14725    }
14726
14727    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14728        final int installFlags = args.installFlags;
14729        final String installerPackageName = args.installerPackageName;
14730        final String volumeUuid = args.volumeUuid;
14731        final File tmpPackageFile = new File(args.getCodePath());
14732        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14733        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14734                || (args.volumeUuid != null));
14735        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14736        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14737        boolean replace = false;
14738        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14739        if (args.move != null) {
14740            // moving a complete application; perform an initial scan on the new install location
14741            scanFlags |= SCAN_INITIAL;
14742        }
14743        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14744            scanFlags |= SCAN_DONT_KILL_APP;
14745        }
14746
14747        // Result object to be returned
14748        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14749
14750        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14751
14752        // Sanity check
14753        if (ephemeral && (forwardLocked || onExternal)) {
14754            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14755                    + " external=" + onExternal);
14756            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14757            return;
14758        }
14759
14760        // Retrieve PackageSettings and parse package
14761        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14762                | PackageParser.PARSE_ENFORCE_CODE
14763                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14764                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14765                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14766                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14767        PackageParser pp = new PackageParser();
14768        pp.setSeparateProcesses(mSeparateProcesses);
14769        pp.setDisplayMetrics(mMetrics);
14770
14771        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14772        final PackageParser.Package pkg;
14773        try {
14774            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14775        } catch (PackageParserException e) {
14776            res.setError("Failed parse during installPackageLI", e);
14777            return;
14778        } finally {
14779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14780        }
14781
14782        // If we are installing a clustered package add results for the children
14783        if (pkg.childPackages != null) {
14784            synchronized (mPackages) {
14785                final int childCount = pkg.childPackages.size();
14786                for (int i = 0; i < childCount; i++) {
14787                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14788                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14789                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14790                    childRes.pkg = childPkg;
14791                    childRes.name = childPkg.packageName;
14792                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14793                    if (childPs != null) {
14794                        childRes.origUsers = childPs.queryInstalledUsers(
14795                                sUserManager.getUserIds(), true);
14796                    }
14797                    if ((mPackages.containsKey(childPkg.packageName))) {
14798                        childRes.removedInfo = new PackageRemovedInfo();
14799                        childRes.removedInfo.removedPackage = childPkg.packageName;
14800                    }
14801                    if (res.addedChildPackages == null) {
14802                        res.addedChildPackages = new ArrayMap<>();
14803                    }
14804                    res.addedChildPackages.put(childPkg.packageName, childRes);
14805                }
14806            }
14807        }
14808
14809        // If package doesn't declare API override, mark that we have an install
14810        // time CPU ABI override.
14811        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14812            pkg.cpuAbiOverride = args.abiOverride;
14813        }
14814
14815        String pkgName = res.name = pkg.packageName;
14816        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14817            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14818                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14819                return;
14820            }
14821        }
14822
14823        try {
14824            // either use what we've been given or parse directly from the APK
14825            if (args.certificates != null) {
14826                try {
14827                    PackageParser.populateCertificates(pkg, args.certificates);
14828                } catch (PackageParserException e) {
14829                    // there was something wrong with the certificates we were given;
14830                    // try to pull them from the APK
14831                    PackageParser.collectCertificates(pkg, parseFlags);
14832                }
14833            } else {
14834                PackageParser.collectCertificates(pkg, parseFlags);
14835            }
14836        } catch (PackageParserException e) {
14837            res.setError("Failed collect during installPackageLI", e);
14838            return;
14839        }
14840
14841        // Get rid of all references to package scan path via parser.
14842        pp = null;
14843        String oldCodePath = null;
14844        boolean systemApp = false;
14845        synchronized (mPackages) {
14846            // Check if installing already existing package
14847            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14848                String oldName = mSettings.mRenamedPackages.get(pkgName);
14849                if (pkg.mOriginalPackages != null
14850                        && pkg.mOriginalPackages.contains(oldName)
14851                        && mPackages.containsKey(oldName)) {
14852                    // This package is derived from an original package,
14853                    // and this device has been updating from that original
14854                    // name.  We must continue using the original name, so
14855                    // rename the new package here.
14856                    pkg.setPackageName(oldName);
14857                    pkgName = pkg.packageName;
14858                    replace = true;
14859                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14860                            + oldName + " pkgName=" + pkgName);
14861                } else if (mPackages.containsKey(pkgName)) {
14862                    // This package, under its official name, already exists
14863                    // on the device; we should replace it.
14864                    replace = true;
14865                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14866                }
14867
14868                // Child packages are installed through the parent package
14869                if (pkg.parentPackage != null) {
14870                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14871                            "Package " + pkg.packageName + " is child of package "
14872                                    + pkg.parentPackage.parentPackage + ". Child packages "
14873                                    + "can be updated only through the parent package.");
14874                    return;
14875                }
14876
14877                if (replace) {
14878                    // Prevent apps opting out from runtime permissions
14879                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14880                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14881                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14882                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14883                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14884                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14885                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14886                                        + " doesn't support runtime permissions but the old"
14887                                        + " target SDK " + oldTargetSdk + " does.");
14888                        return;
14889                    }
14890
14891                    // Prevent installing of child packages
14892                    if (oldPackage.parentPackage != null) {
14893                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14894                                "Package " + pkg.packageName + " is child of package "
14895                                        + oldPackage.parentPackage + ". Child packages "
14896                                        + "can be updated only through the parent package.");
14897                        return;
14898                    }
14899                }
14900            }
14901
14902            PackageSetting ps = mSettings.mPackages.get(pkgName);
14903            if (ps != null) {
14904                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14905
14906                // Quick sanity check that we're signed correctly if updating;
14907                // we'll check this again later when scanning, but we want to
14908                // bail early here before tripping over redefined permissions.
14909                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14910                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14911                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14912                                + pkg.packageName + " upgrade keys do not match the "
14913                                + "previously installed version");
14914                        return;
14915                    }
14916                } else {
14917                    try {
14918                        verifySignaturesLP(ps, pkg);
14919                    } catch (PackageManagerException e) {
14920                        res.setError(e.error, e.getMessage());
14921                        return;
14922                    }
14923                }
14924
14925                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14926                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14927                    systemApp = (ps.pkg.applicationInfo.flags &
14928                            ApplicationInfo.FLAG_SYSTEM) != 0;
14929                }
14930                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14931            }
14932
14933            // Check whether the newly-scanned package wants to define an already-defined perm
14934            int N = pkg.permissions.size();
14935            for (int i = N-1; i >= 0; i--) {
14936                PackageParser.Permission perm = pkg.permissions.get(i);
14937                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14938                if (bp != null) {
14939                    // If the defining package is signed with our cert, it's okay.  This
14940                    // also includes the "updating the same package" case, of course.
14941                    // "updating same package" could also involve key-rotation.
14942                    final boolean sigsOk;
14943                    if (bp.sourcePackage.equals(pkg.packageName)
14944                            && (bp.packageSetting instanceof PackageSetting)
14945                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14946                                    scanFlags))) {
14947                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14948                    } else {
14949                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14950                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14951                    }
14952                    if (!sigsOk) {
14953                        // If the owning package is the system itself, we log but allow
14954                        // install to proceed; we fail the install on all other permission
14955                        // redefinitions.
14956                        if (!bp.sourcePackage.equals("android")) {
14957                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14958                                    + pkg.packageName + " attempting to redeclare permission "
14959                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14960                            res.origPermission = perm.info.name;
14961                            res.origPackage = bp.sourcePackage;
14962                            return;
14963                        } else {
14964                            Slog.w(TAG, "Package " + pkg.packageName
14965                                    + " attempting to redeclare system permission "
14966                                    + perm.info.name + "; ignoring new declaration");
14967                            pkg.permissions.remove(i);
14968                        }
14969                    }
14970                }
14971            }
14972        }
14973
14974        if (systemApp) {
14975            if (onExternal) {
14976                // Abort update; system app can't be replaced with app on sdcard
14977                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14978                        "Cannot install updates to system apps on sdcard");
14979                return;
14980            } else if (ephemeral) {
14981                // Abort update; system app can't be replaced with an ephemeral app
14982                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14983                        "Cannot update a system app with an ephemeral app");
14984                return;
14985            }
14986        }
14987
14988        if (args.move != null) {
14989            // We did an in-place move, so dex is ready to roll
14990            scanFlags |= SCAN_NO_DEX;
14991            scanFlags |= SCAN_MOVE;
14992
14993            synchronized (mPackages) {
14994                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14995                if (ps == null) {
14996                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14997                            "Missing settings for moved package " + pkgName);
14998                }
14999
15000                // We moved the entire application as-is, so bring over the
15001                // previously derived ABI information.
15002                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15003                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15004            }
15005
15006        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15007            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15008            scanFlags |= SCAN_NO_DEX;
15009
15010            try {
15011                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15012                    args.abiOverride : pkg.cpuAbiOverride);
15013                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15014                        true /* extract libs */);
15015            } catch (PackageManagerException pme) {
15016                Slog.e(TAG, "Error deriving application ABI", pme);
15017                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15018                return;
15019            }
15020
15021            // Shared libraries for the package need to be updated.
15022            synchronized (mPackages) {
15023                try {
15024                    updateSharedLibrariesLPw(pkg, null);
15025                } catch (PackageManagerException e) {
15026                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15027                }
15028            }
15029            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15030            // Do not run PackageDexOptimizer through the local performDexOpt
15031            // method because `pkg` may not be in `mPackages` yet.
15032            //
15033            // Also, don't fail application installs if the dexopt step fails.
15034            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15035                    null /* instructionSets */, false /* checkProfiles */,
15036                    getCompilerFilterForReason(REASON_INSTALL),
15037                    getOrCreateCompilerPackageStats(pkg));
15038            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15039
15040            // Notify BackgroundDexOptService that the package has been changed.
15041            // If this is an update of a package which used to fail to compile,
15042            // BDOS will remove it from its blacklist.
15043            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15044        }
15045
15046        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15047            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15048            return;
15049        }
15050
15051        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15052
15053        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15054                "installPackageLI")) {
15055            if (replace) {
15056                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15057                        installerPackageName, res);
15058            } else {
15059                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15060                        args.user, installerPackageName, volumeUuid, res);
15061            }
15062        }
15063        synchronized (mPackages) {
15064            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15065            if (ps != null) {
15066                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15067            }
15068
15069            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15070            for (int i = 0; i < childCount; i++) {
15071                PackageParser.Package childPkg = pkg.childPackages.get(i);
15072                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15073                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15074                if (childPs != null) {
15075                    childRes.newUsers = childPs.queryInstalledUsers(
15076                            sUserManager.getUserIds(), true);
15077                }
15078            }
15079        }
15080    }
15081
15082    private void startIntentFilterVerifications(int userId, boolean replacing,
15083            PackageParser.Package pkg) {
15084        if (mIntentFilterVerifierComponent == null) {
15085            Slog.w(TAG, "No IntentFilter verification will not be done as "
15086                    + "there is no IntentFilterVerifier available!");
15087            return;
15088        }
15089
15090        final int verifierUid = getPackageUid(
15091                mIntentFilterVerifierComponent.getPackageName(),
15092                MATCH_DEBUG_TRIAGED_MISSING,
15093                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15094
15095        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15096        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15097        mHandler.sendMessage(msg);
15098
15099        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15100        for (int i = 0; i < childCount; i++) {
15101            PackageParser.Package childPkg = pkg.childPackages.get(i);
15102            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15103            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15104            mHandler.sendMessage(msg);
15105        }
15106    }
15107
15108    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15109            PackageParser.Package pkg) {
15110        int size = pkg.activities.size();
15111        if (size == 0) {
15112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15113                    "No activity, so no need to verify any IntentFilter!");
15114            return;
15115        }
15116
15117        final boolean hasDomainURLs = hasDomainURLs(pkg);
15118        if (!hasDomainURLs) {
15119            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15120                    "No domain URLs, so no need to verify any IntentFilter!");
15121            return;
15122        }
15123
15124        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15125                + " if any IntentFilter from the " + size
15126                + " Activities needs verification ...");
15127
15128        int count = 0;
15129        final String packageName = pkg.packageName;
15130
15131        synchronized (mPackages) {
15132            // If this is a new install and we see that we've already run verification for this
15133            // package, we have nothing to do: it means the state was restored from backup.
15134            if (!replacing) {
15135                IntentFilterVerificationInfo ivi =
15136                        mSettings.getIntentFilterVerificationLPr(packageName);
15137                if (ivi != null) {
15138                    if (DEBUG_DOMAIN_VERIFICATION) {
15139                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15140                                + ivi.getStatusString());
15141                    }
15142                    return;
15143                }
15144            }
15145
15146            // If any filters need to be verified, then all need to be.
15147            boolean needToVerify = false;
15148            for (PackageParser.Activity a : pkg.activities) {
15149                for (ActivityIntentInfo filter : a.intents) {
15150                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15151                        if (DEBUG_DOMAIN_VERIFICATION) {
15152                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15153                        }
15154                        needToVerify = true;
15155                        break;
15156                    }
15157                }
15158            }
15159
15160            if (needToVerify) {
15161                final int verificationId = mIntentFilterVerificationToken++;
15162                for (PackageParser.Activity a : pkg.activities) {
15163                    for (ActivityIntentInfo filter : a.intents) {
15164                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15165                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15166                                    "Verification needed for IntentFilter:" + filter.toString());
15167                            mIntentFilterVerifier.addOneIntentFilterVerification(
15168                                    verifierUid, userId, verificationId, filter, packageName);
15169                            count++;
15170                        }
15171                    }
15172                }
15173            }
15174        }
15175
15176        if (count > 0) {
15177            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15178                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15179                    +  " for userId:" + userId);
15180            mIntentFilterVerifier.startVerifications(userId);
15181        } else {
15182            if (DEBUG_DOMAIN_VERIFICATION) {
15183                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15184            }
15185        }
15186    }
15187
15188    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15189        final ComponentName cn  = filter.activity.getComponentName();
15190        final String packageName = cn.getPackageName();
15191
15192        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15193                packageName);
15194        if (ivi == null) {
15195            return true;
15196        }
15197        int status = ivi.getStatus();
15198        switch (status) {
15199            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15200            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15201                return true;
15202
15203            default:
15204                // Nothing to do
15205                return false;
15206        }
15207    }
15208
15209    private static boolean isMultiArch(ApplicationInfo info) {
15210        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15211    }
15212
15213    private static boolean isExternal(PackageParser.Package pkg) {
15214        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15215    }
15216
15217    private static boolean isExternal(PackageSetting ps) {
15218        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15219    }
15220
15221    private static boolean isEphemeral(PackageParser.Package pkg) {
15222        return pkg.applicationInfo.isEphemeralApp();
15223    }
15224
15225    private static boolean isEphemeral(PackageSetting ps) {
15226        return ps.pkg != null && isEphemeral(ps.pkg);
15227    }
15228
15229    private static boolean isSystemApp(PackageParser.Package pkg) {
15230        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15231    }
15232
15233    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15234        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15235    }
15236
15237    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15238        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15239    }
15240
15241    private static boolean isSystemApp(PackageSetting ps) {
15242        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15243    }
15244
15245    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15246        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15247    }
15248
15249    private int packageFlagsToInstallFlags(PackageSetting ps) {
15250        int installFlags = 0;
15251        if (isEphemeral(ps)) {
15252            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15253        }
15254        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15255            // This existing package was an external ASEC install when we have
15256            // the external flag without a UUID
15257            installFlags |= PackageManager.INSTALL_EXTERNAL;
15258        }
15259        if (ps.isForwardLocked()) {
15260            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15261        }
15262        return installFlags;
15263    }
15264
15265    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15266        if (isExternal(pkg)) {
15267            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15268                return StorageManager.UUID_PRIMARY_PHYSICAL;
15269            } else {
15270                return pkg.volumeUuid;
15271            }
15272        } else {
15273            return StorageManager.UUID_PRIVATE_INTERNAL;
15274        }
15275    }
15276
15277    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15278        if (isExternal(pkg)) {
15279            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15280                return mSettings.getExternalVersion();
15281            } else {
15282                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15283            }
15284        } else {
15285            return mSettings.getInternalVersion();
15286        }
15287    }
15288
15289    private void deleteTempPackageFiles() {
15290        final FilenameFilter filter = new FilenameFilter() {
15291            public boolean accept(File dir, String name) {
15292                return name.startsWith("vmdl") && name.endsWith(".tmp");
15293            }
15294        };
15295        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15296            file.delete();
15297        }
15298    }
15299
15300    @Override
15301    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15302            int flags) {
15303        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15304                flags);
15305    }
15306
15307    @Override
15308    public void deletePackage(final String packageName,
15309            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15310        mContext.enforceCallingOrSelfPermission(
15311                android.Manifest.permission.DELETE_PACKAGES, null);
15312        Preconditions.checkNotNull(packageName);
15313        Preconditions.checkNotNull(observer);
15314        final int uid = Binder.getCallingUid();
15315        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15316        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15317        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15318            mContext.enforceCallingOrSelfPermission(
15319                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15320                    "deletePackage for user " + userId);
15321        }
15322
15323        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15324            try {
15325                observer.onPackageDeleted(packageName,
15326                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15327            } catch (RemoteException re) {
15328            }
15329            return;
15330        }
15331
15332        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15333            try {
15334                observer.onPackageDeleted(packageName,
15335                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15336            } catch (RemoteException re) {
15337            }
15338            return;
15339        }
15340
15341        if (DEBUG_REMOVE) {
15342            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15343                    + " deleteAllUsers: " + deleteAllUsers );
15344        }
15345        // Queue up an async operation since the package deletion may take a little while.
15346        mHandler.post(new Runnable() {
15347            public void run() {
15348                mHandler.removeCallbacks(this);
15349                int returnCode;
15350                if (!deleteAllUsers) {
15351                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15352                } else {
15353                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15354                    // If nobody is blocking uninstall, proceed with delete for all users
15355                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15356                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15357                    } else {
15358                        // Otherwise uninstall individually for users with blockUninstalls=false
15359                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15360                        for (int userId : users) {
15361                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15362                                returnCode = deletePackageX(packageName, userId, userFlags);
15363                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15364                                    Slog.w(TAG, "Package delete failed for user " + userId
15365                                            + ", returnCode " + returnCode);
15366                                }
15367                            }
15368                        }
15369                        // The app has only been marked uninstalled for certain users.
15370                        // We still need to report that delete was blocked
15371                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15372                    }
15373                }
15374                try {
15375                    observer.onPackageDeleted(packageName, returnCode, null);
15376                } catch (RemoteException e) {
15377                    Log.i(TAG, "Observer no longer exists.");
15378                } //end catch
15379            } //end run
15380        });
15381    }
15382
15383    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15384        int[] result = EMPTY_INT_ARRAY;
15385        for (int userId : userIds) {
15386            if (getBlockUninstallForUser(packageName, userId)) {
15387                result = ArrayUtils.appendInt(result, userId);
15388            }
15389        }
15390        return result;
15391    }
15392
15393    @Override
15394    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15395        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15396    }
15397
15398    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15399        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15400                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15401        try {
15402            if (dpm != null) {
15403                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15404                        /* callingUserOnly =*/ false);
15405                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15406                        : deviceOwnerComponentName.getPackageName();
15407                // Does the package contains the device owner?
15408                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15409                // this check is probably not needed, since DO should be registered as a device
15410                // admin on some user too. (Original bug for this: b/17657954)
15411                if (packageName.equals(deviceOwnerPackageName)) {
15412                    return true;
15413                }
15414                // Does it contain a device admin for any user?
15415                int[] users;
15416                if (userId == UserHandle.USER_ALL) {
15417                    users = sUserManager.getUserIds();
15418                } else {
15419                    users = new int[]{userId};
15420                }
15421                for (int i = 0; i < users.length; ++i) {
15422                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15423                        return true;
15424                    }
15425                }
15426            }
15427        } catch (RemoteException e) {
15428        }
15429        return false;
15430    }
15431
15432    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15433        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15434    }
15435
15436    /**
15437     *  This method is an internal method that could be get invoked either
15438     *  to delete an installed package or to clean up a failed installation.
15439     *  After deleting an installed package, a broadcast is sent to notify any
15440     *  listeners that the package has been removed. For cleaning up a failed
15441     *  installation, the broadcast is not necessary since the package's
15442     *  installation wouldn't have sent the initial broadcast either
15443     *  The key steps in deleting a package are
15444     *  deleting the package information in internal structures like mPackages,
15445     *  deleting the packages base directories through installd
15446     *  updating mSettings to reflect current status
15447     *  persisting settings for later use
15448     *  sending a broadcast if necessary
15449     */
15450    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15451        final PackageRemovedInfo info = new PackageRemovedInfo();
15452        final boolean res;
15453
15454        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15455                ? UserHandle.USER_ALL : userId;
15456
15457        if (isPackageDeviceAdmin(packageName, removeUser)) {
15458            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15459            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15460        }
15461
15462        PackageSetting uninstalledPs = null;
15463
15464        // for the uninstall-updates case and restricted profiles, remember the per-
15465        // user handle installed state
15466        int[] allUsers;
15467        synchronized (mPackages) {
15468            uninstalledPs = mSettings.mPackages.get(packageName);
15469            if (uninstalledPs == null) {
15470                Slog.w(TAG, "Not removing non-existent package " + packageName);
15471                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15472            }
15473            allUsers = sUserManager.getUserIds();
15474            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15475        }
15476
15477        final int freezeUser;
15478        if (isUpdatedSystemApp(uninstalledPs)
15479                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15480            // We're downgrading a system app, which will apply to all users, so
15481            // freeze them all during the downgrade
15482            freezeUser = UserHandle.USER_ALL;
15483        } else {
15484            freezeUser = removeUser;
15485        }
15486
15487        synchronized (mInstallLock) {
15488            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15489            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15490                    deleteFlags, "deletePackageX")) {
15491                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15492                        deleteFlags | REMOVE_CHATTY, info, true, null);
15493            }
15494            synchronized (mPackages) {
15495                if (res) {
15496                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15497                }
15498            }
15499        }
15500
15501        if (res) {
15502            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15503            info.sendPackageRemovedBroadcasts(killApp);
15504            info.sendSystemPackageUpdatedBroadcasts();
15505            info.sendSystemPackageAppearedBroadcasts();
15506        }
15507        // Force a gc here.
15508        Runtime.getRuntime().gc();
15509        // Delete the resources here after sending the broadcast to let
15510        // other processes clean up before deleting resources.
15511        if (info.args != null) {
15512            synchronized (mInstallLock) {
15513                info.args.doPostDeleteLI(true);
15514            }
15515        }
15516
15517        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15518    }
15519
15520    class PackageRemovedInfo {
15521        String removedPackage;
15522        int uid = -1;
15523        int removedAppId = -1;
15524        int[] origUsers;
15525        int[] removedUsers = null;
15526        boolean isRemovedPackageSystemUpdate = false;
15527        boolean isUpdate;
15528        boolean dataRemoved;
15529        boolean removedForAllUsers;
15530        // Clean up resources deleted packages.
15531        InstallArgs args = null;
15532        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15533        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15534
15535        void sendPackageRemovedBroadcasts(boolean killApp) {
15536            sendPackageRemovedBroadcastInternal(killApp);
15537            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15538            for (int i = 0; i < childCount; i++) {
15539                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15540                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15541            }
15542        }
15543
15544        void sendSystemPackageUpdatedBroadcasts() {
15545            if (isRemovedPackageSystemUpdate) {
15546                sendSystemPackageUpdatedBroadcastsInternal();
15547                final int childCount = (removedChildPackages != null)
15548                        ? removedChildPackages.size() : 0;
15549                for (int i = 0; i < childCount; i++) {
15550                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15551                    if (childInfo.isRemovedPackageSystemUpdate) {
15552                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15553                    }
15554                }
15555            }
15556        }
15557
15558        void sendSystemPackageAppearedBroadcasts() {
15559            final int packageCount = (appearedChildPackages != null)
15560                    ? appearedChildPackages.size() : 0;
15561            for (int i = 0; i < packageCount; i++) {
15562                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15563                for (int userId : installedInfo.newUsers) {
15564                    sendPackageAddedForUser(installedInfo.name, true,
15565                            UserHandle.getAppId(installedInfo.uid), userId);
15566                }
15567            }
15568        }
15569
15570        private void sendSystemPackageUpdatedBroadcastsInternal() {
15571            Bundle extras = new Bundle(2);
15572            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15573            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15574            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15575                    extras, 0, null, null, null);
15576            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15577                    extras, 0, null, null, null);
15578            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15579                    null, 0, removedPackage, null, null);
15580        }
15581
15582        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15583            Bundle extras = new Bundle(2);
15584            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15585            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15586            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15587            if (isUpdate || isRemovedPackageSystemUpdate) {
15588                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15589            }
15590            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15591            if (removedPackage != null) {
15592                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15593                        extras, 0, null, null, removedUsers);
15594                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15595                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15596                            removedPackage, extras, 0, null, null, removedUsers);
15597                }
15598            }
15599            if (removedAppId >= 0) {
15600                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15601                        removedUsers);
15602            }
15603        }
15604    }
15605
15606    /*
15607     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15608     * flag is not set, the data directory is removed as well.
15609     * make sure this flag is set for partially installed apps. If not its meaningless to
15610     * delete a partially installed application.
15611     */
15612    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15613            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15614        String packageName = ps.name;
15615        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15616        // Retrieve object to delete permissions for shared user later on
15617        final PackageParser.Package deletedPkg;
15618        final PackageSetting deletedPs;
15619        // reader
15620        synchronized (mPackages) {
15621            deletedPkg = mPackages.get(packageName);
15622            deletedPs = mSettings.mPackages.get(packageName);
15623            if (outInfo != null) {
15624                outInfo.removedPackage = packageName;
15625                outInfo.removedUsers = deletedPs != null
15626                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15627                        : null;
15628            }
15629        }
15630
15631        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15632
15633        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15634            final PackageParser.Package resolvedPkg;
15635            if (deletedPkg != null) {
15636                resolvedPkg = deletedPkg;
15637            } else {
15638                // We don't have a parsed package when it lives on an ejected
15639                // adopted storage device, so fake something together
15640                resolvedPkg = new PackageParser.Package(ps.name);
15641                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15642            }
15643            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15644                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15645            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15646            if (outInfo != null) {
15647                outInfo.dataRemoved = true;
15648            }
15649            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15650        }
15651
15652        // writer
15653        synchronized (mPackages) {
15654            if (deletedPs != null) {
15655                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15656                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15657                    clearDefaultBrowserIfNeeded(packageName);
15658                    if (outInfo != null) {
15659                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15660                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15661                    }
15662                    updatePermissionsLPw(deletedPs.name, null, 0);
15663                    if (deletedPs.sharedUser != null) {
15664                        // Remove permissions associated with package. Since runtime
15665                        // permissions are per user we have to kill the removed package
15666                        // or packages running under the shared user of the removed
15667                        // package if revoking the permissions requested only by the removed
15668                        // package is successful and this causes a change in gids.
15669                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15670                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15671                                    userId);
15672                            if (userIdToKill == UserHandle.USER_ALL
15673                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15674                                // If gids changed for this user, kill all affected packages.
15675                                mHandler.post(new Runnable() {
15676                                    @Override
15677                                    public void run() {
15678                                        // This has to happen with no lock held.
15679                                        killApplication(deletedPs.name, deletedPs.appId,
15680                                                KILL_APP_REASON_GIDS_CHANGED);
15681                                    }
15682                                });
15683                                break;
15684                            }
15685                        }
15686                    }
15687                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15688                }
15689                // make sure to preserve per-user disabled state if this removal was just
15690                // a downgrade of a system app to the factory package
15691                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15692                    if (DEBUG_REMOVE) {
15693                        Slog.d(TAG, "Propagating install state across downgrade");
15694                    }
15695                    for (int userId : allUserHandles) {
15696                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15697                        if (DEBUG_REMOVE) {
15698                            Slog.d(TAG, "    user " + userId + " => " + installed);
15699                        }
15700                        ps.setInstalled(installed, userId);
15701                    }
15702                }
15703            }
15704            // can downgrade to reader
15705            if (writeSettings) {
15706                // Save settings now
15707                mSettings.writeLPr();
15708            }
15709        }
15710        if (outInfo != null) {
15711            // A user ID was deleted here. Go through all users and remove it
15712            // from KeyStore.
15713            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15714        }
15715    }
15716
15717    static boolean locationIsPrivileged(File path) {
15718        try {
15719            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15720                    .getCanonicalPath();
15721            return path.getCanonicalPath().startsWith(privilegedAppDir);
15722        } catch (IOException e) {
15723            Slog.e(TAG, "Unable to access code path " + path);
15724        }
15725        return false;
15726    }
15727
15728    /*
15729     * Tries to delete system package.
15730     */
15731    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15732            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15733            boolean writeSettings) {
15734        if (deletedPs.parentPackageName != null) {
15735            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15736            return false;
15737        }
15738
15739        final boolean applyUserRestrictions
15740                = (allUserHandles != null) && (outInfo.origUsers != null);
15741        final PackageSetting disabledPs;
15742        // Confirm if the system package has been updated
15743        // An updated system app can be deleted. This will also have to restore
15744        // the system pkg from system partition
15745        // reader
15746        synchronized (mPackages) {
15747            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15748        }
15749
15750        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15751                + " disabledPs=" + disabledPs);
15752
15753        if (disabledPs == null) {
15754            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15755            return false;
15756        } else if (DEBUG_REMOVE) {
15757            Slog.d(TAG, "Deleting system pkg from data partition");
15758        }
15759
15760        if (DEBUG_REMOVE) {
15761            if (applyUserRestrictions) {
15762                Slog.d(TAG, "Remembering install states:");
15763                for (int userId : allUserHandles) {
15764                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15765                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15766                }
15767            }
15768        }
15769
15770        // Delete the updated package
15771        outInfo.isRemovedPackageSystemUpdate = true;
15772        if (outInfo.removedChildPackages != null) {
15773            final int childCount = (deletedPs.childPackageNames != null)
15774                    ? deletedPs.childPackageNames.size() : 0;
15775            for (int i = 0; i < childCount; i++) {
15776                String childPackageName = deletedPs.childPackageNames.get(i);
15777                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15778                        .contains(childPackageName)) {
15779                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15780                            childPackageName);
15781                    if (childInfo != null) {
15782                        childInfo.isRemovedPackageSystemUpdate = true;
15783                    }
15784                }
15785            }
15786        }
15787
15788        if (disabledPs.versionCode < deletedPs.versionCode) {
15789            // Delete data for downgrades
15790            flags &= ~PackageManager.DELETE_KEEP_DATA;
15791        } else {
15792            // Preserve data by setting flag
15793            flags |= PackageManager.DELETE_KEEP_DATA;
15794        }
15795
15796        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15797                outInfo, writeSettings, disabledPs.pkg);
15798        if (!ret) {
15799            return false;
15800        }
15801
15802        // writer
15803        synchronized (mPackages) {
15804            // Reinstate the old system package
15805            enableSystemPackageLPw(disabledPs.pkg);
15806            // Remove any native libraries from the upgraded package.
15807            removeNativeBinariesLI(deletedPs);
15808        }
15809
15810        // Install the system package
15811        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15812        int parseFlags = mDefParseFlags
15813                | PackageParser.PARSE_MUST_BE_APK
15814                | PackageParser.PARSE_IS_SYSTEM
15815                | PackageParser.PARSE_IS_SYSTEM_DIR;
15816        if (locationIsPrivileged(disabledPs.codePath)) {
15817            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15818        }
15819
15820        final PackageParser.Package newPkg;
15821        try {
15822            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15823        } catch (PackageManagerException e) {
15824            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15825                    + e.getMessage());
15826            return false;
15827        }
15828
15829        prepareAppDataAfterInstallLIF(newPkg);
15830
15831        // writer
15832        synchronized (mPackages) {
15833            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15834
15835            // Propagate the permissions state as we do not want to drop on the floor
15836            // runtime permissions. The update permissions method below will take
15837            // care of removing obsolete permissions and grant install permissions.
15838            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15839            updatePermissionsLPw(newPkg.packageName, newPkg,
15840                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15841
15842            if (applyUserRestrictions) {
15843                if (DEBUG_REMOVE) {
15844                    Slog.d(TAG, "Propagating install state across reinstall");
15845                }
15846                for (int userId : allUserHandles) {
15847                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15848                    if (DEBUG_REMOVE) {
15849                        Slog.d(TAG, "    user " + userId + " => " + installed);
15850                    }
15851                    ps.setInstalled(installed, userId);
15852
15853                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15854                }
15855                // Regardless of writeSettings we need to ensure that this restriction
15856                // state propagation is persisted
15857                mSettings.writeAllUsersPackageRestrictionsLPr();
15858            }
15859            // can downgrade to reader here
15860            if (writeSettings) {
15861                mSettings.writeLPr();
15862            }
15863        }
15864        return true;
15865    }
15866
15867    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15868            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15869            PackageRemovedInfo outInfo, boolean writeSettings,
15870            PackageParser.Package replacingPackage) {
15871        synchronized (mPackages) {
15872            if (outInfo != null) {
15873                outInfo.uid = ps.appId;
15874            }
15875
15876            if (outInfo != null && outInfo.removedChildPackages != null) {
15877                final int childCount = (ps.childPackageNames != null)
15878                        ? ps.childPackageNames.size() : 0;
15879                for (int i = 0; i < childCount; i++) {
15880                    String childPackageName = ps.childPackageNames.get(i);
15881                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15882                    if (childPs == null) {
15883                        return false;
15884                    }
15885                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15886                            childPackageName);
15887                    if (childInfo != null) {
15888                        childInfo.uid = childPs.appId;
15889                    }
15890                }
15891            }
15892        }
15893
15894        // Delete package data from internal structures and also remove data if flag is set
15895        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15896
15897        // Delete the child packages data
15898        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15899        for (int i = 0; i < childCount; i++) {
15900            PackageSetting childPs;
15901            synchronized (mPackages) {
15902                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15903            }
15904            if (childPs != null) {
15905                PackageRemovedInfo childOutInfo = (outInfo != null
15906                        && outInfo.removedChildPackages != null)
15907                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15908                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15909                        && (replacingPackage != null
15910                        && !replacingPackage.hasChildPackage(childPs.name))
15911                        ? flags & ~DELETE_KEEP_DATA : flags;
15912                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15913                        deleteFlags, writeSettings);
15914            }
15915        }
15916
15917        // Delete application code and resources only for parent packages
15918        if (ps.parentPackageName == null) {
15919            if (deleteCodeAndResources && (outInfo != null)) {
15920                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15921                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15922                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15923            }
15924        }
15925
15926        return true;
15927    }
15928
15929    @Override
15930    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15931            int userId) {
15932        mContext.enforceCallingOrSelfPermission(
15933                android.Manifest.permission.DELETE_PACKAGES, null);
15934        synchronized (mPackages) {
15935            PackageSetting ps = mSettings.mPackages.get(packageName);
15936            if (ps == null) {
15937                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15938                return false;
15939            }
15940            if (!ps.getInstalled(userId)) {
15941                // Can't block uninstall for an app that is not installed or enabled.
15942                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15943                return false;
15944            }
15945            ps.setBlockUninstall(blockUninstall, userId);
15946            mSettings.writePackageRestrictionsLPr(userId);
15947        }
15948        return true;
15949    }
15950
15951    @Override
15952    public boolean getBlockUninstallForUser(String packageName, int userId) {
15953        synchronized (mPackages) {
15954            PackageSetting ps = mSettings.mPackages.get(packageName);
15955            if (ps == null) {
15956                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15957                return false;
15958            }
15959            return ps.getBlockUninstall(userId);
15960        }
15961    }
15962
15963    @Override
15964    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15965        int callingUid = Binder.getCallingUid();
15966        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15967            throw new SecurityException(
15968                    "setRequiredForSystemUser can only be run by the system or root");
15969        }
15970        synchronized (mPackages) {
15971            PackageSetting ps = mSettings.mPackages.get(packageName);
15972            if (ps == null) {
15973                Log.w(TAG, "Package doesn't exist: " + packageName);
15974                return false;
15975            }
15976            if (systemUserApp) {
15977                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15978            } else {
15979                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15980            }
15981            mSettings.writeLPr();
15982        }
15983        return true;
15984    }
15985
15986    /*
15987     * This method handles package deletion in general
15988     */
15989    private boolean deletePackageLIF(String packageName, UserHandle user,
15990            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15991            PackageRemovedInfo outInfo, boolean writeSettings,
15992            PackageParser.Package replacingPackage) {
15993        if (packageName == null) {
15994            Slog.w(TAG, "Attempt to delete null packageName.");
15995            return false;
15996        }
15997
15998        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15999
16000        PackageSetting ps;
16001
16002        synchronized (mPackages) {
16003            ps = mSettings.mPackages.get(packageName);
16004            if (ps == null) {
16005                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16006                return false;
16007            }
16008
16009            if (ps.parentPackageName != null && (!isSystemApp(ps)
16010                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16011                if (DEBUG_REMOVE) {
16012                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16013                            + ((user == null) ? UserHandle.USER_ALL : user));
16014                }
16015                final int removedUserId = (user != null) ? user.getIdentifier()
16016                        : UserHandle.USER_ALL;
16017                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16018                    return false;
16019                }
16020                markPackageUninstalledForUserLPw(ps, user);
16021                scheduleWritePackageRestrictionsLocked(user);
16022                return true;
16023            }
16024        }
16025
16026        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16027                && user.getIdentifier() != UserHandle.USER_ALL)) {
16028            // The caller is asking that the package only be deleted for a single
16029            // user.  To do this, we just mark its uninstalled state and delete
16030            // its data. If this is a system app, we only allow this to happen if
16031            // they have set the special DELETE_SYSTEM_APP which requests different
16032            // semantics than normal for uninstalling system apps.
16033            markPackageUninstalledForUserLPw(ps, user);
16034
16035            if (!isSystemApp(ps)) {
16036                // Do not uninstall the APK if an app should be cached
16037                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16038                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16039                    // Other user still have this package installed, so all
16040                    // we need to do is clear this user's data and save that
16041                    // it is uninstalled.
16042                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16043                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16044                        return false;
16045                    }
16046                    scheduleWritePackageRestrictionsLocked(user);
16047                    return true;
16048                } else {
16049                    // We need to set it back to 'installed' so the uninstall
16050                    // broadcasts will be sent correctly.
16051                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16052                    ps.setInstalled(true, user.getIdentifier());
16053                }
16054            } else {
16055                // This is a system app, so we assume that the
16056                // other users still have this package installed, so all
16057                // we need to do is clear this user's data and save that
16058                // it is uninstalled.
16059                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16060                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16061                    return false;
16062                }
16063                scheduleWritePackageRestrictionsLocked(user);
16064                return true;
16065            }
16066        }
16067
16068        // If we are deleting a composite package for all users, keep track
16069        // of result for each child.
16070        if (ps.childPackageNames != null && outInfo != null) {
16071            synchronized (mPackages) {
16072                final int childCount = ps.childPackageNames.size();
16073                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16074                for (int i = 0; i < childCount; i++) {
16075                    String childPackageName = ps.childPackageNames.get(i);
16076                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16077                    childInfo.removedPackage = childPackageName;
16078                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16079                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16080                    if (childPs != null) {
16081                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16082                    }
16083                }
16084            }
16085        }
16086
16087        boolean ret = false;
16088        if (isSystemApp(ps)) {
16089            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16090            // When an updated system application is deleted we delete the existing resources
16091            // as well and fall back to existing code in system partition
16092            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16093        } else {
16094            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16095            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16096                    outInfo, writeSettings, replacingPackage);
16097        }
16098
16099        // Take a note whether we deleted the package for all users
16100        if (outInfo != null) {
16101            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16102            if (outInfo.removedChildPackages != null) {
16103                synchronized (mPackages) {
16104                    final int childCount = outInfo.removedChildPackages.size();
16105                    for (int i = 0; i < childCount; i++) {
16106                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16107                        if (childInfo != null) {
16108                            childInfo.removedForAllUsers = mPackages.get(
16109                                    childInfo.removedPackage) == null;
16110                        }
16111                    }
16112                }
16113            }
16114            // If we uninstalled an update to a system app there may be some
16115            // child packages that appeared as they are declared in the system
16116            // app but were not declared in the update.
16117            if (isSystemApp(ps)) {
16118                synchronized (mPackages) {
16119                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16120                    final int childCount = (updatedPs.childPackageNames != null)
16121                            ? updatedPs.childPackageNames.size() : 0;
16122                    for (int i = 0; i < childCount; i++) {
16123                        String childPackageName = updatedPs.childPackageNames.get(i);
16124                        if (outInfo.removedChildPackages == null
16125                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16126                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16127                            if (childPs == null) {
16128                                continue;
16129                            }
16130                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16131                            installRes.name = childPackageName;
16132                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16133                            installRes.pkg = mPackages.get(childPackageName);
16134                            installRes.uid = childPs.pkg.applicationInfo.uid;
16135                            if (outInfo.appearedChildPackages == null) {
16136                                outInfo.appearedChildPackages = new ArrayMap<>();
16137                            }
16138                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16139                        }
16140                    }
16141                }
16142            }
16143        }
16144
16145        return ret;
16146    }
16147
16148    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16149        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16150                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16151        for (int nextUserId : userIds) {
16152            if (DEBUG_REMOVE) {
16153                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16154            }
16155            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16156                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16157                    false /*hidden*/, false /*suspended*/, null, null, null,
16158                    false /*blockUninstall*/,
16159                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16160        }
16161    }
16162
16163    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16164            PackageRemovedInfo outInfo) {
16165        final PackageParser.Package pkg;
16166        synchronized (mPackages) {
16167            pkg = mPackages.get(ps.name);
16168        }
16169
16170        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16171                : new int[] {userId};
16172        for (int nextUserId : userIds) {
16173            if (DEBUG_REMOVE) {
16174                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16175                        + nextUserId);
16176            }
16177
16178            destroyAppDataLIF(pkg, userId,
16179                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16180            destroyAppProfilesLIF(pkg, userId);
16181            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16182            schedulePackageCleaning(ps.name, nextUserId, false);
16183            synchronized (mPackages) {
16184                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16185                    scheduleWritePackageRestrictionsLocked(nextUserId);
16186                }
16187                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16188            }
16189        }
16190
16191        if (outInfo != null) {
16192            outInfo.removedPackage = ps.name;
16193            outInfo.removedAppId = ps.appId;
16194            outInfo.removedUsers = userIds;
16195        }
16196
16197        return true;
16198    }
16199
16200    private final class ClearStorageConnection implements ServiceConnection {
16201        IMediaContainerService mContainerService;
16202
16203        @Override
16204        public void onServiceConnected(ComponentName name, IBinder service) {
16205            synchronized (this) {
16206                mContainerService = IMediaContainerService.Stub.asInterface(service);
16207                notifyAll();
16208            }
16209        }
16210
16211        @Override
16212        public void onServiceDisconnected(ComponentName name) {
16213        }
16214    }
16215
16216    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16217        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16218
16219        final boolean mounted;
16220        if (Environment.isExternalStorageEmulated()) {
16221            mounted = true;
16222        } else {
16223            final String status = Environment.getExternalStorageState();
16224
16225            mounted = status.equals(Environment.MEDIA_MOUNTED)
16226                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16227        }
16228
16229        if (!mounted) {
16230            return;
16231        }
16232
16233        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16234        int[] users;
16235        if (userId == UserHandle.USER_ALL) {
16236            users = sUserManager.getUserIds();
16237        } else {
16238            users = new int[] { userId };
16239        }
16240        final ClearStorageConnection conn = new ClearStorageConnection();
16241        if (mContext.bindServiceAsUser(
16242                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16243            try {
16244                for (int curUser : users) {
16245                    long timeout = SystemClock.uptimeMillis() + 5000;
16246                    synchronized (conn) {
16247                        long now;
16248                        while (conn.mContainerService == null &&
16249                                (now = SystemClock.uptimeMillis()) < timeout) {
16250                            try {
16251                                conn.wait(timeout - now);
16252                            } catch (InterruptedException e) {
16253                            }
16254                        }
16255                    }
16256                    if (conn.mContainerService == null) {
16257                        return;
16258                    }
16259
16260                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16261                    clearDirectory(conn.mContainerService,
16262                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16263                    if (allData) {
16264                        clearDirectory(conn.mContainerService,
16265                                userEnv.buildExternalStorageAppDataDirs(packageName));
16266                        clearDirectory(conn.mContainerService,
16267                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16268                    }
16269                }
16270            } finally {
16271                mContext.unbindService(conn);
16272            }
16273        }
16274    }
16275
16276    @Override
16277    public void clearApplicationProfileData(String packageName) {
16278        enforceSystemOrRoot("Only the system can clear all profile data");
16279
16280        final PackageParser.Package pkg;
16281        synchronized (mPackages) {
16282            pkg = mPackages.get(packageName);
16283        }
16284
16285        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16286            synchronized (mInstallLock) {
16287                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16288                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16289                        true /* removeBaseMarker */);
16290            }
16291        }
16292    }
16293
16294    @Override
16295    public void clearApplicationUserData(final String packageName,
16296            final IPackageDataObserver observer, final int userId) {
16297        mContext.enforceCallingOrSelfPermission(
16298                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16299
16300        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16301                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16302
16303        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16304            throw new SecurityException("Cannot clear data for a protected package: "
16305                    + packageName);
16306        }
16307        // Queue up an async operation since the package deletion may take a little while.
16308        mHandler.post(new Runnable() {
16309            public void run() {
16310                mHandler.removeCallbacks(this);
16311                final boolean succeeded;
16312                try (PackageFreezer freezer = freezePackage(packageName,
16313                        "clearApplicationUserData")) {
16314                    synchronized (mInstallLock) {
16315                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16316                    }
16317                    clearExternalStorageDataSync(packageName, userId, true);
16318                }
16319                if (succeeded) {
16320                    // invoke DeviceStorageMonitor's update method to clear any notifications
16321                    DeviceStorageMonitorInternal dsm = LocalServices
16322                            .getService(DeviceStorageMonitorInternal.class);
16323                    if (dsm != null) {
16324                        dsm.checkMemory();
16325                    }
16326                }
16327                if(observer != null) {
16328                    try {
16329                        observer.onRemoveCompleted(packageName, succeeded);
16330                    } catch (RemoteException e) {
16331                        Log.i(TAG, "Observer no longer exists.");
16332                    }
16333                } //end if observer
16334            } //end run
16335        });
16336    }
16337
16338    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16339        if (packageName == null) {
16340            Slog.w(TAG, "Attempt to delete null packageName.");
16341            return false;
16342        }
16343
16344        // Try finding details about the requested package
16345        PackageParser.Package pkg;
16346        synchronized (mPackages) {
16347            pkg = mPackages.get(packageName);
16348            if (pkg == null) {
16349                final PackageSetting ps = mSettings.mPackages.get(packageName);
16350                if (ps != null) {
16351                    pkg = ps.pkg;
16352                }
16353            }
16354
16355            if (pkg == null) {
16356                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16357                return false;
16358            }
16359
16360            PackageSetting ps = (PackageSetting) pkg.mExtras;
16361            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16362        }
16363
16364        clearAppDataLIF(pkg, userId,
16365                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16366
16367        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16368        removeKeystoreDataIfNeeded(userId, appId);
16369
16370        UserManagerInternal umInternal = getUserManagerInternal();
16371        final int flags;
16372        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16373            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16374        } else if (umInternal.isUserRunning(userId)) {
16375            flags = StorageManager.FLAG_STORAGE_DE;
16376        } else {
16377            flags = 0;
16378        }
16379        prepareAppDataContentsLIF(pkg, userId, flags);
16380
16381        return true;
16382    }
16383
16384    /**
16385     * Reverts user permission state changes (permissions and flags) in
16386     * all packages for a given user.
16387     *
16388     * @param userId The device user for which to do a reset.
16389     */
16390    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16391        final int packageCount = mPackages.size();
16392        for (int i = 0; i < packageCount; i++) {
16393            PackageParser.Package pkg = mPackages.valueAt(i);
16394            PackageSetting ps = (PackageSetting) pkg.mExtras;
16395            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16396        }
16397    }
16398
16399    private void resetNetworkPolicies(int userId) {
16400        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16401    }
16402
16403    /**
16404     * Reverts user permission state changes (permissions and flags).
16405     *
16406     * @param ps The package for which to reset.
16407     * @param userId The device user for which to do a reset.
16408     */
16409    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16410            final PackageSetting ps, final int userId) {
16411        if (ps.pkg == null) {
16412            return;
16413        }
16414
16415        // These are flags that can change base on user actions.
16416        final int userSettableMask = FLAG_PERMISSION_USER_SET
16417                | FLAG_PERMISSION_USER_FIXED
16418                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16419                | FLAG_PERMISSION_REVIEW_REQUIRED;
16420
16421        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16422                | FLAG_PERMISSION_POLICY_FIXED;
16423
16424        boolean writeInstallPermissions = false;
16425        boolean writeRuntimePermissions = false;
16426
16427        final int permissionCount = ps.pkg.requestedPermissions.size();
16428        for (int i = 0; i < permissionCount; i++) {
16429            String permission = ps.pkg.requestedPermissions.get(i);
16430
16431            BasePermission bp = mSettings.mPermissions.get(permission);
16432            if (bp == null) {
16433                continue;
16434            }
16435
16436            // If shared user we just reset the state to which only this app contributed.
16437            if (ps.sharedUser != null) {
16438                boolean used = false;
16439                final int packageCount = ps.sharedUser.packages.size();
16440                for (int j = 0; j < packageCount; j++) {
16441                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16442                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16443                            && pkg.pkg.requestedPermissions.contains(permission)) {
16444                        used = true;
16445                        break;
16446                    }
16447                }
16448                if (used) {
16449                    continue;
16450                }
16451            }
16452
16453            PermissionsState permissionsState = ps.getPermissionsState();
16454
16455            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16456
16457            // Always clear the user settable flags.
16458            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16459                    bp.name) != null;
16460            // If permission review is enabled and this is a legacy app, mark the
16461            // permission as requiring a review as this is the initial state.
16462            int flags = 0;
16463            if (Build.PERMISSIONS_REVIEW_REQUIRED
16464                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16465                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16466            }
16467            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16468                if (hasInstallState) {
16469                    writeInstallPermissions = true;
16470                } else {
16471                    writeRuntimePermissions = true;
16472                }
16473            }
16474
16475            // Below is only runtime permission handling.
16476            if (!bp.isRuntime()) {
16477                continue;
16478            }
16479
16480            // Never clobber system or policy.
16481            if ((oldFlags & policyOrSystemFlags) != 0) {
16482                continue;
16483            }
16484
16485            // If this permission was granted by default, make sure it is.
16486            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16487                if (permissionsState.grantRuntimePermission(bp, userId)
16488                        != PERMISSION_OPERATION_FAILURE) {
16489                    writeRuntimePermissions = true;
16490                }
16491            // If permission review is enabled the permissions for a legacy apps
16492            // are represented as constantly granted runtime ones, so don't revoke.
16493            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16494                // Otherwise, reset the permission.
16495                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16496                switch (revokeResult) {
16497                    case PERMISSION_OPERATION_SUCCESS:
16498                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16499                        writeRuntimePermissions = true;
16500                        final int appId = ps.appId;
16501                        mHandler.post(new Runnable() {
16502                            @Override
16503                            public void run() {
16504                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16505                            }
16506                        });
16507                    } break;
16508                }
16509            }
16510        }
16511
16512        // Synchronously write as we are taking permissions away.
16513        if (writeRuntimePermissions) {
16514            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16515        }
16516
16517        // Synchronously write as we are taking permissions away.
16518        if (writeInstallPermissions) {
16519            mSettings.writeLPr();
16520        }
16521    }
16522
16523    /**
16524     * Remove entries from the keystore daemon. Will only remove it if the
16525     * {@code appId} is valid.
16526     */
16527    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16528        if (appId < 0) {
16529            return;
16530        }
16531
16532        final KeyStore keyStore = KeyStore.getInstance();
16533        if (keyStore != null) {
16534            if (userId == UserHandle.USER_ALL) {
16535                for (final int individual : sUserManager.getUserIds()) {
16536                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16537                }
16538            } else {
16539                keyStore.clearUid(UserHandle.getUid(userId, appId));
16540            }
16541        } else {
16542            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16543        }
16544    }
16545
16546    @Override
16547    public void deleteApplicationCacheFiles(final String packageName,
16548            final IPackageDataObserver observer) {
16549        final int userId = UserHandle.getCallingUserId();
16550        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16551    }
16552
16553    @Override
16554    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16555            final IPackageDataObserver observer) {
16556        mContext.enforceCallingOrSelfPermission(
16557                android.Manifest.permission.DELETE_CACHE_FILES, null);
16558        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16559                /* requireFullPermission= */ true, /* checkShell= */ false,
16560                "delete application cache files");
16561
16562        final PackageParser.Package pkg;
16563        synchronized (mPackages) {
16564            pkg = mPackages.get(packageName);
16565        }
16566
16567        // Queue up an async operation since the package deletion may take a little while.
16568        mHandler.post(new Runnable() {
16569            public void run() {
16570                synchronized (mInstallLock) {
16571                    final int flags = StorageManager.FLAG_STORAGE_DE
16572                            | StorageManager.FLAG_STORAGE_CE;
16573                    // We're only clearing cache files, so we don't care if the
16574                    // app is unfrozen and still able to run
16575                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16576                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16577                }
16578                clearExternalStorageDataSync(packageName, userId, false);
16579                if (observer != null) {
16580                    try {
16581                        observer.onRemoveCompleted(packageName, true);
16582                    } catch (RemoteException e) {
16583                        Log.i(TAG, "Observer no longer exists.");
16584                    }
16585                }
16586            }
16587        });
16588    }
16589
16590    @Override
16591    public void getPackageSizeInfo(final String packageName, int userHandle,
16592            final IPackageStatsObserver observer) {
16593        mContext.enforceCallingOrSelfPermission(
16594                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16595        if (packageName == null) {
16596            throw new IllegalArgumentException("Attempt to get size of null packageName");
16597        }
16598
16599        PackageStats stats = new PackageStats(packageName, userHandle);
16600
16601        /*
16602         * Queue up an async operation since the package measurement may take a
16603         * little while.
16604         */
16605        Message msg = mHandler.obtainMessage(INIT_COPY);
16606        msg.obj = new MeasureParams(stats, observer);
16607        mHandler.sendMessage(msg);
16608    }
16609
16610    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16611        final PackageSetting ps;
16612        synchronized (mPackages) {
16613            ps = mSettings.mPackages.get(packageName);
16614            if (ps == null) {
16615                Slog.w(TAG, "Failed to find settings for " + packageName);
16616                return false;
16617            }
16618        }
16619        try {
16620            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16621                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16622                    ps.getCeDataInode(userId), ps.codePathString, stats);
16623        } catch (InstallerException e) {
16624            Slog.w(TAG, String.valueOf(e));
16625            return false;
16626        }
16627
16628        // For now, ignore code size of packages on system partition
16629        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16630            stats.codeSize = 0;
16631        }
16632
16633        return true;
16634    }
16635
16636    private int getUidTargetSdkVersionLockedLPr(int uid) {
16637        Object obj = mSettings.getUserIdLPr(uid);
16638        if (obj instanceof SharedUserSetting) {
16639            final SharedUserSetting sus = (SharedUserSetting) obj;
16640            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16641            final Iterator<PackageSetting> it = sus.packages.iterator();
16642            while (it.hasNext()) {
16643                final PackageSetting ps = it.next();
16644                if (ps.pkg != null) {
16645                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16646                    if (v < vers) vers = v;
16647                }
16648            }
16649            return vers;
16650        } else if (obj instanceof PackageSetting) {
16651            final PackageSetting ps = (PackageSetting) obj;
16652            if (ps.pkg != null) {
16653                return ps.pkg.applicationInfo.targetSdkVersion;
16654            }
16655        }
16656        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16657    }
16658
16659    @Override
16660    public void addPreferredActivity(IntentFilter filter, int match,
16661            ComponentName[] set, ComponentName activity, int userId) {
16662        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16663                "Adding preferred");
16664    }
16665
16666    private void addPreferredActivityInternal(IntentFilter filter, int match,
16667            ComponentName[] set, ComponentName activity, boolean always, int userId,
16668            String opname) {
16669        // writer
16670        int callingUid = Binder.getCallingUid();
16671        enforceCrossUserPermission(callingUid, userId,
16672                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16673        if (filter.countActions() == 0) {
16674            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16675            return;
16676        }
16677        synchronized (mPackages) {
16678            if (mContext.checkCallingOrSelfPermission(
16679                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16680                    != PackageManager.PERMISSION_GRANTED) {
16681                if (getUidTargetSdkVersionLockedLPr(callingUid)
16682                        < Build.VERSION_CODES.FROYO) {
16683                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16684                            + callingUid);
16685                    return;
16686                }
16687                mContext.enforceCallingOrSelfPermission(
16688                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16689            }
16690
16691            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16692            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16693                    + userId + ":");
16694            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16695            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16696            scheduleWritePackageRestrictionsLocked(userId);
16697            postPreferredActivityChangedBroadcast(userId);
16698        }
16699    }
16700
16701    private void postPreferredActivityChangedBroadcast(int userId) {
16702        mHandler.post(() -> {
16703            final IActivityManager am = ActivityManagerNative.getDefault();
16704            if (am == null) {
16705                return;
16706            }
16707
16708            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16709            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16710            try {
16711                am.broadcastIntent(null, intent, null, null,
16712                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16713                        null, false, false, userId);
16714            } catch (RemoteException e) {
16715            }
16716        });
16717    }
16718
16719    @Override
16720    public void replacePreferredActivity(IntentFilter filter, int match,
16721            ComponentName[] set, ComponentName activity, int userId) {
16722        if (filter.countActions() != 1) {
16723            throw new IllegalArgumentException(
16724                    "replacePreferredActivity expects filter to have only 1 action.");
16725        }
16726        if (filter.countDataAuthorities() != 0
16727                || filter.countDataPaths() != 0
16728                || filter.countDataSchemes() > 1
16729                || filter.countDataTypes() != 0) {
16730            throw new IllegalArgumentException(
16731                    "replacePreferredActivity expects filter to have no data authorities, " +
16732                    "paths, or types; and at most one scheme.");
16733        }
16734
16735        final int callingUid = Binder.getCallingUid();
16736        enforceCrossUserPermission(callingUid, userId,
16737                true /* requireFullPermission */, false /* checkShell */,
16738                "replace preferred activity");
16739        synchronized (mPackages) {
16740            if (mContext.checkCallingOrSelfPermission(
16741                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16742                    != PackageManager.PERMISSION_GRANTED) {
16743                if (getUidTargetSdkVersionLockedLPr(callingUid)
16744                        < Build.VERSION_CODES.FROYO) {
16745                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16746                            + Binder.getCallingUid());
16747                    return;
16748                }
16749                mContext.enforceCallingOrSelfPermission(
16750                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16751            }
16752
16753            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16754            if (pir != null) {
16755                // Get all of the existing entries that exactly match this filter.
16756                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16757                if (existing != null && existing.size() == 1) {
16758                    PreferredActivity cur = existing.get(0);
16759                    if (DEBUG_PREFERRED) {
16760                        Slog.i(TAG, "Checking replace of preferred:");
16761                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16762                        if (!cur.mPref.mAlways) {
16763                            Slog.i(TAG, "  -- CUR; not mAlways!");
16764                        } else {
16765                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16766                            Slog.i(TAG, "  -- CUR: mSet="
16767                                    + Arrays.toString(cur.mPref.mSetComponents));
16768                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16769                            Slog.i(TAG, "  -- NEW: mMatch="
16770                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16771                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16772                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16773                        }
16774                    }
16775                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16776                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16777                            && cur.mPref.sameSet(set)) {
16778                        // Setting the preferred activity to what it happens to be already
16779                        if (DEBUG_PREFERRED) {
16780                            Slog.i(TAG, "Replacing with same preferred activity "
16781                                    + cur.mPref.mShortComponent + " for user "
16782                                    + userId + ":");
16783                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16784                        }
16785                        return;
16786                    }
16787                }
16788
16789                if (existing != null) {
16790                    if (DEBUG_PREFERRED) {
16791                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16792                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16793                    }
16794                    for (int i = 0; i < existing.size(); i++) {
16795                        PreferredActivity pa = existing.get(i);
16796                        if (DEBUG_PREFERRED) {
16797                            Slog.i(TAG, "Removing existing preferred activity "
16798                                    + pa.mPref.mComponent + ":");
16799                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16800                        }
16801                        pir.removeFilter(pa);
16802                    }
16803                }
16804            }
16805            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16806                    "Replacing preferred");
16807        }
16808    }
16809
16810    @Override
16811    public void clearPackagePreferredActivities(String packageName) {
16812        final int uid = Binder.getCallingUid();
16813        // writer
16814        synchronized (mPackages) {
16815            PackageParser.Package pkg = mPackages.get(packageName);
16816            if (pkg == null || pkg.applicationInfo.uid != uid) {
16817                if (mContext.checkCallingOrSelfPermission(
16818                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16819                        != PackageManager.PERMISSION_GRANTED) {
16820                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16821                            < Build.VERSION_CODES.FROYO) {
16822                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16823                                + Binder.getCallingUid());
16824                        return;
16825                    }
16826                    mContext.enforceCallingOrSelfPermission(
16827                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16828                }
16829            }
16830
16831            int user = UserHandle.getCallingUserId();
16832            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16833                scheduleWritePackageRestrictionsLocked(user);
16834            }
16835        }
16836    }
16837
16838    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16839    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16840        ArrayList<PreferredActivity> removed = null;
16841        boolean changed = false;
16842        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16843            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16844            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16845            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16846                continue;
16847            }
16848            Iterator<PreferredActivity> it = pir.filterIterator();
16849            while (it.hasNext()) {
16850                PreferredActivity pa = it.next();
16851                // Mark entry for removal only if it matches the package name
16852                // and the entry is of type "always".
16853                if (packageName == null ||
16854                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16855                                && pa.mPref.mAlways)) {
16856                    if (removed == null) {
16857                        removed = new ArrayList<PreferredActivity>();
16858                    }
16859                    removed.add(pa);
16860                }
16861            }
16862            if (removed != null) {
16863                for (int j=0; j<removed.size(); j++) {
16864                    PreferredActivity pa = removed.get(j);
16865                    pir.removeFilter(pa);
16866                }
16867                changed = true;
16868            }
16869        }
16870        if (changed) {
16871            postPreferredActivityChangedBroadcast(userId);
16872        }
16873        return changed;
16874    }
16875
16876    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16877    private void clearIntentFilterVerificationsLPw(int userId) {
16878        final int packageCount = mPackages.size();
16879        for (int i = 0; i < packageCount; i++) {
16880            PackageParser.Package pkg = mPackages.valueAt(i);
16881            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16882        }
16883    }
16884
16885    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16886    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16887        if (userId == UserHandle.USER_ALL) {
16888            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16889                    sUserManager.getUserIds())) {
16890                for (int oneUserId : sUserManager.getUserIds()) {
16891                    scheduleWritePackageRestrictionsLocked(oneUserId);
16892                }
16893            }
16894        } else {
16895            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16896                scheduleWritePackageRestrictionsLocked(userId);
16897            }
16898        }
16899    }
16900
16901    void clearDefaultBrowserIfNeeded(String packageName) {
16902        for (int oneUserId : sUserManager.getUserIds()) {
16903            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16904            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16905            if (packageName.equals(defaultBrowserPackageName)) {
16906                setDefaultBrowserPackageName(null, oneUserId);
16907            }
16908        }
16909    }
16910
16911    @Override
16912    public void resetApplicationPreferences(int userId) {
16913        mContext.enforceCallingOrSelfPermission(
16914                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16915        final long identity = Binder.clearCallingIdentity();
16916        // writer
16917        try {
16918            synchronized (mPackages) {
16919                clearPackagePreferredActivitiesLPw(null, userId);
16920                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16921                // TODO: We have to reset the default SMS and Phone. This requires
16922                // significant refactoring to keep all default apps in the package
16923                // manager (cleaner but more work) or have the services provide
16924                // callbacks to the package manager to request a default app reset.
16925                applyFactoryDefaultBrowserLPw(userId);
16926                clearIntentFilterVerificationsLPw(userId);
16927                primeDomainVerificationsLPw(userId);
16928                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16929                scheduleWritePackageRestrictionsLocked(userId);
16930            }
16931            resetNetworkPolicies(userId);
16932        } finally {
16933            Binder.restoreCallingIdentity(identity);
16934        }
16935    }
16936
16937    @Override
16938    public int getPreferredActivities(List<IntentFilter> outFilters,
16939            List<ComponentName> outActivities, String packageName) {
16940
16941        int num = 0;
16942        final int userId = UserHandle.getCallingUserId();
16943        // reader
16944        synchronized (mPackages) {
16945            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16946            if (pir != null) {
16947                final Iterator<PreferredActivity> it = pir.filterIterator();
16948                while (it.hasNext()) {
16949                    final PreferredActivity pa = it.next();
16950                    if (packageName == null
16951                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16952                                    && pa.mPref.mAlways)) {
16953                        if (outFilters != null) {
16954                            outFilters.add(new IntentFilter(pa));
16955                        }
16956                        if (outActivities != null) {
16957                            outActivities.add(pa.mPref.mComponent);
16958                        }
16959                    }
16960                }
16961            }
16962        }
16963
16964        return num;
16965    }
16966
16967    @Override
16968    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16969            int userId) {
16970        int callingUid = Binder.getCallingUid();
16971        if (callingUid != Process.SYSTEM_UID) {
16972            throw new SecurityException(
16973                    "addPersistentPreferredActivity can only be run by the system");
16974        }
16975        if (filter.countActions() == 0) {
16976            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16977            return;
16978        }
16979        synchronized (mPackages) {
16980            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16981                    ":");
16982            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16983            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16984                    new PersistentPreferredActivity(filter, activity));
16985            scheduleWritePackageRestrictionsLocked(userId);
16986            postPreferredActivityChangedBroadcast(userId);
16987        }
16988    }
16989
16990    @Override
16991    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16992        int callingUid = Binder.getCallingUid();
16993        if (callingUid != Process.SYSTEM_UID) {
16994            throw new SecurityException(
16995                    "clearPackagePersistentPreferredActivities can only be run by the system");
16996        }
16997        ArrayList<PersistentPreferredActivity> removed = null;
16998        boolean changed = false;
16999        synchronized (mPackages) {
17000            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17001                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17002                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17003                        .valueAt(i);
17004                if (userId != thisUserId) {
17005                    continue;
17006                }
17007                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17008                while (it.hasNext()) {
17009                    PersistentPreferredActivity ppa = it.next();
17010                    // Mark entry for removal only if it matches the package name.
17011                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17012                        if (removed == null) {
17013                            removed = new ArrayList<PersistentPreferredActivity>();
17014                        }
17015                        removed.add(ppa);
17016                    }
17017                }
17018                if (removed != null) {
17019                    for (int j=0; j<removed.size(); j++) {
17020                        PersistentPreferredActivity ppa = removed.get(j);
17021                        ppir.removeFilter(ppa);
17022                    }
17023                    changed = true;
17024                }
17025            }
17026
17027            if (changed) {
17028                scheduleWritePackageRestrictionsLocked(userId);
17029                postPreferredActivityChangedBroadcast(userId);
17030            }
17031        }
17032    }
17033
17034    /**
17035     * Common machinery for picking apart a restored XML blob and passing
17036     * it to a caller-supplied functor to be applied to the running system.
17037     */
17038    private void restoreFromXml(XmlPullParser parser, int userId,
17039            String expectedStartTag, BlobXmlRestorer functor)
17040            throws IOException, XmlPullParserException {
17041        int type;
17042        while ((type = parser.next()) != XmlPullParser.START_TAG
17043                && type != XmlPullParser.END_DOCUMENT) {
17044        }
17045        if (type != XmlPullParser.START_TAG) {
17046            // oops didn't find a start tag?!
17047            if (DEBUG_BACKUP) {
17048                Slog.e(TAG, "Didn't find start tag during restore");
17049            }
17050            return;
17051        }
17052Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17053        // this is supposed to be TAG_PREFERRED_BACKUP
17054        if (!expectedStartTag.equals(parser.getName())) {
17055            if (DEBUG_BACKUP) {
17056                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17057            }
17058            return;
17059        }
17060
17061        // skip interfering stuff, then we're aligned with the backing implementation
17062        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17063Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17064        functor.apply(parser, userId);
17065    }
17066
17067    private interface BlobXmlRestorer {
17068        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17069    }
17070
17071    /**
17072     * Non-Binder method, support for the backup/restore mechanism: write the
17073     * full set of preferred activities in its canonical XML format.  Returns the
17074     * XML output as a byte array, or null if there is none.
17075     */
17076    @Override
17077    public byte[] getPreferredActivityBackup(int userId) {
17078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17079            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17080        }
17081
17082        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17083        try {
17084            final XmlSerializer serializer = new FastXmlSerializer();
17085            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17086            serializer.startDocument(null, true);
17087            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17088
17089            synchronized (mPackages) {
17090                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17091            }
17092
17093            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17094            serializer.endDocument();
17095            serializer.flush();
17096        } catch (Exception e) {
17097            if (DEBUG_BACKUP) {
17098                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17099            }
17100            return null;
17101        }
17102
17103        return dataStream.toByteArray();
17104    }
17105
17106    @Override
17107    public void restorePreferredActivities(byte[] backup, int userId) {
17108        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17109            throw new SecurityException("Only the system may call restorePreferredActivities()");
17110        }
17111
17112        try {
17113            final XmlPullParser parser = Xml.newPullParser();
17114            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17115            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17116                    new BlobXmlRestorer() {
17117                        @Override
17118                        public void apply(XmlPullParser parser, int userId)
17119                                throws XmlPullParserException, IOException {
17120                            synchronized (mPackages) {
17121                                mSettings.readPreferredActivitiesLPw(parser, userId);
17122                            }
17123                        }
17124                    } );
17125        } catch (Exception e) {
17126            if (DEBUG_BACKUP) {
17127                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17128            }
17129        }
17130    }
17131
17132    /**
17133     * Non-Binder method, support for the backup/restore mechanism: write the
17134     * default browser (etc) settings in its canonical XML format.  Returns the default
17135     * browser XML representation as a byte array, or null if there is none.
17136     */
17137    @Override
17138    public byte[] getDefaultAppsBackup(int userId) {
17139        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17140            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17141        }
17142
17143        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17144        try {
17145            final XmlSerializer serializer = new FastXmlSerializer();
17146            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17147            serializer.startDocument(null, true);
17148            serializer.startTag(null, TAG_DEFAULT_APPS);
17149
17150            synchronized (mPackages) {
17151                mSettings.writeDefaultAppsLPr(serializer, userId);
17152            }
17153
17154            serializer.endTag(null, TAG_DEFAULT_APPS);
17155            serializer.endDocument();
17156            serializer.flush();
17157        } catch (Exception e) {
17158            if (DEBUG_BACKUP) {
17159                Slog.e(TAG, "Unable to write default apps for backup", e);
17160            }
17161            return null;
17162        }
17163
17164        return dataStream.toByteArray();
17165    }
17166
17167    @Override
17168    public void restoreDefaultApps(byte[] backup, int userId) {
17169        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17170            throw new SecurityException("Only the system may call restoreDefaultApps()");
17171        }
17172
17173        try {
17174            final XmlPullParser parser = Xml.newPullParser();
17175            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17176            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17177                    new BlobXmlRestorer() {
17178                        @Override
17179                        public void apply(XmlPullParser parser, int userId)
17180                                throws XmlPullParserException, IOException {
17181                            synchronized (mPackages) {
17182                                mSettings.readDefaultAppsLPw(parser, userId);
17183                            }
17184                        }
17185                    } );
17186        } catch (Exception e) {
17187            if (DEBUG_BACKUP) {
17188                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17189            }
17190        }
17191    }
17192
17193    @Override
17194    public byte[] getIntentFilterVerificationBackup(int userId) {
17195        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17196            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17197        }
17198
17199        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17200        try {
17201            final XmlSerializer serializer = new FastXmlSerializer();
17202            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17203            serializer.startDocument(null, true);
17204            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17205
17206            synchronized (mPackages) {
17207                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17208            }
17209
17210            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17211            serializer.endDocument();
17212            serializer.flush();
17213        } catch (Exception e) {
17214            if (DEBUG_BACKUP) {
17215                Slog.e(TAG, "Unable to write default apps for backup", e);
17216            }
17217            return null;
17218        }
17219
17220        return dataStream.toByteArray();
17221    }
17222
17223    @Override
17224    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17225        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17226            throw new SecurityException("Only the system may call restorePreferredActivities()");
17227        }
17228
17229        try {
17230            final XmlPullParser parser = Xml.newPullParser();
17231            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17232            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17233                    new BlobXmlRestorer() {
17234                        @Override
17235                        public void apply(XmlPullParser parser, int userId)
17236                                throws XmlPullParserException, IOException {
17237                            synchronized (mPackages) {
17238                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17239                                mSettings.writeLPr();
17240                            }
17241                        }
17242                    } );
17243        } catch (Exception e) {
17244            if (DEBUG_BACKUP) {
17245                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17246            }
17247        }
17248    }
17249
17250    @Override
17251    public byte[] getPermissionGrantBackup(int userId) {
17252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17253            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17254        }
17255
17256        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17257        try {
17258            final XmlSerializer serializer = new FastXmlSerializer();
17259            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17260            serializer.startDocument(null, true);
17261            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17262
17263            synchronized (mPackages) {
17264                serializeRuntimePermissionGrantsLPr(serializer, userId);
17265            }
17266
17267            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17268            serializer.endDocument();
17269            serializer.flush();
17270        } catch (Exception e) {
17271            if (DEBUG_BACKUP) {
17272                Slog.e(TAG, "Unable to write default apps for backup", e);
17273            }
17274            return null;
17275        }
17276
17277        return dataStream.toByteArray();
17278    }
17279
17280    @Override
17281    public void restorePermissionGrants(byte[] backup, int userId) {
17282        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17283            throw new SecurityException("Only the system may call restorePermissionGrants()");
17284        }
17285
17286        try {
17287            final XmlPullParser parser = Xml.newPullParser();
17288            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17289            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17290                    new BlobXmlRestorer() {
17291                        @Override
17292                        public void apply(XmlPullParser parser, int userId)
17293                                throws XmlPullParserException, IOException {
17294                            synchronized (mPackages) {
17295                                processRestoredPermissionGrantsLPr(parser, userId);
17296                            }
17297                        }
17298                    } );
17299        } catch (Exception e) {
17300            if (DEBUG_BACKUP) {
17301                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17302            }
17303        }
17304    }
17305
17306    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17307            throws IOException {
17308        serializer.startTag(null, TAG_ALL_GRANTS);
17309
17310        final int N = mSettings.mPackages.size();
17311        for (int i = 0; i < N; i++) {
17312            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17313            boolean pkgGrantsKnown = false;
17314
17315            PermissionsState packagePerms = ps.getPermissionsState();
17316
17317            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17318                final int grantFlags = state.getFlags();
17319                // only look at grants that are not system/policy fixed
17320                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17321                    final boolean isGranted = state.isGranted();
17322                    // And only back up the user-twiddled state bits
17323                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17324                        final String packageName = mSettings.mPackages.keyAt(i);
17325                        if (!pkgGrantsKnown) {
17326                            serializer.startTag(null, TAG_GRANT);
17327                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17328                            pkgGrantsKnown = true;
17329                        }
17330
17331                        final boolean userSet =
17332                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17333                        final boolean userFixed =
17334                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17335                        final boolean revoke =
17336                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17337
17338                        serializer.startTag(null, TAG_PERMISSION);
17339                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17340                        if (isGranted) {
17341                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17342                        }
17343                        if (userSet) {
17344                            serializer.attribute(null, ATTR_USER_SET, "true");
17345                        }
17346                        if (userFixed) {
17347                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17348                        }
17349                        if (revoke) {
17350                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17351                        }
17352                        serializer.endTag(null, TAG_PERMISSION);
17353                    }
17354                }
17355            }
17356
17357            if (pkgGrantsKnown) {
17358                serializer.endTag(null, TAG_GRANT);
17359            }
17360        }
17361
17362        serializer.endTag(null, TAG_ALL_GRANTS);
17363    }
17364
17365    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17366            throws XmlPullParserException, IOException {
17367        String pkgName = null;
17368        int outerDepth = parser.getDepth();
17369        int type;
17370        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17371                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17372            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17373                continue;
17374            }
17375
17376            final String tagName = parser.getName();
17377            if (tagName.equals(TAG_GRANT)) {
17378                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17379                if (DEBUG_BACKUP) {
17380                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17381                }
17382            } else if (tagName.equals(TAG_PERMISSION)) {
17383
17384                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17385                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17386
17387                int newFlagSet = 0;
17388                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17389                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17390                }
17391                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17392                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17393                }
17394                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17395                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17396                }
17397                if (DEBUG_BACKUP) {
17398                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17399                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17400                }
17401                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17402                if (ps != null) {
17403                    // Already installed so we apply the grant immediately
17404                    if (DEBUG_BACKUP) {
17405                        Slog.v(TAG, "        + already installed; applying");
17406                    }
17407                    PermissionsState perms = ps.getPermissionsState();
17408                    BasePermission bp = mSettings.mPermissions.get(permName);
17409                    if (bp != null) {
17410                        if (isGranted) {
17411                            perms.grantRuntimePermission(bp, userId);
17412                        }
17413                        if (newFlagSet != 0) {
17414                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17415                        }
17416                    }
17417                } else {
17418                    // Need to wait for post-restore install to apply the grant
17419                    if (DEBUG_BACKUP) {
17420                        Slog.v(TAG, "        - not yet installed; saving for later");
17421                    }
17422                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17423                            isGranted, newFlagSet, userId);
17424                }
17425            } else {
17426                PackageManagerService.reportSettingsProblem(Log.WARN,
17427                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17428                XmlUtils.skipCurrentTag(parser);
17429            }
17430        }
17431
17432        scheduleWriteSettingsLocked();
17433        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17434    }
17435
17436    @Override
17437    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17438            int sourceUserId, int targetUserId, int flags) {
17439        mContext.enforceCallingOrSelfPermission(
17440                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17441        int callingUid = Binder.getCallingUid();
17442        enforceOwnerRights(ownerPackage, callingUid);
17443        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17444        if (intentFilter.countActions() == 0) {
17445            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17446            return;
17447        }
17448        synchronized (mPackages) {
17449            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17450                    ownerPackage, targetUserId, flags);
17451            CrossProfileIntentResolver resolver =
17452                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17453            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17454            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17455            if (existing != null) {
17456                int size = existing.size();
17457                for (int i = 0; i < size; i++) {
17458                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17459                        return;
17460                    }
17461                }
17462            }
17463            resolver.addFilter(newFilter);
17464            scheduleWritePackageRestrictionsLocked(sourceUserId);
17465        }
17466    }
17467
17468    @Override
17469    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17470        mContext.enforceCallingOrSelfPermission(
17471                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17472        int callingUid = Binder.getCallingUid();
17473        enforceOwnerRights(ownerPackage, callingUid);
17474        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17475        synchronized (mPackages) {
17476            CrossProfileIntentResolver resolver =
17477                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17478            ArraySet<CrossProfileIntentFilter> set =
17479                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17480            for (CrossProfileIntentFilter filter : set) {
17481                if (filter.getOwnerPackage().equals(ownerPackage)) {
17482                    resolver.removeFilter(filter);
17483                }
17484            }
17485            scheduleWritePackageRestrictionsLocked(sourceUserId);
17486        }
17487    }
17488
17489    // Enforcing that callingUid is owning pkg on userId
17490    private void enforceOwnerRights(String pkg, int callingUid) {
17491        // The system owns everything.
17492        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17493            return;
17494        }
17495        int callingUserId = UserHandle.getUserId(callingUid);
17496        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17497        if (pi == null) {
17498            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17499                    + callingUserId);
17500        }
17501        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17502            throw new SecurityException("Calling uid " + callingUid
17503                    + " does not own package " + pkg);
17504        }
17505    }
17506
17507    @Override
17508    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17509        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17510    }
17511
17512    private Intent getHomeIntent() {
17513        Intent intent = new Intent(Intent.ACTION_MAIN);
17514        intent.addCategory(Intent.CATEGORY_HOME);
17515        intent.addCategory(Intent.CATEGORY_DEFAULT);
17516        return intent;
17517    }
17518
17519    private IntentFilter getHomeFilter() {
17520        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17521        filter.addCategory(Intent.CATEGORY_HOME);
17522        filter.addCategory(Intent.CATEGORY_DEFAULT);
17523        return filter;
17524    }
17525
17526    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17527            int userId) {
17528        Intent intent  = getHomeIntent();
17529        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17530                PackageManager.GET_META_DATA, userId);
17531        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17532                true, false, false, userId);
17533
17534        allHomeCandidates.clear();
17535        if (list != null) {
17536            for (ResolveInfo ri : list) {
17537                allHomeCandidates.add(ri);
17538            }
17539        }
17540        return (preferred == null || preferred.activityInfo == null)
17541                ? null
17542                : new ComponentName(preferred.activityInfo.packageName,
17543                        preferred.activityInfo.name);
17544    }
17545
17546    @Override
17547    public void setHomeActivity(ComponentName comp, int userId) {
17548        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17549        getHomeActivitiesAsUser(homeActivities, userId);
17550
17551        boolean found = false;
17552
17553        final int size = homeActivities.size();
17554        final ComponentName[] set = new ComponentName[size];
17555        for (int i = 0; i < size; i++) {
17556            final ResolveInfo candidate = homeActivities.get(i);
17557            final ActivityInfo info = candidate.activityInfo;
17558            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17559            set[i] = activityName;
17560            if (!found && activityName.equals(comp)) {
17561                found = true;
17562            }
17563        }
17564        if (!found) {
17565            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17566                    + userId);
17567        }
17568        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17569                set, comp, userId);
17570    }
17571
17572    private @Nullable String getSetupWizardPackageName() {
17573        final Intent intent = new Intent(Intent.ACTION_MAIN);
17574        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17575
17576        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17577                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17578                        | MATCH_DISABLED_COMPONENTS,
17579                UserHandle.myUserId());
17580        if (matches.size() == 1) {
17581            return matches.get(0).getComponentInfo().packageName;
17582        } else {
17583            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17584                    + ": matches=" + matches);
17585            return null;
17586        }
17587    }
17588
17589    @Override
17590    public void setApplicationEnabledSetting(String appPackageName,
17591            int newState, int flags, int userId, String callingPackage) {
17592        if (!sUserManager.exists(userId)) return;
17593        if (callingPackage == null) {
17594            callingPackage = Integer.toString(Binder.getCallingUid());
17595        }
17596        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17597    }
17598
17599    @Override
17600    public void setComponentEnabledSetting(ComponentName componentName,
17601            int newState, int flags, int userId) {
17602        if (!sUserManager.exists(userId)) return;
17603        setEnabledSetting(componentName.getPackageName(),
17604                componentName.getClassName(), newState, flags, userId, null);
17605    }
17606
17607    private void setEnabledSetting(final String packageName, String className, int newState,
17608            final int flags, int userId, String callingPackage) {
17609        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17610              || newState == COMPONENT_ENABLED_STATE_ENABLED
17611              || newState == COMPONENT_ENABLED_STATE_DISABLED
17612              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17613              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17614            throw new IllegalArgumentException("Invalid new component state: "
17615                    + newState);
17616        }
17617        PackageSetting pkgSetting;
17618        final int uid = Binder.getCallingUid();
17619        final int permission;
17620        if (uid == Process.SYSTEM_UID) {
17621            permission = PackageManager.PERMISSION_GRANTED;
17622        } else {
17623            permission = mContext.checkCallingOrSelfPermission(
17624                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17625        }
17626        enforceCrossUserPermission(uid, userId,
17627                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17628        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17629        boolean sendNow = false;
17630        boolean isApp = (className == null);
17631        String componentName = isApp ? packageName : className;
17632        int packageUid = -1;
17633        ArrayList<String> components;
17634
17635        // writer
17636        synchronized (mPackages) {
17637            pkgSetting = mSettings.mPackages.get(packageName);
17638            if (pkgSetting == null) {
17639                if (className == null) {
17640                    throw new IllegalArgumentException("Unknown package: " + packageName);
17641                }
17642                throw new IllegalArgumentException(
17643                        "Unknown component: " + packageName + "/" + className);
17644            }
17645        }
17646
17647        // Limit who can change which apps
17648        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17649            // Don't allow apps that don't have permission to modify other apps
17650            if (!allowedByPermission) {
17651                throw new SecurityException(
17652                        "Permission Denial: attempt to change component state from pid="
17653                        + Binder.getCallingPid()
17654                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17655            }
17656            // Don't allow changing protected packages.
17657            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17658                throw new SecurityException("Cannot disable a protected package: " + packageName);
17659            }
17660        }
17661
17662        synchronized (mPackages) {
17663            if (uid == Process.SHELL_UID) {
17664                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17665                int oldState = pkgSetting.getEnabled(userId);
17666                if (className == null
17667                    &&
17668                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17669                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17670                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17671                    &&
17672                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17673                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17674                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17675                    // ok
17676                } else {
17677                    throw new SecurityException(
17678                            "Shell cannot change component state for " + packageName + "/"
17679                            + className + " to " + newState);
17680                }
17681            }
17682            if (className == null) {
17683                // We're dealing with an application/package level state change
17684                if (pkgSetting.getEnabled(userId) == newState) {
17685                    // Nothing to do
17686                    return;
17687                }
17688                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17689                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17690                    // Don't care about who enables an app.
17691                    callingPackage = null;
17692                }
17693                pkgSetting.setEnabled(newState, userId, callingPackage);
17694                // pkgSetting.pkg.mSetEnabled = newState;
17695            } else {
17696                // We're dealing with a component level state change
17697                // First, verify that this is a valid class name.
17698                PackageParser.Package pkg = pkgSetting.pkg;
17699                if (pkg == null || !pkg.hasComponentClassName(className)) {
17700                    if (pkg != null &&
17701                            pkg.applicationInfo.targetSdkVersion >=
17702                                    Build.VERSION_CODES.JELLY_BEAN) {
17703                        throw new IllegalArgumentException("Component class " + className
17704                                + " does not exist in " + packageName);
17705                    } else {
17706                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17707                                + className + " does not exist in " + packageName);
17708                    }
17709                }
17710                switch (newState) {
17711                case COMPONENT_ENABLED_STATE_ENABLED:
17712                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17713                        return;
17714                    }
17715                    break;
17716                case COMPONENT_ENABLED_STATE_DISABLED:
17717                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17718                        return;
17719                    }
17720                    break;
17721                case COMPONENT_ENABLED_STATE_DEFAULT:
17722                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17723                        return;
17724                    }
17725                    break;
17726                default:
17727                    Slog.e(TAG, "Invalid new component state: " + newState);
17728                    return;
17729                }
17730            }
17731            scheduleWritePackageRestrictionsLocked(userId);
17732            components = mPendingBroadcasts.get(userId, packageName);
17733            final boolean newPackage = components == null;
17734            if (newPackage) {
17735                components = new ArrayList<String>();
17736            }
17737            if (!components.contains(componentName)) {
17738                components.add(componentName);
17739            }
17740            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17741                sendNow = true;
17742                // Purge entry from pending broadcast list if another one exists already
17743                // since we are sending one right away.
17744                mPendingBroadcasts.remove(userId, packageName);
17745            } else {
17746                if (newPackage) {
17747                    mPendingBroadcasts.put(userId, packageName, components);
17748                }
17749                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17750                    // Schedule a message
17751                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17752                }
17753            }
17754        }
17755
17756        long callingId = Binder.clearCallingIdentity();
17757        try {
17758            if (sendNow) {
17759                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17760                sendPackageChangedBroadcast(packageName,
17761                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17762            }
17763        } finally {
17764            Binder.restoreCallingIdentity(callingId);
17765        }
17766    }
17767
17768    @Override
17769    public void flushPackageRestrictionsAsUser(int userId) {
17770        if (!sUserManager.exists(userId)) {
17771            return;
17772        }
17773        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17774                false /* checkShell */, "flushPackageRestrictions");
17775        synchronized (mPackages) {
17776            mSettings.writePackageRestrictionsLPr(userId);
17777            mDirtyUsers.remove(userId);
17778            if (mDirtyUsers.isEmpty()) {
17779                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17780            }
17781        }
17782    }
17783
17784    private void sendPackageChangedBroadcast(String packageName,
17785            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17786        if (DEBUG_INSTALL)
17787            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17788                    + componentNames);
17789        Bundle extras = new Bundle(4);
17790        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17791        String nameList[] = new String[componentNames.size()];
17792        componentNames.toArray(nameList);
17793        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17794        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17795        extras.putInt(Intent.EXTRA_UID, packageUid);
17796        // If this is not reporting a change of the overall package, then only send it
17797        // to registered receivers.  We don't want to launch a swath of apps for every
17798        // little component state change.
17799        final int flags = !componentNames.contains(packageName)
17800                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17801        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17802                new int[] {UserHandle.getUserId(packageUid)});
17803    }
17804
17805    @Override
17806    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17807        if (!sUserManager.exists(userId)) return;
17808        final int uid = Binder.getCallingUid();
17809        final int permission = mContext.checkCallingOrSelfPermission(
17810                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17811        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17812        enforceCrossUserPermission(uid, userId,
17813                true /* requireFullPermission */, true /* checkShell */, "stop package");
17814        // writer
17815        synchronized (mPackages) {
17816            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17817                    allowedByPermission, uid, userId)) {
17818                scheduleWritePackageRestrictionsLocked(userId);
17819            }
17820        }
17821    }
17822
17823    @Override
17824    public String getInstallerPackageName(String packageName) {
17825        // reader
17826        synchronized (mPackages) {
17827            return mSettings.getInstallerPackageNameLPr(packageName);
17828        }
17829    }
17830
17831    public boolean isOrphaned(String packageName) {
17832        // reader
17833        synchronized (mPackages) {
17834            return mSettings.isOrphaned(packageName);
17835        }
17836    }
17837
17838    @Override
17839    public int getApplicationEnabledSetting(String packageName, int userId) {
17840        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17841        int uid = Binder.getCallingUid();
17842        enforceCrossUserPermission(uid, userId,
17843                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17844        // reader
17845        synchronized (mPackages) {
17846            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17847        }
17848    }
17849
17850    @Override
17851    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17852        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17853        int uid = Binder.getCallingUid();
17854        enforceCrossUserPermission(uid, userId,
17855                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17856        // reader
17857        synchronized (mPackages) {
17858            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17859        }
17860    }
17861
17862    @Override
17863    public void enterSafeMode() {
17864        enforceSystemOrRoot("Only the system can request entering safe mode");
17865
17866        if (!mSystemReady) {
17867            mSafeMode = true;
17868        }
17869    }
17870
17871    @Override
17872    public void systemReady() {
17873        mSystemReady = true;
17874
17875        // Read the compatibilty setting when the system is ready.
17876        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17877                mContext.getContentResolver(),
17878                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17879        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17880        if (DEBUG_SETTINGS) {
17881            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17882        }
17883
17884        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17885
17886        synchronized (mPackages) {
17887            // Verify that all of the preferred activity components actually
17888            // exist.  It is possible for applications to be updated and at
17889            // that point remove a previously declared activity component that
17890            // had been set as a preferred activity.  We try to clean this up
17891            // the next time we encounter that preferred activity, but it is
17892            // possible for the user flow to never be able to return to that
17893            // situation so here we do a sanity check to make sure we haven't
17894            // left any junk around.
17895            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17896            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17897                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17898                removed.clear();
17899                for (PreferredActivity pa : pir.filterSet()) {
17900                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17901                        removed.add(pa);
17902                    }
17903                }
17904                if (removed.size() > 0) {
17905                    for (int r=0; r<removed.size(); r++) {
17906                        PreferredActivity pa = removed.get(r);
17907                        Slog.w(TAG, "Removing dangling preferred activity: "
17908                                + pa.mPref.mComponent);
17909                        pir.removeFilter(pa);
17910                    }
17911                    mSettings.writePackageRestrictionsLPr(
17912                            mSettings.mPreferredActivities.keyAt(i));
17913                }
17914            }
17915
17916            for (int userId : UserManagerService.getInstance().getUserIds()) {
17917                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17918                    grantPermissionsUserIds = ArrayUtils.appendInt(
17919                            grantPermissionsUserIds, userId);
17920                }
17921            }
17922        }
17923        sUserManager.systemReady();
17924
17925        // If we upgraded grant all default permissions before kicking off.
17926        for (int userId : grantPermissionsUserIds) {
17927            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17928        }
17929
17930        // Kick off any messages waiting for system ready
17931        if (mPostSystemReadyMessages != null) {
17932            for (Message msg : mPostSystemReadyMessages) {
17933                msg.sendToTarget();
17934            }
17935            mPostSystemReadyMessages = null;
17936        }
17937
17938        // Watch for external volumes that come and go over time
17939        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17940        storage.registerListener(mStorageListener);
17941
17942        mInstallerService.systemReady();
17943        mPackageDexOptimizer.systemReady();
17944
17945        MountServiceInternal mountServiceInternal = LocalServices.getService(
17946                MountServiceInternal.class);
17947        mountServiceInternal.addExternalStoragePolicy(
17948                new MountServiceInternal.ExternalStorageMountPolicy() {
17949            @Override
17950            public int getMountMode(int uid, String packageName) {
17951                if (Process.isIsolated(uid)) {
17952                    return Zygote.MOUNT_EXTERNAL_NONE;
17953                }
17954                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17955                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17956                }
17957                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17958                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17959                }
17960                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17961                    return Zygote.MOUNT_EXTERNAL_READ;
17962                }
17963                return Zygote.MOUNT_EXTERNAL_WRITE;
17964            }
17965
17966            @Override
17967            public boolean hasExternalStorage(int uid, String packageName) {
17968                return true;
17969            }
17970        });
17971
17972        // Now that we're mostly running, clean up stale users and apps
17973        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17974        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17975    }
17976
17977    @Override
17978    public boolean isSafeMode() {
17979        return mSafeMode;
17980    }
17981
17982    @Override
17983    public boolean hasSystemUidErrors() {
17984        return mHasSystemUidErrors;
17985    }
17986
17987    static String arrayToString(int[] array) {
17988        StringBuffer buf = new StringBuffer(128);
17989        buf.append('[');
17990        if (array != null) {
17991            for (int i=0; i<array.length; i++) {
17992                if (i > 0) buf.append(", ");
17993                buf.append(array[i]);
17994            }
17995        }
17996        buf.append(']');
17997        return buf.toString();
17998    }
17999
18000    static class DumpState {
18001        public static final int DUMP_LIBS = 1 << 0;
18002        public static final int DUMP_FEATURES = 1 << 1;
18003        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18004        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18005        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18006        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18007        public static final int DUMP_PERMISSIONS = 1 << 6;
18008        public static final int DUMP_PACKAGES = 1 << 7;
18009        public static final int DUMP_SHARED_USERS = 1 << 8;
18010        public static final int DUMP_MESSAGES = 1 << 9;
18011        public static final int DUMP_PROVIDERS = 1 << 10;
18012        public static final int DUMP_VERIFIERS = 1 << 11;
18013        public static final int DUMP_PREFERRED = 1 << 12;
18014        public static final int DUMP_PREFERRED_XML = 1 << 13;
18015        public static final int DUMP_KEYSETS = 1 << 14;
18016        public static final int DUMP_VERSION = 1 << 15;
18017        public static final int DUMP_INSTALLS = 1 << 16;
18018        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18019        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18020        public static final int DUMP_FROZEN = 1 << 19;
18021        public static final int DUMP_DEXOPT = 1 << 20;
18022        public static final int DUMP_COMPILER_STATS = 1 << 21;
18023
18024        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18025
18026        private int mTypes;
18027
18028        private int mOptions;
18029
18030        private boolean mTitlePrinted;
18031
18032        private SharedUserSetting mSharedUser;
18033
18034        public boolean isDumping(int type) {
18035            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18036                return true;
18037            }
18038
18039            return (mTypes & type) != 0;
18040        }
18041
18042        public void setDump(int type) {
18043            mTypes |= type;
18044        }
18045
18046        public boolean isOptionEnabled(int option) {
18047            return (mOptions & option) != 0;
18048        }
18049
18050        public void setOptionEnabled(int option) {
18051            mOptions |= option;
18052        }
18053
18054        public boolean onTitlePrinted() {
18055            final boolean printed = mTitlePrinted;
18056            mTitlePrinted = true;
18057            return printed;
18058        }
18059
18060        public boolean getTitlePrinted() {
18061            return mTitlePrinted;
18062        }
18063
18064        public void setTitlePrinted(boolean enabled) {
18065            mTitlePrinted = enabled;
18066        }
18067
18068        public SharedUserSetting getSharedUser() {
18069            return mSharedUser;
18070        }
18071
18072        public void setSharedUser(SharedUserSetting user) {
18073            mSharedUser = user;
18074        }
18075    }
18076
18077    @Override
18078    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18079            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18080        (new PackageManagerShellCommand(this)).exec(
18081                this, in, out, err, args, resultReceiver);
18082    }
18083
18084    @Override
18085    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18086        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18087                != PackageManager.PERMISSION_GRANTED) {
18088            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18089                    + Binder.getCallingPid()
18090                    + ", uid=" + Binder.getCallingUid()
18091                    + " without permission "
18092                    + android.Manifest.permission.DUMP);
18093            return;
18094        }
18095
18096        DumpState dumpState = new DumpState();
18097        boolean fullPreferred = false;
18098        boolean checkin = false;
18099
18100        String packageName = null;
18101        ArraySet<String> permissionNames = null;
18102
18103        int opti = 0;
18104        while (opti < args.length) {
18105            String opt = args[opti];
18106            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18107                break;
18108            }
18109            opti++;
18110
18111            if ("-a".equals(opt)) {
18112                // Right now we only know how to print all.
18113            } else if ("-h".equals(opt)) {
18114                pw.println("Package manager dump options:");
18115                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18116                pw.println("    --checkin: dump for a checkin");
18117                pw.println("    -f: print details of intent filters");
18118                pw.println("    -h: print this help");
18119                pw.println("  cmd may be one of:");
18120                pw.println("    l[ibraries]: list known shared libraries");
18121                pw.println("    f[eatures]: list device features");
18122                pw.println("    k[eysets]: print known keysets");
18123                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18124                pw.println("    perm[issions]: dump permissions");
18125                pw.println("    permission [name ...]: dump declaration and use of given permission");
18126                pw.println("    pref[erred]: print preferred package settings");
18127                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18128                pw.println("    prov[iders]: dump content providers");
18129                pw.println("    p[ackages]: dump installed packages");
18130                pw.println("    s[hared-users]: dump shared user IDs");
18131                pw.println("    m[essages]: print collected runtime messages");
18132                pw.println("    v[erifiers]: print package verifier info");
18133                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18134                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18135                pw.println("    version: print database version info");
18136                pw.println("    write: write current settings now");
18137                pw.println("    installs: details about install sessions");
18138                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18139                pw.println("    dexopt: dump dexopt state");
18140                pw.println("    compiler-stats: dump compiler statistics");
18141                pw.println("    <package.name>: info about given package");
18142                return;
18143            } else if ("--checkin".equals(opt)) {
18144                checkin = true;
18145            } else if ("-f".equals(opt)) {
18146                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18147            } else {
18148                pw.println("Unknown argument: " + opt + "; use -h for help");
18149            }
18150        }
18151
18152        // Is the caller requesting to dump a particular piece of data?
18153        if (opti < args.length) {
18154            String cmd = args[opti];
18155            opti++;
18156            // Is this a package name?
18157            if ("android".equals(cmd) || cmd.contains(".")) {
18158                packageName = cmd;
18159                // When dumping a single package, we always dump all of its
18160                // filter information since the amount of data will be reasonable.
18161                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18162            } else if ("check-permission".equals(cmd)) {
18163                if (opti >= args.length) {
18164                    pw.println("Error: check-permission missing permission argument");
18165                    return;
18166                }
18167                String perm = args[opti];
18168                opti++;
18169                if (opti >= args.length) {
18170                    pw.println("Error: check-permission missing package argument");
18171                    return;
18172                }
18173                String pkg = args[opti];
18174                opti++;
18175                int user = UserHandle.getUserId(Binder.getCallingUid());
18176                if (opti < args.length) {
18177                    try {
18178                        user = Integer.parseInt(args[opti]);
18179                    } catch (NumberFormatException e) {
18180                        pw.println("Error: check-permission user argument is not a number: "
18181                                + args[opti]);
18182                        return;
18183                    }
18184                }
18185                pw.println(checkPermission(perm, pkg, user));
18186                return;
18187            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18188                dumpState.setDump(DumpState.DUMP_LIBS);
18189            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18190                dumpState.setDump(DumpState.DUMP_FEATURES);
18191            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18192                if (opti >= args.length) {
18193                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18194                            | DumpState.DUMP_SERVICE_RESOLVERS
18195                            | DumpState.DUMP_RECEIVER_RESOLVERS
18196                            | DumpState.DUMP_CONTENT_RESOLVERS);
18197                } else {
18198                    while (opti < args.length) {
18199                        String name = args[opti];
18200                        if ("a".equals(name) || "activity".equals(name)) {
18201                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18202                        } else if ("s".equals(name) || "service".equals(name)) {
18203                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18204                        } else if ("r".equals(name) || "receiver".equals(name)) {
18205                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18206                        } else if ("c".equals(name) || "content".equals(name)) {
18207                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18208                        } else {
18209                            pw.println("Error: unknown resolver table type: " + name);
18210                            return;
18211                        }
18212                        opti++;
18213                    }
18214                }
18215            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18216                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18217            } else if ("permission".equals(cmd)) {
18218                if (opti >= args.length) {
18219                    pw.println("Error: permission requires permission name");
18220                    return;
18221                }
18222                permissionNames = new ArraySet<>();
18223                while (opti < args.length) {
18224                    permissionNames.add(args[opti]);
18225                    opti++;
18226                }
18227                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18228                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18229            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18230                dumpState.setDump(DumpState.DUMP_PREFERRED);
18231            } else if ("preferred-xml".equals(cmd)) {
18232                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18233                if (opti < args.length && "--full".equals(args[opti])) {
18234                    fullPreferred = true;
18235                    opti++;
18236                }
18237            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18238                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18239            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18240                dumpState.setDump(DumpState.DUMP_PACKAGES);
18241            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18242                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18243            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18244                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18245            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18246                dumpState.setDump(DumpState.DUMP_MESSAGES);
18247            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18248                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18249            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18250                    || "intent-filter-verifiers".equals(cmd)) {
18251                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18252            } else if ("version".equals(cmd)) {
18253                dumpState.setDump(DumpState.DUMP_VERSION);
18254            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18255                dumpState.setDump(DumpState.DUMP_KEYSETS);
18256            } else if ("installs".equals(cmd)) {
18257                dumpState.setDump(DumpState.DUMP_INSTALLS);
18258            } else if ("frozen".equals(cmd)) {
18259                dumpState.setDump(DumpState.DUMP_FROZEN);
18260            } else if ("dexopt".equals(cmd)) {
18261                dumpState.setDump(DumpState.DUMP_DEXOPT);
18262            } else if ("compiler-stats".equals(cmd)) {
18263                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18264            } else if ("write".equals(cmd)) {
18265                synchronized (mPackages) {
18266                    mSettings.writeLPr();
18267                    pw.println("Settings written.");
18268                    return;
18269                }
18270            }
18271        }
18272
18273        if (checkin) {
18274            pw.println("vers,1");
18275        }
18276
18277        // reader
18278        synchronized (mPackages) {
18279            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18280                if (!checkin) {
18281                    if (dumpState.onTitlePrinted())
18282                        pw.println();
18283                    pw.println("Database versions:");
18284                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18285                }
18286            }
18287
18288            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18289                if (!checkin) {
18290                    if (dumpState.onTitlePrinted())
18291                        pw.println();
18292                    pw.println("Verifiers:");
18293                    pw.print("  Required: ");
18294                    pw.print(mRequiredVerifierPackage);
18295                    pw.print(" (uid=");
18296                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18297                            UserHandle.USER_SYSTEM));
18298                    pw.println(")");
18299                } else if (mRequiredVerifierPackage != null) {
18300                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18301                    pw.print(",");
18302                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18303                            UserHandle.USER_SYSTEM));
18304                }
18305            }
18306
18307            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18308                    packageName == null) {
18309                if (mIntentFilterVerifierComponent != null) {
18310                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18311                    if (!checkin) {
18312                        if (dumpState.onTitlePrinted())
18313                            pw.println();
18314                        pw.println("Intent Filter Verifier:");
18315                        pw.print("  Using: ");
18316                        pw.print(verifierPackageName);
18317                        pw.print(" (uid=");
18318                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18319                                UserHandle.USER_SYSTEM));
18320                        pw.println(")");
18321                    } else if (verifierPackageName != null) {
18322                        pw.print("ifv,"); pw.print(verifierPackageName);
18323                        pw.print(",");
18324                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18325                                UserHandle.USER_SYSTEM));
18326                    }
18327                } else {
18328                    pw.println();
18329                    pw.println("No Intent Filter Verifier available!");
18330                }
18331            }
18332
18333            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18334                boolean printedHeader = false;
18335                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18336                while (it.hasNext()) {
18337                    String name = it.next();
18338                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18339                    if (!checkin) {
18340                        if (!printedHeader) {
18341                            if (dumpState.onTitlePrinted())
18342                                pw.println();
18343                            pw.println("Libraries:");
18344                            printedHeader = true;
18345                        }
18346                        pw.print("  ");
18347                    } else {
18348                        pw.print("lib,");
18349                    }
18350                    pw.print(name);
18351                    if (!checkin) {
18352                        pw.print(" -> ");
18353                    }
18354                    if (ent.path != null) {
18355                        if (!checkin) {
18356                            pw.print("(jar) ");
18357                            pw.print(ent.path);
18358                        } else {
18359                            pw.print(",jar,");
18360                            pw.print(ent.path);
18361                        }
18362                    } else {
18363                        if (!checkin) {
18364                            pw.print("(apk) ");
18365                            pw.print(ent.apk);
18366                        } else {
18367                            pw.print(",apk,");
18368                            pw.print(ent.apk);
18369                        }
18370                    }
18371                    pw.println();
18372                }
18373            }
18374
18375            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18376                if (dumpState.onTitlePrinted())
18377                    pw.println();
18378                if (!checkin) {
18379                    pw.println("Features:");
18380                }
18381
18382                for (FeatureInfo feat : mAvailableFeatures.values()) {
18383                    if (checkin) {
18384                        pw.print("feat,");
18385                        pw.print(feat.name);
18386                        pw.print(",");
18387                        pw.println(feat.version);
18388                    } else {
18389                        pw.print("  ");
18390                        pw.print(feat.name);
18391                        if (feat.version > 0) {
18392                            pw.print(" version=");
18393                            pw.print(feat.version);
18394                        }
18395                        pw.println();
18396                    }
18397                }
18398            }
18399
18400            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18401                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18402                        : "Activity Resolver Table:", "  ", packageName,
18403                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18404                    dumpState.setTitlePrinted(true);
18405                }
18406            }
18407            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18408                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18409                        : "Receiver Resolver Table:", "  ", packageName,
18410                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18411                    dumpState.setTitlePrinted(true);
18412                }
18413            }
18414            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18415                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18416                        : "Service Resolver Table:", "  ", packageName,
18417                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18418                    dumpState.setTitlePrinted(true);
18419                }
18420            }
18421            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18422                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18423                        : "Provider Resolver Table:", "  ", packageName,
18424                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18425                    dumpState.setTitlePrinted(true);
18426                }
18427            }
18428
18429            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18430                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18431                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18432                    int user = mSettings.mPreferredActivities.keyAt(i);
18433                    if (pir.dump(pw,
18434                            dumpState.getTitlePrinted()
18435                                ? "\nPreferred Activities User " + user + ":"
18436                                : "Preferred Activities User " + user + ":", "  ",
18437                            packageName, true, false)) {
18438                        dumpState.setTitlePrinted(true);
18439                    }
18440                }
18441            }
18442
18443            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18444                pw.flush();
18445                FileOutputStream fout = new FileOutputStream(fd);
18446                BufferedOutputStream str = new BufferedOutputStream(fout);
18447                XmlSerializer serializer = new FastXmlSerializer();
18448                try {
18449                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18450                    serializer.startDocument(null, true);
18451                    serializer.setFeature(
18452                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18453                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18454                    serializer.endDocument();
18455                    serializer.flush();
18456                } catch (IllegalArgumentException e) {
18457                    pw.println("Failed writing: " + e);
18458                } catch (IllegalStateException e) {
18459                    pw.println("Failed writing: " + e);
18460                } catch (IOException e) {
18461                    pw.println("Failed writing: " + e);
18462                }
18463            }
18464
18465            if (!checkin
18466                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18467                    && packageName == null) {
18468                pw.println();
18469                int count = mSettings.mPackages.size();
18470                if (count == 0) {
18471                    pw.println("No applications!");
18472                    pw.println();
18473                } else {
18474                    final String prefix = "  ";
18475                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18476                    if (allPackageSettings.size() == 0) {
18477                        pw.println("No domain preferred apps!");
18478                        pw.println();
18479                    } else {
18480                        pw.println("App verification status:");
18481                        pw.println();
18482                        count = 0;
18483                        for (PackageSetting ps : allPackageSettings) {
18484                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18485                            if (ivi == null || ivi.getPackageName() == null) continue;
18486                            pw.println(prefix + "Package: " + ivi.getPackageName());
18487                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18488                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18489                            pw.println();
18490                            count++;
18491                        }
18492                        if (count == 0) {
18493                            pw.println(prefix + "No app verification established.");
18494                            pw.println();
18495                        }
18496                        for (int userId : sUserManager.getUserIds()) {
18497                            pw.println("App linkages for user " + userId + ":");
18498                            pw.println();
18499                            count = 0;
18500                            for (PackageSetting ps : allPackageSettings) {
18501                                final long status = ps.getDomainVerificationStatusForUser(userId);
18502                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18503                                    continue;
18504                                }
18505                                pw.println(prefix + "Package: " + ps.name);
18506                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18507                                String statusStr = IntentFilterVerificationInfo.
18508                                        getStatusStringFromValue(status);
18509                                pw.println(prefix + "Status:  " + statusStr);
18510                                pw.println();
18511                                count++;
18512                            }
18513                            if (count == 0) {
18514                                pw.println(prefix + "No configured app linkages.");
18515                                pw.println();
18516                            }
18517                        }
18518                    }
18519                }
18520            }
18521
18522            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18523                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18524                if (packageName == null && permissionNames == null) {
18525                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18526                        if (iperm == 0) {
18527                            if (dumpState.onTitlePrinted())
18528                                pw.println();
18529                            pw.println("AppOp Permissions:");
18530                        }
18531                        pw.print("  AppOp Permission ");
18532                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18533                        pw.println(":");
18534                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18535                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18536                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18537                        }
18538                    }
18539                }
18540            }
18541
18542            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18543                boolean printedSomething = false;
18544                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18545                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18546                        continue;
18547                    }
18548                    if (!printedSomething) {
18549                        if (dumpState.onTitlePrinted())
18550                            pw.println();
18551                        pw.println("Registered ContentProviders:");
18552                        printedSomething = true;
18553                    }
18554                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18555                    pw.print("    "); pw.println(p.toString());
18556                }
18557                printedSomething = false;
18558                for (Map.Entry<String, PackageParser.Provider> entry :
18559                        mProvidersByAuthority.entrySet()) {
18560                    PackageParser.Provider p = entry.getValue();
18561                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18562                        continue;
18563                    }
18564                    if (!printedSomething) {
18565                        if (dumpState.onTitlePrinted())
18566                            pw.println();
18567                        pw.println("ContentProvider Authorities:");
18568                        printedSomething = true;
18569                    }
18570                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18571                    pw.print("    "); pw.println(p.toString());
18572                    if (p.info != null && p.info.applicationInfo != null) {
18573                        final String appInfo = p.info.applicationInfo.toString();
18574                        pw.print("      applicationInfo="); pw.println(appInfo);
18575                    }
18576                }
18577            }
18578
18579            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18580                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18581            }
18582
18583            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18584                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18585            }
18586
18587            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18588                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18589            }
18590
18591            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18592                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18593            }
18594
18595            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18596                // XXX should handle packageName != null by dumping only install data that
18597                // the given package is involved with.
18598                if (dumpState.onTitlePrinted()) pw.println();
18599                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18600            }
18601
18602            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18603                // XXX should handle packageName != null by dumping only install data that
18604                // the given package is involved with.
18605                if (dumpState.onTitlePrinted()) pw.println();
18606
18607                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18608                ipw.println();
18609                ipw.println("Frozen packages:");
18610                ipw.increaseIndent();
18611                if (mFrozenPackages.size() == 0) {
18612                    ipw.println("(none)");
18613                } else {
18614                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18615                        ipw.println(mFrozenPackages.valueAt(i));
18616                    }
18617                }
18618                ipw.decreaseIndent();
18619            }
18620
18621            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18622                if (dumpState.onTitlePrinted()) pw.println();
18623                dumpDexoptStateLPr(pw, packageName);
18624            }
18625
18626            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18627                if (dumpState.onTitlePrinted()) pw.println();
18628                dumpCompilerStatsLPr(pw, packageName);
18629            }
18630
18631            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18632                if (dumpState.onTitlePrinted()) pw.println();
18633                mSettings.dumpReadMessagesLPr(pw, dumpState);
18634
18635                pw.println();
18636                pw.println("Package warning messages:");
18637                BufferedReader in = null;
18638                String line = null;
18639                try {
18640                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18641                    while ((line = in.readLine()) != null) {
18642                        if (line.contains("ignored: updated version")) continue;
18643                        pw.println(line);
18644                    }
18645                } catch (IOException ignored) {
18646                } finally {
18647                    IoUtils.closeQuietly(in);
18648                }
18649            }
18650
18651            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18652                BufferedReader in = null;
18653                String line = null;
18654                try {
18655                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18656                    while ((line = in.readLine()) != null) {
18657                        if (line.contains("ignored: updated version")) continue;
18658                        pw.print("msg,");
18659                        pw.println(line);
18660                    }
18661                } catch (IOException ignored) {
18662                } finally {
18663                    IoUtils.closeQuietly(in);
18664                }
18665            }
18666        }
18667    }
18668
18669    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18670        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18671        ipw.println();
18672        ipw.println("Dexopt state:");
18673        ipw.increaseIndent();
18674        Collection<PackageParser.Package> packages = null;
18675        if (packageName != null) {
18676            PackageParser.Package targetPackage = mPackages.get(packageName);
18677            if (targetPackage != null) {
18678                packages = Collections.singletonList(targetPackage);
18679            } else {
18680                ipw.println("Unable to find package: " + packageName);
18681                return;
18682            }
18683        } else {
18684            packages = mPackages.values();
18685        }
18686
18687        for (PackageParser.Package pkg : packages) {
18688            ipw.println("[" + pkg.packageName + "]");
18689            ipw.increaseIndent();
18690            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18691            ipw.decreaseIndent();
18692        }
18693    }
18694
18695    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18696        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18697        ipw.println();
18698        ipw.println("Compiler stats:");
18699        ipw.increaseIndent();
18700        Collection<PackageParser.Package> packages = null;
18701        if (packageName != null) {
18702            PackageParser.Package targetPackage = mPackages.get(packageName);
18703            if (targetPackage != null) {
18704                packages = Collections.singletonList(targetPackage);
18705            } else {
18706                ipw.println("Unable to find package: " + packageName);
18707                return;
18708            }
18709        } else {
18710            packages = mPackages.values();
18711        }
18712
18713        for (PackageParser.Package pkg : packages) {
18714            ipw.println("[" + pkg.packageName + "]");
18715            ipw.increaseIndent();
18716
18717            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18718            if (stats == null) {
18719                ipw.println("(No recorded stats)");
18720            } else {
18721                stats.dump(ipw);
18722            }
18723            ipw.decreaseIndent();
18724        }
18725    }
18726
18727    private String dumpDomainString(String packageName) {
18728        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18729                .getList();
18730        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18731
18732        ArraySet<String> result = new ArraySet<>();
18733        if (iviList.size() > 0) {
18734            for (IntentFilterVerificationInfo ivi : iviList) {
18735                for (String host : ivi.getDomains()) {
18736                    result.add(host);
18737                }
18738            }
18739        }
18740        if (filters != null && filters.size() > 0) {
18741            for (IntentFilter filter : filters) {
18742                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18743                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18744                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18745                    result.addAll(filter.getHostsList());
18746                }
18747            }
18748        }
18749
18750        StringBuilder sb = new StringBuilder(result.size() * 16);
18751        for (String domain : result) {
18752            if (sb.length() > 0) sb.append(" ");
18753            sb.append(domain);
18754        }
18755        return sb.toString();
18756    }
18757
18758    // ------- apps on sdcard specific code -------
18759    static final boolean DEBUG_SD_INSTALL = false;
18760
18761    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18762
18763    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18764
18765    private boolean mMediaMounted = false;
18766
18767    static String getEncryptKey() {
18768        try {
18769            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18770                    SD_ENCRYPTION_KEYSTORE_NAME);
18771            if (sdEncKey == null) {
18772                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18773                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18774                if (sdEncKey == null) {
18775                    Slog.e(TAG, "Failed to create encryption keys");
18776                    return null;
18777                }
18778            }
18779            return sdEncKey;
18780        } catch (NoSuchAlgorithmException nsae) {
18781            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18782            return null;
18783        } catch (IOException ioe) {
18784            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18785            return null;
18786        }
18787    }
18788
18789    /*
18790     * Update media status on PackageManager.
18791     */
18792    @Override
18793    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18794        int callingUid = Binder.getCallingUid();
18795        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18796            throw new SecurityException("Media status can only be updated by the system");
18797        }
18798        // reader; this apparently protects mMediaMounted, but should probably
18799        // be a different lock in that case.
18800        synchronized (mPackages) {
18801            Log.i(TAG, "Updating external media status from "
18802                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18803                    + (mediaStatus ? "mounted" : "unmounted"));
18804            if (DEBUG_SD_INSTALL)
18805                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18806                        + ", mMediaMounted=" + mMediaMounted);
18807            if (mediaStatus == mMediaMounted) {
18808                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18809                        : 0, -1);
18810                mHandler.sendMessage(msg);
18811                return;
18812            }
18813            mMediaMounted = mediaStatus;
18814        }
18815        // Queue up an async operation since the package installation may take a
18816        // little while.
18817        mHandler.post(new Runnable() {
18818            public void run() {
18819                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18820            }
18821        });
18822    }
18823
18824    /**
18825     * Called by MountService when the initial ASECs to scan are available.
18826     * Should block until all the ASEC containers are finished being scanned.
18827     */
18828    public void scanAvailableAsecs() {
18829        updateExternalMediaStatusInner(true, false, false);
18830    }
18831
18832    /*
18833     * Collect information of applications on external media, map them against
18834     * existing containers and update information based on current mount status.
18835     * Please note that we always have to report status if reportStatus has been
18836     * set to true especially when unloading packages.
18837     */
18838    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18839            boolean externalStorage) {
18840        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18841        int[] uidArr = EmptyArray.INT;
18842
18843        final String[] list = PackageHelper.getSecureContainerList();
18844        if (ArrayUtils.isEmpty(list)) {
18845            Log.i(TAG, "No secure containers found");
18846        } else {
18847            // Process list of secure containers and categorize them
18848            // as active or stale based on their package internal state.
18849
18850            // reader
18851            synchronized (mPackages) {
18852                for (String cid : list) {
18853                    // Leave stages untouched for now; installer service owns them
18854                    if (PackageInstallerService.isStageName(cid)) continue;
18855
18856                    if (DEBUG_SD_INSTALL)
18857                        Log.i(TAG, "Processing container " + cid);
18858                    String pkgName = getAsecPackageName(cid);
18859                    if (pkgName == null) {
18860                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18861                        continue;
18862                    }
18863                    if (DEBUG_SD_INSTALL)
18864                        Log.i(TAG, "Looking for pkg : " + pkgName);
18865
18866                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18867                    if (ps == null) {
18868                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18869                        continue;
18870                    }
18871
18872                    /*
18873                     * Skip packages that are not external if we're unmounting
18874                     * external storage.
18875                     */
18876                    if (externalStorage && !isMounted && !isExternal(ps)) {
18877                        continue;
18878                    }
18879
18880                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18881                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18882                    // The package status is changed only if the code path
18883                    // matches between settings and the container id.
18884                    if (ps.codePathString != null
18885                            && ps.codePathString.startsWith(args.getCodePath())) {
18886                        if (DEBUG_SD_INSTALL) {
18887                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18888                                    + " at code path: " + ps.codePathString);
18889                        }
18890
18891                        // We do have a valid package installed on sdcard
18892                        processCids.put(args, ps.codePathString);
18893                        final int uid = ps.appId;
18894                        if (uid != -1) {
18895                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18896                        }
18897                    } else {
18898                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18899                                + ps.codePathString);
18900                    }
18901                }
18902            }
18903
18904            Arrays.sort(uidArr);
18905        }
18906
18907        // Process packages with valid entries.
18908        if (isMounted) {
18909            if (DEBUG_SD_INSTALL)
18910                Log.i(TAG, "Loading packages");
18911            loadMediaPackages(processCids, uidArr, externalStorage);
18912            startCleaningPackages();
18913            mInstallerService.onSecureContainersAvailable();
18914        } else {
18915            if (DEBUG_SD_INSTALL)
18916                Log.i(TAG, "Unloading packages");
18917            unloadMediaPackages(processCids, uidArr, reportStatus);
18918        }
18919    }
18920
18921    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18922            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18923        final int size = infos.size();
18924        final String[] packageNames = new String[size];
18925        final int[] packageUids = new int[size];
18926        for (int i = 0; i < size; i++) {
18927            final ApplicationInfo info = infos.get(i);
18928            packageNames[i] = info.packageName;
18929            packageUids[i] = info.uid;
18930        }
18931        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18932                finishedReceiver);
18933    }
18934
18935    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18936            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18937        sendResourcesChangedBroadcast(mediaStatus, replacing,
18938                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18939    }
18940
18941    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18942            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18943        int size = pkgList.length;
18944        if (size > 0) {
18945            // Send broadcasts here
18946            Bundle extras = new Bundle();
18947            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18948            if (uidArr != null) {
18949                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18950            }
18951            if (replacing) {
18952                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18953            }
18954            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18955                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18956            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18957        }
18958    }
18959
18960   /*
18961     * Look at potentially valid container ids from processCids If package
18962     * information doesn't match the one on record or package scanning fails,
18963     * the cid is added to list of removeCids. We currently don't delete stale
18964     * containers.
18965     */
18966    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18967            boolean externalStorage) {
18968        ArrayList<String> pkgList = new ArrayList<String>();
18969        Set<AsecInstallArgs> keys = processCids.keySet();
18970
18971        for (AsecInstallArgs args : keys) {
18972            String codePath = processCids.get(args);
18973            if (DEBUG_SD_INSTALL)
18974                Log.i(TAG, "Loading container : " + args.cid);
18975            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18976            try {
18977                // Make sure there are no container errors first.
18978                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18979                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18980                            + " when installing from sdcard");
18981                    continue;
18982                }
18983                // Check code path here.
18984                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18985                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18986                            + " does not match one in settings " + codePath);
18987                    continue;
18988                }
18989                // Parse package
18990                int parseFlags = mDefParseFlags;
18991                if (args.isExternalAsec()) {
18992                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18993                }
18994                if (args.isFwdLocked()) {
18995                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18996                }
18997
18998                synchronized (mInstallLock) {
18999                    PackageParser.Package pkg = null;
19000                    try {
19001                        // Sadly we don't know the package name yet to freeze it
19002                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19003                                SCAN_IGNORE_FROZEN, 0, null);
19004                    } catch (PackageManagerException e) {
19005                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19006                    }
19007                    // Scan the package
19008                    if (pkg != null) {
19009                        /*
19010                         * TODO why is the lock being held? doPostInstall is
19011                         * called in other places without the lock. This needs
19012                         * to be straightened out.
19013                         */
19014                        // writer
19015                        synchronized (mPackages) {
19016                            retCode = PackageManager.INSTALL_SUCCEEDED;
19017                            pkgList.add(pkg.packageName);
19018                            // Post process args
19019                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19020                                    pkg.applicationInfo.uid);
19021                        }
19022                    } else {
19023                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19024                    }
19025                }
19026
19027            } finally {
19028                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19029                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19030                }
19031            }
19032        }
19033        // writer
19034        synchronized (mPackages) {
19035            // If the platform SDK has changed since the last time we booted,
19036            // we need to re-grant app permission to catch any new ones that
19037            // appear. This is really a hack, and means that apps can in some
19038            // cases get permissions that the user didn't initially explicitly
19039            // allow... it would be nice to have some better way to handle
19040            // this situation.
19041            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19042                    : mSettings.getInternalVersion();
19043            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19044                    : StorageManager.UUID_PRIVATE_INTERNAL;
19045
19046            int updateFlags = UPDATE_PERMISSIONS_ALL;
19047            if (ver.sdkVersion != mSdkVersion) {
19048                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19049                        + mSdkVersion + "; regranting permissions for external");
19050                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19051            }
19052            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19053
19054            // Yay, everything is now upgraded
19055            ver.forceCurrent();
19056
19057            // can downgrade to reader
19058            // Persist settings
19059            mSettings.writeLPr();
19060        }
19061        // Send a broadcast to let everyone know we are done processing
19062        if (pkgList.size() > 0) {
19063            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19064        }
19065    }
19066
19067   /*
19068     * Utility method to unload a list of specified containers
19069     */
19070    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19071        // Just unmount all valid containers.
19072        for (AsecInstallArgs arg : cidArgs) {
19073            synchronized (mInstallLock) {
19074                arg.doPostDeleteLI(false);
19075           }
19076       }
19077   }
19078
19079    /*
19080     * Unload packages mounted on external media. This involves deleting package
19081     * data from internal structures, sending broadcasts about disabled packages,
19082     * gc'ing to free up references, unmounting all secure containers
19083     * corresponding to packages on external media, and posting a
19084     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19085     * that we always have to post this message if status has been requested no
19086     * matter what.
19087     */
19088    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19089            final boolean reportStatus) {
19090        if (DEBUG_SD_INSTALL)
19091            Log.i(TAG, "unloading media packages");
19092        ArrayList<String> pkgList = new ArrayList<String>();
19093        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19094        final Set<AsecInstallArgs> keys = processCids.keySet();
19095        for (AsecInstallArgs args : keys) {
19096            String pkgName = args.getPackageName();
19097            if (DEBUG_SD_INSTALL)
19098                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19099            // Delete package internally
19100            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19101            synchronized (mInstallLock) {
19102                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19103                final boolean res;
19104                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19105                        "unloadMediaPackages")) {
19106                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19107                            null);
19108                }
19109                if (res) {
19110                    pkgList.add(pkgName);
19111                } else {
19112                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19113                    failedList.add(args);
19114                }
19115            }
19116        }
19117
19118        // reader
19119        synchronized (mPackages) {
19120            // We didn't update the settings after removing each package;
19121            // write them now for all packages.
19122            mSettings.writeLPr();
19123        }
19124
19125        // We have to absolutely send UPDATED_MEDIA_STATUS only
19126        // after confirming that all the receivers processed the ordered
19127        // broadcast when packages get disabled, force a gc to clean things up.
19128        // and unload all the containers.
19129        if (pkgList.size() > 0) {
19130            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19131                    new IIntentReceiver.Stub() {
19132                public void performReceive(Intent intent, int resultCode, String data,
19133                        Bundle extras, boolean ordered, boolean sticky,
19134                        int sendingUser) throws RemoteException {
19135                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19136                            reportStatus ? 1 : 0, 1, keys);
19137                    mHandler.sendMessage(msg);
19138                }
19139            });
19140        } else {
19141            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19142                    keys);
19143            mHandler.sendMessage(msg);
19144        }
19145    }
19146
19147    private void loadPrivatePackages(final VolumeInfo vol) {
19148        mHandler.post(new Runnable() {
19149            @Override
19150            public void run() {
19151                loadPrivatePackagesInner(vol);
19152            }
19153        });
19154    }
19155
19156    private void loadPrivatePackagesInner(VolumeInfo vol) {
19157        final String volumeUuid = vol.fsUuid;
19158        if (TextUtils.isEmpty(volumeUuid)) {
19159            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19160            return;
19161        }
19162
19163        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19164        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19165        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19166
19167        final VersionInfo ver;
19168        final List<PackageSetting> packages;
19169        synchronized (mPackages) {
19170            ver = mSettings.findOrCreateVersion(volumeUuid);
19171            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19172        }
19173
19174        for (PackageSetting ps : packages) {
19175            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19176            synchronized (mInstallLock) {
19177                final PackageParser.Package pkg;
19178                try {
19179                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19180                    loaded.add(pkg.applicationInfo);
19181
19182                } catch (PackageManagerException e) {
19183                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19184                }
19185
19186                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19187                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19188                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19189                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19190                }
19191            }
19192        }
19193
19194        // Reconcile app data for all started/unlocked users
19195        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19196        final UserManager um = mContext.getSystemService(UserManager.class);
19197        UserManagerInternal umInternal = getUserManagerInternal();
19198        for (UserInfo user : um.getUsers()) {
19199            final int flags;
19200            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19201                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19202            } else if (umInternal.isUserRunning(user.id)) {
19203                flags = StorageManager.FLAG_STORAGE_DE;
19204            } else {
19205                continue;
19206            }
19207
19208            try {
19209                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19210                synchronized (mInstallLock) {
19211                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19212                }
19213            } catch (IllegalStateException e) {
19214                // Device was probably ejected, and we'll process that event momentarily
19215                Slog.w(TAG, "Failed to prepare storage: " + e);
19216            }
19217        }
19218
19219        synchronized (mPackages) {
19220            int updateFlags = UPDATE_PERMISSIONS_ALL;
19221            if (ver.sdkVersion != mSdkVersion) {
19222                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19223                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19224                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19225            }
19226            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19227
19228            // Yay, everything is now upgraded
19229            ver.forceCurrent();
19230
19231            mSettings.writeLPr();
19232        }
19233
19234        for (PackageFreezer freezer : freezers) {
19235            freezer.close();
19236        }
19237
19238        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19239        sendResourcesChangedBroadcast(true, false, loaded, null);
19240    }
19241
19242    private void unloadPrivatePackages(final VolumeInfo vol) {
19243        mHandler.post(new Runnable() {
19244            @Override
19245            public void run() {
19246                unloadPrivatePackagesInner(vol);
19247            }
19248        });
19249    }
19250
19251    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19252        final String volumeUuid = vol.fsUuid;
19253        if (TextUtils.isEmpty(volumeUuid)) {
19254            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19255            return;
19256        }
19257
19258        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19259        synchronized (mInstallLock) {
19260        synchronized (mPackages) {
19261            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19262            for (PackageSetting ps : packages) {
19263                if (ps.pkg == null) continue;
19264
19265                final ApplicationInfo info = ps.pkg.applicationInfo;
19266                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19267                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19268
19269                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19270                        "unloadPrivatePackagesInner")) {
19271                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19272                            false, null)) {
19273                        unloaded.add(info);
19274                    } else {
19275                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19276                    }
19277                }
19278
19279                // Try very hard to release any references to this package
19280                // so we don't risk the system server being killed due to
19281                // open FDs
19282                AttributeCache.instance().removePackage(ps.name);
19283            }
19284
19285            mSettings.writeLPr();
19286        }
19287        }
19288
19289        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19290        sendResourcesChangedBroadcast(false, false, unloaded, null);
19291
19292        // Try very hard to release any references to this path so we don't risk
19293        // the system server being killed due to open FDs
19294        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19295
19296        for (int i = 0; i < 3; i++) {
19297            System.gc();
19298            System.runFinalization();
19299        }
19300    }
19301
19302    /**
19303     * Prepare storage areas for given user on all mounted devices.
19304     */
19305    void prepareUserData(int userId, int userSerial, 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                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19311            }
19312        }
19313    }
19314
19315    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19316            boolean allowRecover) {
19317        // Prepare storage and verify that serial numbers are consistent; if
19318        // there's a mismatch we need to destroy to avoid leaking data
19319        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19320        try {
19321            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19322
19323            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19324                UserManagerService.enforceSerialNumber(
19325                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19326                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19327                    UserManagerService.enforceSerialNumber(
19328                            Environment.getDataSystemDeDirectory(userId), userSerial);
19329                }
19330            }
19331            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19332                UserManagerService.enforceSerialNumber(
19333                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19334                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19335                    UserManagerService.enforceSerialNumber(
19336                            Environment.getDataSystemCeDirectory(userId), userSerial);
19337                }
19338            }
19339
19340            synchronized (mInstallLock) {
19341                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19342            }
19343        } catch (Exception e) {
19344            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19345                    + " because we failed to prepare: " + e);
19346            destroyUserDataLI(volumeUuid, userId,
19347                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19348
19349            if (allowRecover) {
19350                // Try one last time; if we fail again we're really in trouble
19351                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19352            }
19353        }
19354    }
19355
19356    /**
19357     * Destroy storage areas for given user on all mounted devices.
19358     */
19359    void destroyUserData(int userId, int flags) {
19360        synchronized (mInstallLock) {
19361            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19362            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19363                final String volumeUuid = vol.getFsUuid();
19364                destroyUserDataLI(volumeUuid, userId, flags);
19365            }
19366        }
19367    }
19368
19369    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19370        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19371        try {
19372            // Clean up app data, profile data, and media data
19373            mInstaller.destroyUserData(volumeUuid, userId, flags);
19374
19375            // Clean up system data
19376            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19377                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19378                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19379                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19380                }
19381                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19382                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19383                }
19384            }
19385
19386            // Data with special labels is now gone, so finish the job
19387            storage.destroyUserStorage(volumeUuid, userId, flags);
19388
19389        } catch (Exception e) {
19390            logCriticalInfo(Log.WARN,
19391                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19392        }
19393    }
19394
19395    /**
19396     * Examine all users present on given mounted volume, and destroy data
19397     * belonging to users that are no longer valid, or whose user ID has been
19398     * recycled.
19399     */
19400    private void reconcileUsers(String volumeUuid) {
19401        final List<File> files = new ArrayList<>();
19402        Collections.addAll(files, FileUtils
19403                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19404        Collections.addAll(files, FileUtils
19405                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19406        Collections.addAll(files, FileUtils
19407                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19408        Collections.addAll(files, FileUtils
19409                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19410        for (File file : files) {
19411            if (!file.isDirectory()) continue;
19412
19413            final int userId;
19414            final UserInfo info;
19415            try {
19416                userId = Integer.parseInt(file.getName());
19417                info = sUserManager.getUserInfo(userId);
19418            } catch (NumberFormatException e) {
19419                Slog.w(TAG, "Invalid user directory " + file);
19420                continue;
19421            }
19422
19423            boolean destroyUser = false;
19424            if (info == null) {
19425                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19426                        + " because no matching user was found");
19427                destroyUser = true;
19428            } else if (!mOnlyCore) {
19429                try {
19430                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19431                } catch (IOException e) {
19432                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19433                            + " because we failed to enforce serial number: " + e);
19434                    destroyUser = true;
19435                }
19436            }
19437
19438            if (destroyUser) {
19439                synchronized (mInstallLock) {
19440                    destroyUserDataLI(volumeUuid, userId,
19441                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19442                }
19443            }
19444        }
19445    }
19446
19447    private void assertPackageKnown(String volumeUuid, String packageName)
19448            throws PackageManagerException {
19449        synchronized (mPackages) {
19450            final PackageSetting ps = mSettings.mPackages.get(packageName);
19451            if (ps == null) {
19452                throw new PackageManagerException("Package " + packageName + " is unknown");
19453            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19454                throw new PackageManagerException(
19455                        "Package " + packageName + " found on unknown volume " + volumeUuid
19456                                + "; expected volume " + ps.volumeUuid);
19457            }
19458        }
19459    }
19460
19461    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19462            throws PackageManagerException {
19463        synchronized (mPackages) {
19464            final PackageSetting ps = mSettings.mPackages.get(packageName);
19465            if (ps == null) {
19466                throw new PackageManagerException("Package " + packageName + " is unknown");
19467            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19468                throw new PackageManagerException(
19469                        "Package " + packageName + " found on unknown volume " + volumeUuid
19470                                + "; expected volume " + ps.volumeUuid);
19471            } else if (!ps.getInstalled(userId)) {
19472                throw new PackageManagerException(
19473                        "Package " + packageName + " not installed for user " + userId);
19474            }
19475        }
19476    }
19477
19478    /**
19479     * Examine all apps present on given mounted volume, and destroy apps that
19480     * aren't expected, either due to uninstallation or reinstallation on
19481     * another volume.
19482     */
19483    private void reconcileApps(String volumeUuid) {
19484        final File[] files = FileUtils
19485                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19486        for (File file : files) {
19487            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19488                    && !PackageInstallerService.isStageName(file.getName());
19489            if (!isPackage) {
19490                // Ignore entries which are not packages
19491                continue;
19492            }
19493
19494            try {
19495                final PackageLite pkg = PackageParser.parsePackageLite(file,
19496                        PackageParser.PARSE_MUST_BE_APK);
19497                assertPackageKnown(volumeUuid, pkg.packageName);
19498
19499            } catch (PackageParserException | PackageManagerException e) {
19500                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19501                synchronized (mInstallLock) {
19502                    removeCodePathLI(file);
19503                }
19504            }
19505        }
19506    }
19507
19508    /**
19509     * Reconcile all app data for the given user.
19510     * <p>
19511     * Verifies that directories exist and that ownership and labeling is
19512     * correct for all installed apps on all mounted volumes.
19513     */
19514    void reconcileAppsData(int userId, int flags) {
19515        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19516        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19517            final String volumeUuid = vol.getFsUuid();
19518            synchronized (mInstallLock) {
19519                reconcileAppsDataLI(volumeUuid, userId, flags);
19520            }
19521        }
19522    }
19523
19524    /**
19525     * Reconcile all app data on given mounted volume.
19526     * <p>
19527     * Destroys app data that isn't expected, either due to uninstallation or
19528     * reinstallation on another volume.
19529     * <p>
19530     * Verifies that directories exist and that ownership and labeling is
19531     * correct for all installed apps.
19532     */
19533    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19534        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19535                + Integer.toHexString(flags));
19536
19537        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19538        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19539
19540        boolean restoreconNeeded = false;
19541
19542        // First look for stale data that doesn't belong, and check if things
19543        // have changed since we did our last restorecon
19544        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19545            if (StorageManager.isFileEncryptedNativeOrEmulated()
19546                    && !StorageManager.isUserKeyUnlocked(userId)) {
19547                throw new RuntimeException(
19548                        "Yikes, someone asked us to reconcile CE storage while " + userId
19549                                + " was still locked; this would have caused massive data loss!");
19550            }
19551
19552            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19553
19554            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19555            for (File file : files) {
19556                final String packageName = file.getName();
19557                try {
19558                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19559                } catch (PackageManagerException e) {
19560                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19561                    try {
19562                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19563                                StorageManager.FLAG_STORAGE_CE, 0);
19564                    } catch (InstallerException e2) {
19565                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19566                    }
19567                }
19568            }
19569        }
19570        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19571            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19572
19573            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19574            for (File file : files) {
19575                final String packageName = file.getName();
19576                try {
19577                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19578                } catch (PackageManagerException e) {
19579                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19580                    try {
19581                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19582                                StorageManager.FLAG_STORAGE_DE, 0);
19583                    } catch (InstallerException e2) {
19584                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19585                    }
19586                }
19587            }
19588        }
19589
19590        // Ensure that data directories are ready to roll for all packages
19591        // installed for this volume and user
19592        final List<PackageSetting> packages;
19593        synchronized (mPackages) {
19594            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19595        }
19596        int preparedCount = 0;
19597        for (PackageSetting ps : packages) {
19598            final String packageName = ps.name;
19599            if (ps.pkg == null) {
19600                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19601                // TODO: might be due to legacy ASEC apps; we should circle back
19602                // and reconcile again once they're scanned
19603                continue;
19604            }
19605
19606            if (ps.getInstalled(userId)) {
19607                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19608
19609                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19610                    // We may have just shuffled around app data directories, so
19611                    // prepare them one more time
19612                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19613                }
19614
19615                preparedCount++;
19616            }
19617        }
19618
19619        if (restoreconNeeded) {
19620            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19621                SELinuxMMAC.setRestoreconDone(ceDir);
19622            }
19623            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19624                SELinuxMMAC.setRestoreconDone(deDir);
19625            }
19626        }
19627
19628        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19629                + " packages; restoreconNeeded was " + restoreconNeeded);
19630    }
19631
19632    /**
19633     * Prepare app data for the given app just after it was installed or
19634     * upgraded. This method carefully only touches users that it's installed
19635     * for, and it forces a restorecon to handle any seinfo changes.
19636     * <p>
19637     * Verifies that directories exist and that ownership and labeling is
19638     * correct for all installed apps. If there is an ownership mismatch, it
19639     * will try recovering system apps by wiping data; third-party app data is
19640     * left intact.
19641     * <p>
19642     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19643     */
19644    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19645        final PackageSetting ps;
19646        synchronized (mPackages) {
19647            ps = mSettings.mPackages.get(pkg.packageName);
19648            mSettings.writeKernelMappingLPr(ps);
19649        }
19650
19651        final UserManager um = mContext.getSystemService(UserManager.class);
19652        UserManagerInternal umInternal = getUserManagerInternal();
19653        for (UserInfo user : um.getUsers()) {
19654            final int flags;
19655            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19656                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19657            } else if (umInternal.isUserRunning(user.id)) {
19658                flags = StorageManager.FLAG_STORAGE_DE;
19659            } else {
19660                continue;
19661            }
19662
19663            if (ps.getInstalled(user.id)) {
19664                // Whenever an app changes, force a restorecon of its data
19665                // TODO: when user data is locked, mark that we're still dirty
19666                prepareAppDataLIF(pkg, user.id, flags, true);
19667            }
19668        }
19669    }
19670
19671    /**
19672     * Prepare app data for the given app.
19673     * <p>
19674     * Verifies that directories exist and that ownership and labeling is
19675     * correct for all installed apps. If there is an ownership mismatch, this
19676     * will try recovering system apps by wiping data; third-party app data is
19677     * left intact.
19678     */
19679    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19680            boolean restoreconNeeded) {
19681        if (pkg == null) {
19682            Slog.wtf(TAG, "Package was null!", new Throwable());
19683            return;
19684        }
19685        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19686        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19687        for (int i = 0; i < childCount; i++) {
19688            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19689        }
19690    }
19691
19692    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19693            boolean restoreconNeeded) {
19694        if (DEBUG_APP_DATA) {
19695            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19696                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19697        }
19698
19699        final String volumeUuid = pkg.volumeUuid;
19700        final String packageName = pkg.packageName;
19701        final ApplicationInfo app = pkg.applicationInfo;
19702        final int appId = UserHandle.getAppId(app.uid);
19703
19704        Preconditions.checkNotNull(app.seinfo);
19705
19706        try {
19707            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19708                    appId, app.seinfo, app.targetSdkVersion);
19709        } catch (InstallerException e) {
19710            if (app.isSystemApp()) {
19711                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19712                        + ", but trying to recover: " + e);
19713                destroyAppDataLeafLIF(pkg, userId, flags);
19714                try {
19715                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19716                            appId, app.seinfo, app.targetSdkVersion);
19717                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19718                } catch (InstallerException e2) {
19719                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19720                }
19721            } else {
19722                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19723            }
19724        }
19725
19726        if (restoreconNeeded) {
19727            try {
19728                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19729                        app.seinfo);
19730            } catch (InstallerException e) {
19731                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19732            }
19733        }
19734
19735        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19736            try {
19737                // CE storage is unlocked right now, so read out the inode and
19738                // remember for use later when it's locked
19739                // TODO: mark this structure as dirty so we persist it!
19740                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19741                        StorageManager.FLAG_STORAGE_CE);
19742                synchronized (mPackages) {
19743                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19744                    if (ps != null) {
19745                        ps.setCeDataInode(ceDataInode, userId);
19746                    }
19747                }
19748            } catch (InstallerException e) {
19749                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19750            }
19751        }
19752
19753        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19754    }
19755
19756    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19757        if (pkg == null) {
19758            Slog.wtf(TAG, "Package was null!", new Throwable());
19759            return;
19760        }
19761        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19762        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19763        for (int i = 0; i < childCount; i++) {
19764            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19765        }
19766    }
19767
19768    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19769        final String volumeUuid = pkg.volumeUuid;
19770        final String packageName = pkg.packageName;
19771        final ApplicationInfo app = pkg.applicationInfo;
19772
19773        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19774            // Create a native library symlink only if we have native libraries
19775            // and if the native libraries are 32 bit libraries. We do not provide
19776            // this symlink for 64 bit libraries.
19777            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19778                final String nativeLibPath = app.nativeLibraryDir;
19779                try {
19780                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19781                            nativeLibPath, userId);
19782                } catch (InstallerException e) {
19783                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19784                }
19785            }
19786        }
19787    }
19788
19789    /**
19790     * For system apps on non-FBE devices, this method migrates any existing
19791     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19792     * requested by the app.
19793     */
19794    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19795        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19796                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19797            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19798                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19799            try {
19800                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19801                        storageTarget);
19802            } catch (InstallerException e) {
19803                logCriticalInfo(Log.WARN,
19804                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19805            }
19806            return true;
19807        } else {
19808            return false;
19809        }
19810    }
19811
19812    public PackageFreezer freezePackage(String packageName, String killReason) {
19813        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19814    }
19815
19816    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19817        return new PackageFreezer(packageName, userId, killReason);
19818    }
19819
19820    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19821            String killReason) {
19822        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19823    }
19824
19825    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19826            String killReason) {
19827        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19828            return new PackageFreezer();
19829        } else {
19830            return freezePackage(packageName, userId, killReason);
19831        }
19832    }
19833
19834    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19835            String killReason) {
19836        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19837    }
19838
19839    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19840            String killReason) {
19841        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19842            return new PackageFreezer();
19843        } else {
19844            return freezePackage(packageName, userId, killReason);
19845        }
19846    }
19847
19848    /**
19849     * Class that freezes and kills the given package upon creation, and
19850     * unfreezes it upon closing. This is typically used when doing surgery on
19851     * app code/data to prevent the app from running while you're working.
19852     */
19853    private class PackageFreezer implements AutoCloseable {
19854        private final String mPackageName;
19855        private final PackageFreezer[] mChildren;
19856
19857        private final boolean mWeFroze;
19858
19859        private final AtomicBoolean mClosed = new AtomicBoolean();
19860        private final CloseGuard mCloseGuard = CloseGuard.get();
19861
19862        /**
19863         * Create and return a stub freezer that doesn't actually do anything,
19864         * typically used when someone requested
19865         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19866         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19867         */
19868        public PackageFreezer() {
19869            mPackageName = null;
19870            mChildren = null;
19871            mWeFroze = false;
19872            mCloseGuard.open("close");
19873        }
19874
19875        public PackageFreezer(String packageName, int userId, String killReason) {
19876            synchronized (mPackages) {
19877                mPackageName = packageName;
19878                mWeFroze = mFrozenPackages.add(mPackageName);
19879
19880                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19881                if (ps != null) {
19882                    killApplication(ps.name, ps.appId, userId, killReason);
19883                }
19884
19885                final PackageParser.Package p = mPackages.get(packageName);
19886                if (p != null && p.childPackages != null) {
19887                    final int N = p.childPackages.size();
19888                    mChildren = new PackageFreezer[N];
19889                    for (int i = 0; i < N; i++) {
19890                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19891                                userId, killReason);
19892                    }
19893                } else {
19894                    mChildren = null;
19895                }
19896            }
19897            mCloseGuard.open("close");
19898        }
19899
19900        @Override
19901        protected void finalize() throws Throwable {
19902            try {
19903                mCloseGuard.warnIfOpen();
19904                close();
19905            } finally {
19906                super.finalize();
19907            }
19908        }
19909
19910        @Override
19911        public void close() {
19912            mCloseGuard.close();
19913            if (mClosed.compareAndSet(false, true)) {
19914                synchronized (mPackages) {
19915                    if (mWeFroze) {
19916                        mFrozenPackages.remove(mPackageName);
19917                    }
19918
19919                    if (mChildren != null) {
19920                        for (PackageFreezer freezer : mChildren) {
19921                            freezer.close();
19922                        }
19923                    }
19924                }
19925            }
19926        }
19927    }
19928
19929    /**
19930     * Verify that given package is currently frozen.
19931     */
19932    private void checkPackageFrozen(String packageName) {
19933        synchronized (mPackages) {
19934            if (!mFrozenPackages.contains(packageName)) {
19935                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19936            }
19937        }
19938    }
19939
19940    @Override
19941    public int movePackage(final String packageName, final String volumeUuid) {
19942        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19943
19944        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19945        final int moveId = mNextMoveId.getAndIncrement();
19946        mHandler.post(new Runnable() {
19947            @Override
19948            public void run() {
19949                try {
19950                    movePackageInternal(packageName, volumeUuid, moveId, user);
19951                } catch (PackageManagerException e) {
19952                    Slog.w(TAG, "Failed to move " + packageName, e);
19953                    mMoveCallbacks.notifyStatusChanged(moveId,
19954                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19955                }
19956            }
19957        });
19958        return moveId;
19959    }
19960
19961    private void movePackageInternal(final String packageName, final String volumeUuid,
19962            final int moveId, UserHandle user) throws PackageManagerException {
19963        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19964        final PackageManager pm = mContext.getPackageManager();
19965
19966        final boolean currentAsec;
19967        final String currentVolumeUuid;
19968        final File codeFile;
19969        final String installerPackageName;
19970        final String packageAbiOverride;
19971        final int appId;
19972        final String seinfo;
19973        final String label;
19974        final int targetSdkVersion;
19975        final PackageFreezer freezer;
19976        final int[] installedUserIds;
19977
19978        // reader
19979        synchronized (mPackages) {
19980            final PackageParser.Package pkg = mPackages.get(packageName);
19981            final PackageSetting ps = mSettings.mPackages.get(packageName);
19982            if (pkg == null || ps == null) {
19983                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19984            }
19985
19986            if (pkg.applicationInfo.isSystemApp()) {
19987                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19988                        "Cannot move system application");
19989            }
19990
19991            if (pkg.applicationInfo.isExternalAsec()) {
19992                currentAsec = true;
19993                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19994            } else if (pkg.applicationInfo.isForwardLocked()) {
19995                currentAsec = true;
19996                currentVolumeUuid = "forward_locked";
19997            } else {
19998                currentAsec = false;
19999                currentVolumeUuid = ps.volumeUuid;
20000
20001                final File probe = new File(pkg.codePath);
20002                final File probeOat = new File(probe, "oat");
20003                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20004                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20005                            "Move only supported for modern cluster style installs");
20006                }
20007            }
20008
20009            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20010                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20011                        "Package already moved to " + volumeUuid);
20012            }
20013            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20014                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20015                        "Device admin cannot be moved");
20016            }
20017
20018            if (mFrozenPackages.contains(packageName)) {
20019                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20020                        "Failed to move already frozen package");
20021            }
20022
20023            codeFile = new File(pkg.codePath);
20024            installerPackageName = ps.installerPackageName;
20025            packageAbiOverride = ps.cpuAbiOverrideString;
20026            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20027            seinfo = pkg.applicationInfo.seinfo;
20028            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20029            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20030            freezer = freezePackage(packageName, "movePackageInternal");
20031            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20032        }
20033
20034        final Bundle extras = new Bundle();
20035        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20036        extras.putString(Intent.EXTRA_TITLE, label);
20037        mMoveCallbacks.notifyCreated(moveId, extras);
20038
20039        int installFlags;
20040        final boolean moveCompleteApp;
20041        final File measurePath;
20042
20043        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20044            installFlags = INSTALL_INTERNAL;
20045            moveCompleteApp = !currentAsec;
20046            measurePath = Environment.getDataAppDirectory(volumeUuid);
20047        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20048            installFlags = INSTALL_EXTERNAL;
20049            moveCompleteApp = false;
20050            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20051        } else {
20052            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20053            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20054                    || !volume.isMountedWritable()) {
20055                freezer.close();
20056                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20057                        "Move location not mounted private volume");
20058            }
20059
20060            Preconditions.checkState(!currentAsec);
20061
20062            installFlags = INSTALL_INTERNAL;
20063            moveCompleteApp = true;
20064            measurePath = Environment.getDataAppDirectory(volumeUuid);
20065        }
20066
20067        final PackageStats stats = new PackageStats(null, -1);
20068        synchronized (mInstaller) {
20069            for (int userId : installedUserIds) {
20070                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20071                    freezer.close();
20072                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20073                            "Failed to measure package size");
20074                }
20075            }
20076        }
20077
20078        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20079                + stats.dataSize);
20080
20081        final long startFreeBytes = measurePath.getFreeSpace();
20082        final long sizeBytes;
20083        if (moveCompleteApp) {
20084            sizeBytes = stats.codeSize + stats.dataSize;
20085        } else {
20086            sizeBytes = stats.codeSize;
20087        }
20088
20089        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20090            freezer.close();
20091            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20092                    "Not enough free space to move");
20093        }
20094
20095        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20096
20097        final CountDownLatch installedLatch = new CountDownLatch(1);
20098        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20099            @Override
20100            public void onUserActionRequired(Intent intent) throws RemoteException {
20101                throw new IllegalStateException();
20102            }
20103
20104            @Override
20105            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20106                    Bundle extras) throws RemoteException {
20107                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20108                        + PackageManager.installStatusToString(returnCode, msg));
20109
20110                installedLatch.countDown();
20111                freezer.close();
20112
20113                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20114                switch (status) {
20115                    case PackageInstaller.STATUS_SUCCESS:
20116                        mMoveCallbacks.notifyStatusChanged(moveId,
20117                                PackageManager.MOVE_SUCCEEDED);
20118                        break;
20119                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20120                        mMoveCallbacks.notifyStatusChanged(moveId,
20121                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20122                        break;
20123                    default:
20124                        mMoveCallbacks.notifyStatusChanged(moveId,
20125                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20126                        break;
20127                }
20128            }
20129        };
20130
20131        final MoveInfo move;
20132        if (moveCompleteApp) {
20133            // Kick off a thread to report progress estimates
20134            new Thread() {
20135                @Override
20136                public void run() {
20137                    while (true) {
20138                        try {
20139                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20140                                break;
20141                            }
20142                        } catch (InterruptedException ignored) {
20143                        }
20144
20145                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20146                        final int progress = 10 + (int) MathUtils.constrain(
20147                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20148                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20149                    }
20150                }
20151            }.start();
20152
20153            final String dataAppName = codeFile.getName();
20154            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20155                    dataAppName, appId, seinfo, targetSdkVersion);
20156        } else {
20157            move = null;
20158        }
20159
20160        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20161
20162        final Message msg = mHandler.obtainMessage(INIT_COPY);
20163        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20164        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20165                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20166                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20167        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20168        msg.obj = params;
20169
20170        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20171                System.identityHashCode(msg.obj));
20172        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20173                System.identityHashCode(msg.obj));
20174
20175        mHandler.sendMessage(msg);
20176    }
20177
20178    @Override
20179    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20180        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20181
20182        final int realMoveId = mNextMoveId.getAndIncrement();
20183        final Bundle extras = new Bundle();
20184        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20185        mMoveCallbacks.notifyCreated(realMoveId, extras);
20186
20187        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20188            @Override
20189            public void onCreated(int moveId, Bundle extras) {
20190                // Ignored
20191            }
20192
20193            @Override
20194            public void onStatusChanged(int moveId, int status, long estMillis) {
20195                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20196            }
20197        };
20198
20199        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20200        storage.setPrimaryStorageUuid(volumeUuid, callback);
20201        return realMoveId;
20202    }
20203
20204    @Override
20205    public int getMoveStatus(int moveId) {
20206        mContext.enforceCallingOrSelfPermission(
20207                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20208        return mMoveCallbacks.mLastStatus.get(moveId);
20209    }
20210
20211    @Override
20212    public void registerMoveCallback(IPackageMoveObserver callback) {
20213        mContext.enforceCallingOrSelfPermission(
20214                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20215        mMoveCallbacks.register(callback);
20216    }
20217
20218    @Override
20219    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20220        mContext.enforceCallingOrSelfPermission(
20221                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20222        mMoveCallbacks.unregister(callback);
20223    }
20224
20225    @Override
20226    public boolean setInstallLocation(int loc) {
20227        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20228                null);
20229        if (getInstallLocation() == loc) {
20230            return true;
20231        }
20232        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20233                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20234            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20235                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20236            return true;
20237        }
20238        return false;
20239   }
20240
20241    @Override
20242    public int getInstallLocation() {
20243        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20244                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20245                PackageHelper.APP_INSTALL_AUTO);
20246    }
20247
20248    /** Called by UserManagerService */
20249    void cleanUpUser(UserManagerService userManager, int userHandle) {
20250        synchronized (mPackages) {
20251            mDirtyUsers.remove(userHandle);
20252            mUserNeedsBadging.delete(userHandle);
20253            mSettings.removeUserLPw(userHandle);
20254            mPendingBroadcasts.remove(userHandle);
20255            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20256            removeUnusedPackagesLPw(userManager, userHandle);
20257        }
20258    }
20259
20260    /**
20261     * We're removing userHandle and would like to remove any downloaded packages
20262     * that are no longer in use by any other user.
20263     * @param userHandle the user being removed
20264     */
20265    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20266        final boolean DEBUG_CLEAN_APKS = false;
20267        int [] users = userManager.getUserIds();
20268        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20269        while (psit.hasNext()) {
20270            PackageSetting ps = psit.next();
20271            if (ps.pkg == null) {
20272                continue;
20273            }
20274            final String packageName = ps.pkg.packageName;
20275            // Skip over if system app
20276            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20277                continue;
20278            }
20279            if (DEBUG_CLEAN_APKS) {
20280                Slog.i(TAG, "Checking package " + packageName);
20281            }
20282            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20283            if (keep) {
20284                if (DEBUG_CLEAN_APKS) {
20285                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20286                }
20287            } else {
20288                for (int i = 0; i < users.length; i++) {
20289                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20290                        keep = true;
20291                        if (DEBUG_CLEAN_APKS) {
20292                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20293                                    + users[i]);
20294                        }
20295                        break;
20296                    }
20297                }
20298            }
20299            if (!keep) {
20300                if (DEBUG_CLEAN_APKS) {
20301                    Slog.i(TAG, "  Removing package " + packageName);
20302                }
20303                mHandler.post(new Runnable() {
20304                    public void run() {
20305                        deletePackageX(packageName, userHandle, 0);
20306                    } //end run
20307                });
20308            }
20309        }
20310    }
20311
20312    /** Called by UserManagerService */
20313    void createNewUser(int userId) {
20314        synchronized (mInstallLock) {
20315            mSettings.createNewUserLI(this, mInstaller, userId);
20316        }
20317        synchronized (mPackages) {
20318            scheduleWritePackageRestrictionsLocked(userId);
20319            scheduleWritePackageListLocked(userId);
20320            applyFactoryDefaultBrowserLPw(userId);
20321            primeDomainVerificationsLPw(userId);
20322        }
20323    }
20324
20325    void onNewUserCreated(final int userId) {
20326        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20327        // If permission review for legacy apps is required, we represent
20328        // dagerous permissions for such apps as always granted runtime
20329        // permissions to keep per user flag state whether review is needed.
20330        // Hence, if a new user is added we have to propagate dangerous
20331        // permission grants for these legacy apps.
20332        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20333            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20334                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20335        }
20336    }
20337
20338    @Override
20339    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20340        mContext.enforceCallingOrSelfPermission(
20341                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20342                "Only package verification agents can read the verifier device identity");
20343
20344        synchronized (mPackages) {
20345            return mSettings.getVerifierDeviceIdentityLPw();
20346        }
20347    }
20348
20349    @Override
20350    public void setPermissionEnforced(String permission, boolean enforced) {
20351        // TODO: Now that we no longer change GID for storage, this should to away.
20352        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20353                "setPermissionEnforced");
20354        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20355            synchronized (mPackages) {
20356                if (mSettings.mReadExternalStorageEnforced == null
20357                        || mSettings.mReadExternalStorageEnforced != enforced) {
20358                    mSettings.mReadExternalStorageEnforced = enforced;
20359                    mSettings.writeLPr();
20360                }
20361            }
20362            // kill any non-foreground processes so we restart them and
20363            // grant/revoke the GID.
20364            final IActivityManager am = ActivityManagerNative.getDefault();
20365            if (am != null) {
20366                final long token = Binder.clearCallingIdentity();
20367                try {
20368                    am.killProcessesBelowForeground("setPermissionEnforcement");
20369                } catch (RemoteException e) {
20370                } finally {
20371                    Binder.restoreCallingIdentity(token);
20372                }
20373            }
20374        } else {
20375            throw new IllegalArgumentException("No selective enforcement for " + permission);
20376        }
20377    }
20378
20379    @Override
20380    @Deprecated
20381    public boolean isPermissionEnforced(String permission) {
20382        return true;
20383    }
20384
20385    @Override
20386    public boolean isStorageLow() {
20387        final long token = Binder.clearCallingIdentity();
20388        try {
20389            final DeviceStorageMonitorInternal
20390                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20391            if (dsm != null) {
20392                return dsm.isMemoryLow();
20393            } else {
20394                return false;
20395            }
20396        } finally {
20397            Binder.restoreCallingIdentity(token);
20398        }
20399    }
20400
20401    @Override
20402    public IPackageInstaller getPackageInstaller() {
20403        return mInstallerService;
20404    }
20405
20406    private boolean userNeedsBadging(int userId) {
20407        int index = mUserNeedsBadging.indexOfKey(userId);
20408        if (index < 0) {
20409            final UserInfo userInfo;
20410            final long token = Binder.clearCallingIdentity();
20411            try {
20412                userInfo = sUserManager.getUserInfo(userId);
20413            } finally {
20414                Binder.restoreCallingIdentity(token);
20415            }
20416            final boolean b;
20417            if (userInfo != null && userInfo.isManagedProfile()) {
20418                b = true;
20419            } else {
20420                b = false;
20421            }
20422            mUserNeedsBadging.put(userId, b);
20423            return b;
20424        }
20425        return mUserNeedsBadging.valueAt(index);
20426    }
20427
20428    @Override
20429    public KeySet getKeySetByAlias(String packageName, String alias) {
20430        if (packageName == null || alias == null) {
20431            return null;
20432        }
20433        synchronized(mPackages) {
20434            final PackageParser.Package pkg = mPackages.get(packageName);
20435            if (pkg == null) {
20436                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20437                throw new IllegalArgumentException("Unknown package: " + packageName);
20438            }
20439            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20440            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20441        }
20442    }
20443
20444    @Override
20445    public KeySet getSigningKeySet(String packageName) {
20446        if (packageName == null) {
20447            return null;
20448        }
20449        synchronized(mPackages) {
20450            final PackageParser.Package pkg = mPackages.get(packageName);
20451            if (pkg == null) {
20452                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20453                throw new IllegalArgumentException("Unknown package: " + packageName);
20454            }
20455            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20456                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20457                throw new SecurityException("May not access signing KeySet of other apps.");
20458            }
20459            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20460            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20461        }
20462    }
20463
20464    @Override
20465    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20466        if (packageName == null || ks == null) {
20467            return false;
20468        }
20469        synchronized(mPackages) {
20470            final PackageParser.Package pkg = mPackages.get(packageName);
20471            if (pkg == null) {
20472                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20473                throw new IllegalArgumentException("Unknown package: " + packageName);
20474            }
20475            IBinder ksh = ks.getToken();
20476            if (ksh instanceof KeySetHandle) {
20477                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20478                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20479            }
20480            return false;
20481        }
20482    }
20483
20484    @Override
20485    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20486        if (packageName == null || ks == null) {
20487            return false;
20488        }
20489        synchronized(mPackages) {
20490            final PackageParser.Package pkg = mPackages.get(packageName);
20491            if (pkg == null) {
20492                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20493                throw new IllegalArgumentException("Unknown package: " + packageName);
20494            }
20495            IBinder ksh = ks.getToken();
20496            if (ksh instanceof KeySetHandle) {
20497                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20498                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20499            }
20500            return false;
20501        }
20502    }
20503
20504    private void deletePackageIfUnusedLPr(final String packageName) {
20505        PackageSetting ps = mSettings.mPackages.get(packageName);
20506        if (ps == null) {
20507            return;
20508        }
20509        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20510            // TODO Implement atomic delete if package is unused
20511            // It is currently possible that the package will be deleted even if it is installed
20512            // after this method returns.
20513            mHandler.post(new Runnable() {
20514                public void run() {
20515                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20516                }
20517            });
20518        }
20519    }
20520
20521    /**
20522     * Check and throw if the given before/after packages would be considered a
20523     * downgrade.
20524     */
20525    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20526            throws PackageManagerException {
20527        if (after.versionCode < before.mVersionCode) {
20528            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20529                    "Update version code " + after.versionCode + " is older than current "
20530                    + before.mVersionCode);
20531        } else if (after.versionCode == before.mVersionCode) {
20532            if (after.baseRevisionCode < before.baseRevisionCode) {
20533                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20534                        "Update base revision code " + after.baseRevisionCode
20535                        + " is older than current " + before.baseRevisionCode);
20536            }
20537
20538            if (!ArrayUtils.isEmpty(after.splitNames)) {
20539                for (int i = 0; i < after.splitNames.length; i++) {
20540                    final String splitName = after.splitNames[i];
20541                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20542                    if (j != -1) {
20543                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20544                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20545                                    "Update split " + splitName + " revision code "
20546                                    + after.splitRevisionCodes[i] + " is older than current "
20547                                    + before.splitRevisionCodes[j]);
20548                        }
20549                    }
20550                }
20551            }
20552        }
20553    }
20554
20555    private static class MoveCallbacks extends Handler {
20556        private static final int MSG_CREATED = 1;
20557        private static final int MSG_STATUS_CHANGED = 2;
20558
20559        private final RemoteCallbackList<IPackageMoveObserver>
20560                mCallbacks = new RemoteCallbackList<>();
20561
20562        private final SparseIntArray mLastStatus = new SparseIntArray();
20563
20564        public MoveCallbacks(Looper looper) {
20565            super(looper);
20566        }
20567
20568        public void register(IPackageMoveObserver callback) {
20569            mCallbacks.register(callback);
20570        }
20571
20572        public void unregister(IPackageMoveObserver callback) {
20573            mCallbacks.unregister(callback);
20574        }
20575
20576        @Override
20577        public void handleMessage(Message msg) {
20578            final SomeArgs args = (SomeArgs) msg.obj;
20579            final int n = mCallbacks.beginBroadcast();
20580            for (int i = 0; i < n; i++) {
20581                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20582                try {
20583                    invokeCallback(callback, msg.what, args);
20584                } catch (RemoteException ignored) {
20585                }
20586            }
20587            mCallbacks.finishBroadcast();
20588            args.recycle();
20589        }
20590
20591        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20592                throws RemoteException {
20593            switch (what) {
20594                case MSG_CREATED: {
20595                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20596                    break;
20597                }
20598                case MSG_STATUS_CHANGED: {
20599                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20600                    break;
20601                }
20602            }
20603        }
20604
20605        private void notifyCreated(int moveId, Bundle extras) {
20606            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20607
20608            final SomeArgs args = SomeArgs.obtain();
20609            args.argi1 = moveId;
20610            args.arg2 = extras;
20611            obtainMessage(MSG_CREATED, args).sendToTarget();
20612        }
20613
20614        private void notifyStatusChanged(int moveId, int status) {
20615            notifyStatusChanged(moveId, status, -1);
20616        }
20617
20618        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20619            Slog.v(TAG, "Move " + moveId + " status " + status);
20620
20621            final SomeArgs args = SomeArgs.obtain();
20622            args.argi1 = moveId;
20623            args.argi2 = status;
20624            args.arg3 = estMillis;
20625            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20626
20627            synchronized (mLastStatus) {
20628                mLastStatus.put(moveId, status);
20629            }
20630        }
20631    }
20632
20633    private final static class OnPermissionChangeListeners extends Handler {
20634        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20635
20636        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20637                new RemoteCallbackList<>();
20638
20639        public OnPermissionChangeListeners(Looper looper) {
20640            super(looper);
20641        }
20642
20643        @Override
20644        public void handleMessage(Message msg) {
20645            switch (msg.what) {
20646                case MSG_ON_PERMISSIONS_CHANGED: {
20647                    final int uid = msg.arg1;
20648                    handleOnPermissionsChanged(uid);
20649                } break;
20650            }
20651        }
20652
20653        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20654            mPermissionListeners.register(listener);
20655
20656        }
20657
20658        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20659            mPermissionListeners.unregister(listener);
20660        }
20661
20662        public void onPermissionsChanged(int uid) {
20663            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20664                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20665            }
20666        }
20667
20668        private void handleOnPermissionsChanged(int uid) {
20669            final int count = mPermissionListeners.beginBroadcast();
20670            try {
20671                for (int i = 0; i < count; i++) {
20672                    IOnPermissionsChangeListener callback = mPermissionListeners
20673                            .getBroadcastItem(i);
20674                    try {
20675                        callback.onPermissionsChanged(uid);
20676                    } catch (RemoteException e) {
20677                        Log.e(TAG, "Permission listener is dead", e);
20678                    }
20679                }
20680            } finally {
20681                mPermissionListeners.finishBroadcast();
20682            }
20683        }
20684    }
20685
20686    private class PackageManagerInternalImpl extends PackageManagerInternal {
20687        @Override
20688        public void setLocationPackagesProvider(PackagesProvider provider) {
20689            synchronized (mPackages) {
20690                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20691            }
20692        }
20693
20694        @Override
20695        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20696            synchronized (mPackages) {
20697                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20698            }
20699        }
20700
20701        @Override
20702        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20703            synchronized (mPackages) {
20704                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20705            }
20706        }
20707
20708        @Override
20709        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20710            synchronized (mPackages) {
20711                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20712            }
20713        }
20714
20715        @Override
20716        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20717            synchronized (mPackages) {
20718                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20719            }
20720        }
20721
20722        @Override
20723        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20724            synchronized (mPackages) {
20725                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20726            }
20727        }
20728
20729        @Override
20730        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20731            synchronized (mPackages) {
20732                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20733                        packageName, userId);
20734            }
20735        }
20736
20737        @Override
20738        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20739            synchronized (mPackages) {
20740                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20741                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20742                        packageName, userId);
20743            }
20744        }
20745
20746        @Override
20747        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20748            synchronized (mPackages) {
20749                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20750                        packageName, userId);
20751            }
20752        }
20753
20754        @Override
20755        public void setKeepUninstalledPackages(final List<String> packageList) {
20756            Preconditions.checkNotNull(packageList);
20757            List<String> removedFromList = null;
20758            synchronized (mPackages) {
20759                if (mKeepUninstalledPackages != null) {
20760                    final int packagesCount = mKeepUninstalledPackages.size();
20761                    for (int i = 0; i < packagesCount; i++) {
20762                        String oldPackage = mKeepUninstalledPackages.get(i);
20763                        if (packageList != null && packageList.contains(oldPackage)) {
20764                            continue;
20765                        }
20766                        if (removedFromList == null) {
20767                            removedFromList = new ArrayList<>();
20768                        }
20769                        removedFromList.add(oldPackage);
20770                    }
20771                }
20772                mKeepUninstalledPackages = new ArrayList<>(packageList);
20773                if (removedFromList != null) {
20774                    final int removedCount = removedFromList.size();
20775                    for (int i = 0; i < removedCount; i++) {
20776                        deletePackageIfUnusedLPr(removedFromList.get(i));
20777                    }
20778                }
20779            }
20780        }
20781
20782        @Override
20783        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20784            synchronized (mPackages) {
20785                // If we do not support permission review, done.
20786                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20787                    return false;
20788                }
20789
20790                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20791                if (packageSetting == null) {
20792                    return false;
20793                }
20794
20795                // Permission review applies only to apps not supporting the new permission model.
20796                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20797                    return false;
20798                }
20799
20800                // Legacy apps have the permission and get user consent on launch.
20801                PermissionsState permissionsState = packageSetting.getPermissionsState();
20802                return permissionsState.isPermissionReviewRequired(userId);
20803            }
20804        }
20805
20806        @Override
20807        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20808            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20809        }
20810
20811        @Override
20812        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20813                int userId) {
20814            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20815        }
20816
20817        @Override
20818        public void setDeviceAndProfileOwnerPackages(
20819                int deviceOwnerUserId, String deviceOwnerPackage,
20820                SparseArray<String> profileOwnerPackages) {
20821            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20822                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20823        }
20824
20825        @Override
20826        public boolean isPackageDataProtected(int userId, String packageName) {
20827            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20828        }
20829    }
20830
20831    @Override
20832    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20833        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20834        synchronized (mPackages) {
20835            final long identity = Binder.clearCallingIdentity();
20836            try {
20837                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20838                        packageNames, userId);
20839            } finally {
20840                Binder.restoreCallingIdentity(identity);
20841            }
20842        }
20843    }
20844
20845    private static void enforceSystemOrPhoneCaller(String tag) {
20846        int callingUid = Binder.getCallingUid();
20847        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20848            throw new SecurityException(
20849                    "Cannot call " + tag + " from UID " + callingUid);
20850        }
20851    }
20852
20853    boolean isHistoricalPackageUsageAvailable() {
20854        return mPackageUsage.isHistoricalPackageUsageAvailable();
20855    }
20856
20857    /**
20858     * Return a <b>copy</b> of the collection of packages known to the package manager.
20859     * @return A copy of the values of mPackages.
20860     */
20861    Collection<PackageParser.Package> getPackages() {
20862        synchronized (mPackages) {
20863            return new ArrayList<>(mPackages.values());
20864        }
20865    }
20866
20867    /**
20868     * Logs process start information (including base APK hash) to the security log.
20869     * @hide
20870     */
20871    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20872            String apkFile, int pid) {
20873        if (!SecurityLog.isLoggingEnabled()) {
20874            return;
20875        }
20876        Bundle data = new Bundle();
20877        data.putLong("startTimestamp", System.currentTimeMillis());
20878        data.putString("processName", processName);
20879        data.putInt("uid", uid);
20880        data.putString("seinfo", seinfo);
20881        data.putString("apkFile", apkFile);
20882        data.putInt("pid", pid);
20883        Message msg = mProcessLoggingHandler.obtainMessage(
20884                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20885        msg.setData(data);
20886        mProcessLoggingHandler.sendMessage(msg);
20887    }
20888
20889    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20890        return mCompilerStats.getPackageStats(pkgName);
20891    }
20892
20893    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20894        return getOrCreateCompilerPackageStats(pkg.packageName);
20895    }
20896
20897    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20898        return mCompilerStats.getOrCreatePackageStats(pkgName);
20899    }
20900
20901    public void deleteCompilerPackageStats(String pkgName) {
20902        mCompilerStats.deletePackageStats(pkgName);
20903    }
20904}
20905